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/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 #define DEBUG_TYPE "x86-isel"
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64 SelectionDAG &DAG, SDLoc dl,
65 unsigned vectorWidth) {
66 assert((vectorWidth == 128 || vectorWidth == 256) &&
67 "Unsupported vector width");
68 EVT VT = Vec.getValueType();
69 EVT ElVT = VT.getVectorElementType();
70 unsigned Factor = VT.getSizeInBits()/vectorWidth;
71 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72 VT.getVectorNumElements()/Factor);
74 // Extract from UNDEF is UNDEF.
75 if (Vec.getOpcode() == ISD::UNDEF)
76 return DAG.getUNDEF(ResultVT);
78 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
79 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
81 // This is the index of the first element of the vectorWidth-bit chunk
83 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
86 // If the input is a buildvector just emit a smaller one.
87 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
92 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106 SelectionDAG &DAG, SDLoc dl) {
107 assert((Vec.getValueType().is256BitVector() ||
108 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114 SelectionDAG &DAG, SDLoc dl) {
115 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120 unsigned IdxVal, SelectionDAG &DAG,
121 SDLoc dl, unsigned vectorWidth) {
122 assert((vectorWidth == 128 || vectorWidth == 256) &&
123 "Unsupported vector width");
124 // Inserting UNDEF is Result
125 if (Vec.getOpcode() == ISD::UNDEF)
127 EVT VT = Vec.getValueType();
128 EVT ElVT = VT.getVectorElementType();
129 EVT ResultVT = Result.getValueType();
131 // Insert the relevant vectorWidth bits.
132 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
134 // This is the index of the first element of the vectorWidth-bit chunk
136 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
139 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
143 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference. Idx is an index in the 128 bits
147 /// we want. It need not be aligned to a 128-bit bounday. That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150 unsigned IdxVal, SelectionDAG &DAG,
152 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157 unsigned IdxVal, SelectionDAG &DAG,
159 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168 unsigned NumElems, SelectionDAG &DAG,
170 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175 unsigned NumElems, SelectionDAG &DAG,
177 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
181 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
182 if (TT.isOSBinFormatMachO()) {
183 if (TT.getArch() == Triple::x86_64)
184 return new X86_64MachoTargetObjectFile();
185 return new TargetLoweringObjectFileMachO();
189 return new X86LinuxTargetObjectFile();
190 if (TT.isOSBinFormatELF())
191 return new TargetLoweringObjectFileELF();
192 if (TT.isKnownWindowsMSVCEnvironment())
193 return new X86WindowsTargetObjectFile();
194 if (TT.isOSBinFormatCOFF())
195 return new TargetLoweringObjectFileCOFF();
196 llvm_unreachable("unknown subtarget type");
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
201 Subtarget = &TM.getSubtarget<X86Subtarget>();
202 X86ScalarSSEf64 = Subtarget->hasSSE2();
203 X86ScalarSSEf32 = Subtarget->hasSSE1();
204 TD = getDataLayout();
206 resetOperationActions();
209 void X86TargetLowering::resetOperationActions() {
210 const TargetMachine &TM = getTargetMachine();
211 static bool FirstTimeThrough = true;
213 // If none of the target options have changed, then we don't need to reset the
214 // operation actions.
215 if (!FirstTimeThrough && TO == TM.Options) return;
217 if (!FirstTimeThrough) {
218 // Reinitialize the actions.
220 FirstTimeThrough = false;
225 // Set up the TargetLowering object.
226 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228 // X86 is weird, it always uses i8 for shift amounts and setcc results.
229 setBooleanContents(ZeroOrOneBooleanContent);
230 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233 // For 64-bit since we have so many registers use the ILP scheduler, for
234 // 32-bit code use the register pressure specific scheduling.
235 // For Atom, always use ILP scheduling.
236 if (Subtarget->isAtom())
237 setSchedulingPreference(Sched::ILP);
238 else if (Subtarget->is64Bit())
239 setSchedulingPreference(Sched::ILP);
241 setSchedulingPreference(Sched::RegPressure);
242 const X86RegisterInfo *RegInfo =
243 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246 // Bypass expensive divides on Atom when compiling with O2
247 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248 addBypassSlowDiv(32, 8);
249 if (Subtarget->is64Bit())
250 addBypassSlowDiv(64, 16);
253 if (Subtarget->isTargetKnownWindowsMSVC()) {
254 // Setup Windows compiler runtime calls.
255 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257 setLibcallName(RTLIB::SREM_I64, "_allrem");
258 setLibcallName(RTLIB::UREM_I64, "_aullrem");
259 setLibcallName(RTLIB::MUL_I64, "_allmul");
260 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266 // The _ftol2 runtime function has an unusual calling conv, which
267 // is modeled by a special pseudo-instruction.
268 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
269 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
270 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
274 if (Subtarget->isTargetDarwin()) {
275 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276 setUseUnderscoreSetJmp(false);
277 setUseUnderscoreLongJmp(false);
278 } else if (Subtarget->isTargetWindowsGNU()) {
279 // MS runtime is weird: it exports _setjmp, but longjmp!
280 setUseUnderscoreSetJmp(true);
281 setUseUnderscoreLongJmp(false);
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(true);
287 // Set up the register classes.
288 addRegisterClass(MVT::i8, &X86::GR8RegClass);
289 addRegisterClass(MVT::i16, &X86::GR16RegClass);
290 addRegisterClass(MVT::i32, &X86::GR32RegClass);
291 if (Subtarget->is64Bit())
292 addRegisterClass(MVT::i64, &X86::GR64RegClass);
294 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296 // We don't accept any truncstore of integer registers.
297 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
304 // SETOEQ and SETUNE require checking two conditions.
305 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
315 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
318 if (Subtarget->is64Bit()) {
319 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
320 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
321 } else if (!TM.Options.UseSoftFloat) {
322 // We have an algorithm for SSE2->double, and we turn this into a
323 // 64-bit FILD followed by conditional FADD for other targets.
324 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
325 // We have an algorithm for SSE2, and we turn this into a 64-bit
326 // FILD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
330 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
333 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
335 if (!TM.Options.UseSoftFloat) {
336 // SSE has no i16 to fp conversion, only i32
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
350 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
351 // are Legal, f80 is custom lowered.
352 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
353 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
355 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
358 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
360 if (X86ScalarSSEf32) {
361 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
362 // f32 and f64 cases are Legal, f80 case is not
363 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
365 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
369 // Handle FP_TO_UINT by promoting the destination to a larger signed
371 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
372 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
375 if (Subtarget->is64Bit()) {
376 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
377 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
378 } else if (!TM.Options.UseSoftFloat) {
379 // Since AVX is a superset of SSE3, only check for SSE here.
380 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381 // Expand FP_TO_UINT into a select.
382 // FIXME: We would like to use a Custom expander here eventually to do
383 // the optimal thing for SSE vs. the default expansion in the legalizer.
384 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
386 // With SSE3 we can use fisttpll to convert to a signed i64; without
387 // SSE, we're stuck with a fistpll.
388 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
391 if (isTargetFTOL()) {
392 // Use the _ftol2 runtime function, which has a pseudo-instruction
393 // to handle its weird calling convention.
394 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
397 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398 if (!X86ScalarSSEf64) {
399 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
400 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
401 if (Subtarget->is64Bit()) {
402 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
403 // Without SSE, i64->f64 goes through memory.
404 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
408 // Scalar integer divide and remainder are lowered to use operations that
409 // produce two results, to match the available instructions. This exposes
410 // the two-result form to trivial CSE, which is able to combine x/y and x%y
411 // into a single instruction.
413 // Scalar integer multiply-high is also lowered to use two-result
414 // operations, to match the available instructions. However, plain multiply
415 // (low) operations are left as Legal, as there are single-result
416 // instructions for this in x86. Using the two-result multiply instructions
417 // when both high and low results are needed must be arranged by dagcombine.
418 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420 setOperationAction(ISD::MULHS, VT, Expand);
421 setOperationAction(ISD::MULHU, VT, Expand);
422 setOperationAction(ISD::SDIV, VT, Expand);
423 setOperationAction(ISD::UDIV, VT, Expand);
424 setOperationAction(ISD::SREM, VT, Expand);
425 setOperationAction(ISD::UREM, VT, Expand);
427 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428 setOperationAction(ISD::ADDC, VT, Custom);
429 setOperationAction(ISD::ADDE, VT, Custom);
430 setOperationAction(ISD::SUBC, VT, Custom);
431 setOperationAction(ISD::SUBE, VT, Custom);
434 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
435 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
436 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
437 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
443 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
444 if (Subtarget->is64Bit())
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
449 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
450 setOperationAction(ISD::FREM , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f64 , Expand);
452 setOperationAction(ISD::FREM , MVT::f80 , Expand);
453 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
455 // Promote the i8 variants and force them on up to i32 which has a shorter
457 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
459 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
461 if (Subtarget->hasBMI()) {
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
468 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
469 if (Subtarget->is64Bit())
470 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
473 if (Subtarget->hasLZCNT()) {
474 // When promoting the i8 variants, force them to i32 for a shorter
476 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
482 if (Subtarget->is64Bit())
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
486 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
491 if (Subtarget->is64Bit()) {
492 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497 if (Subtarget->hasPOPCNT()) {
498 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
500 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
501 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
507 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
509 if (!Subtarget->hasMOVBE())
510 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
512 // These should be promoted to a larger select which is supported.
513 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
514 // X86 wants to expand cmov itself.
515 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
516 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
518 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
521 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
524 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
527 if (Subtarget->is64Bit()) {
528 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
531 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
532 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534 // support continuation, user-level threading, and etc.. As a result, no
535 // other SjLj exception interfaces are implemented and please don't build
536 // your own exception handling based on them.
537 // LLVM/Clang supports zero-cost DWARF exception handling.
538 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
542 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
543 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
544 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
546 if (Subtarget->is64Bit())
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
549 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
550 if (Subtarget->is64Bit()) {
551 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
552 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
553 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
554 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
555 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
557 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
561 if (Subtarget->is64Bit()) {
562 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
567 if (Subtarget->hasSSE1())
568 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
570 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
572 // Expand certain atomics
573 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
580 if (!Subtarget->is64Bit()) {
581 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
595 if (Subtarget->hasCmpxchg16b()) {
596 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
599 // FIXME - use subtarget debug flags
600 if (!Subtarget->isTargetDarwin() &&
601 !Subtarget->isTargetELF() &&
602 !Subtarget->isTargetCygMing()) {
603 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
606 if (Subtarget->is64Bit()) {
607 setExceptionPointerRegister(X86::RAX);
608 setExceptionSelectorRegister(X86::RDX);
610 setExceptionPointerRegister(X86::EAX);
611 setExceptionSelectorRegister(X86::EDX);
613 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619 setOperationAction(ISD::TRAP, MVT::Other, Legal);
620 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623 setOperationAction(ISD::VASTART , MVT::Other, Custom);
624 setOperationAction(ISD::VAEND , MVT::Other, Expand);
625 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626 // TargetInfo::X86_64ABIBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Custom);
628 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
630 // TargetInfo::CharPtrBuiltinVaList
631 setOperationAction(ISD::VAARG , MVT::Other, Expand);
632 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
635 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
636 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
638 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639 MVT::i64 : MVT::i32, Custom);
641 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
642 // f32 and f64 use SSE.
643 // Set up the FP register classes.
644 addRegisterClass(MVT::f32, &X86::FR32RegClass);
645 addRegisterClass(MVT::f64, &X86::FR64RegClass);
647 // Use ANDPD to simulate FABS.
648 setOperationAction(ISD::FABS , MVT::f64, Custom);
649 setOperationAction(ISD::FABS , MVT::f32, Custom);
651 // Use XORP to simulate FNEG.
652 setOperationAction(ISD::FNEG , MVT::f64, Custom);
653 setOperationAction(ISD::FNEG , MVT::f32, Custom);
655 // Use ANDPD and ORPD to simulate FCOPYSIGN.
656 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
657 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
659 // Lower this to FGETSIGNx86 plus an AND.
660 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
661 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
663 // We don't support sin/cos/fmod
664 setOperationAction(ISD::FSIN , MVT::f64, Expand);
665 setOperationAction(ISD::FCOS , MVT::f64, Expand);
666 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
667 setOperationAction(ISD::FSIN , MVT::f32, Expand);
668 setOperationAction(ISD::FCOS , MVT::f32, Expand);
669 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
671 // Expand FP immediates into loads from the stack, except for the special
673 addLegalFPImmediate(APFloat(+0.0)); // xorpd
674 addLegalFPImmediate(APFloat(+0.0f)); // xorps
675 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
676 // Use SSE for f32, x87 for f64.
677 // Set up the FP register classes.
678 addRegisterClass(MVT::f32, &X86::FR32RegClass);
679 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
681 // Use ANDPS to simulate FABS.
682 setOperationAction(ISD::FABS , MVT::f32, Custom);
684 // Use XORP to simulate FNEG.
685 setOperationAction(ISD::FNEG , MVT::f32, Custom);
687 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
689 // Use ANDPS and ORPS to simulate FCOPYSIGN.
690 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
691 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
693 // We don't support sin/cos/fmod
694 setOperationAction(ISD::FSIN , MVT::f32, Expand);
695 setOperationAction(ISD::FCOS , MVT::f32, Expand);
696 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
698 // Special cases we handle for FP constants.
699 addLegalFPImmediate(APFloat(+0.0f)); // xorps
700 addLegalFPImmediate(APFloat(+0.0)); // FLD0
701 addLegalFPImmediate(APFloat(+1.0)); // FLD1
702 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
703 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
705 if (!TM.Options.UnsafeFPMath) {
706 setOperationAction(ISD::FSIN , MVT::f64, Expand);
707 setOperationAction(ISD::FCOS , MVT::f64, Expand);
708 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
710 } else if (!TM.Options.UseSoftFloat) {
711 // f32 and f64 in x87.
712 // Set up the FP register classes.
713 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
714 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
716 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
717 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
718 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
719 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
721 if (!TM.Options.UnsafeFPMath) {
722 setOperationAction(ISD::FSIN , MVT::f64, Expand);
723 setOperationAction(ISD::FSIN , MVT::f32, Expand);
724 setOperationAction(ISD::FCOS , MVT::f64, Expand);
725 setOperationAction(ISD::FCOS , MVT::f32, Expand);
726 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
727 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
729 addLegalFPImmediate(APFloat(+0.0)); // FLD0
730 addLegalFPImmediate(APFloat(+1.0)); // FLD1
731 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
732 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
733 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
734 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
735 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
736 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
739 // We don't support FMA.
740 setOperationAction(ISD::FMA, MVT::f64, Expand);
741 setOperationAction(ISD::FMA, MVT::f32, Expand);
743 // Long double always uses X87.
744 if (!TM.Options.UseSoftFloat) {
745 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
746 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
747 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
749 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
750 addLegalFPImmediate(TmpFlt); // FLD0
752 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
755 APFloat TmpFlt2(+1.0);
756 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
758 addLegalFPImmediate(TmpFlt2); // FLD1
759 TmpFlt2.changeSign();
760 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
763 if (!TM.Options.UnsafeFPMath) {
764 setOperationAction(ISD::FSIN , MVT::f80, Expand);
765 setOperationAction(ISD::FCOS , MVT::f80, Expand);
766 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
769 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
770 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
771 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
772 setOperationAction(ISD::FRINT, MVT::f80, Expand);
773 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
774 setOperationAction(ISD::FMA, MVT::f80, Expand);
777 // Always use a library call for pow.
778 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
779 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
780 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
782 setOperationAction(ISD::FLOG, MVT::f80, Expand);
783 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
784 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
785 setOperationAction(ISD::FEXP, MVT::f80, Expand);
786 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
788 // First set operation action for all vector types to either promote
789 // (for widening) or expand (for scalarization). Then we will selectively
790 // turn on ones that can be effectively codegen'd.
791 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
792 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
793 MVT VT = (MVT::SimpleValueType)i;
794 setOperationAction(ISD::ADD , VT, Expand);
795 setOperationAction(ISD::SUB , VT, Expand);
796 setOperationAction(ISD::FADD, VT, Expand);
797 setOperationAction(ISD::FNEG, VT, Expand);
798 setOperationAction(ISD::FSUB, VT, Expand);
799 setOperationAction(ISD::MUL , VT, Expand);
800 setOperationAction(ISD::FMUL, VT, Expand);
801 setOperationAction(ISD::SDIV, VT, Expand);
802 setOperationAction(ISD::UDIV, VT, Expand);
803 setOperationAction(ISD::FDIV, VT, Expand);
804 setOperationAction(ISD::SREM, VT, Expand);
805 setOperationAction(ISD::UREM, VT, Expand);
806 setOperationAction(ISD::LOAD, VT, Expand);
807 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
808 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
809 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
810 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
811 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
812 setOperationAction(ISD::FABS, VT, Expand);
813 setOperationAction(ISD::FSIN, VT, Expand);
814 setOperationAction(ISD::FSINCOS, VT, Expand);
815 setOperationAction(ISD::FCOS, VT, Expand);
816 setOperationAction(ISD::FSINCOS, VT, Expand);
817 setOperationAction(ISD::FREM, VT, Expand);
818 setOperationAction(ISD::FMA, VT, Expand);
819 setOperationAction(ISD::FPOWI, VT, Expand);
820 setOperationAction(ISD::FSQRT, VT, Expand);
821 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
822 setOperationAction(ISD::FFLOOR, VT, Expand);
823 setOperationAction(ISD::FCEIL, VT, Expand);
824 setOperationAction(ISD::FTRUNC, VT, Expand);
825 setOperationAction(ISD::FRINT, VT, Expand);
826 setOperationAction(ISD::FNEARBYINT, VT, Expand);
827 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
828 setOperationAction(ISD::MULHS, VT, Expand);
829 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830 setOperationAction(ISD::MULHU, VT, Expand);
831 setOperationAction(ISD::SDIVREM, VT, Expand);
832 setOperationAction(ISD::UDIVREM, VT, Expand);
833 setOperationAction(ISD::FPOW, VT, Expand);
834 setOperationAction(ISD::CTPOP, VT, Expand);
835 setOperationAction(ISD::CTTZ, VT, Expand);
836 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
837 setOperationAction(ISD::CTLZ, VT, Expand);
838 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
839 setOperationAction(ISD::SHL, VT, Expand);
840 setOperationAction(ISD::SRA, VT, Expand);
841 setOperationAction(ISD::SRL, VT, Expand);
842 setOperationAction(ISD::ROTL, VT, Expand);
843 setOperationAction(ISD::ROTR, VT, Expand);
844 setOperationAction(ISD::BSWAP, VT, Expand);
845 setOperationAction(ISD::SETCC, VT, Expand);
846 setOperationAction(ISD::FLOG, VT, Expand);
847 setOperationAction(ISD::FLOG2, VT, Expand);
848 setOperationAction(ISD::FLOG10, VT, Expand);
849 setOperationAction(ISD::FEXP, VT, Expand);
850 setOperationAction(ISD::FEXP2, VT, Expand);
851 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
852 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
853 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
854 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
855 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
856 setOperationAction(ISD::TRUNCATE, VT, Expand);
857 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
858 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
859 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
860 setOperationAction(ISD::VSELECT, VT, Expand);
861 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
862 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
863 setTruncStoreAction(VT,
864 (MVT::SimpleValueType)InnerVT, Expand);
865 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
866 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
870 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
871 // with -msoft-float, disable use of MMX as well.
872 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
873 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
874 // No operations on x86mmx supported, everything uses intrinsics.
877 // MMX-sized vectors (other than x86mmx) are expected to be expanded
878 // into smaller operations.
879 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
880 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
881 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
882 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
883 setOperationAction(ISD::AND, MVT::v8i8, Expand);
884 setOperationAction(ISD::AND, MVT::v4i16, Expand);
885 setOperationAction(ISD::AND, MVT::v2i32, Expand);
886 setOperationAction(ISD::AND, MVT::v1i64, Expand);
887 setOperationAction(ISD::OR, MVT::v8i8, Expand);
888 setOperationAction(ISD::OR, MVT::v4i16, Expand);
889 setOperationAction(ISD::OR, MVT::v2i32, Expand);
890 setOperationAction(ISD::OR, MVT::v1i64, Expand);
891 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
892 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
893 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
894 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
895 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
899 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
900 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
901 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
902 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
903 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
904 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
909 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
910 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
913 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
914 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
915 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
916 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
917 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
918 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
919 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
920 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
921 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
923 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
926 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
927 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
930 // registers cannot be used even for integer operations.
931 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
932 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
933 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
934 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
937 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
938 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
939 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
940 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
941 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
942 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
943 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
944 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
945 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
946 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
947 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
948 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
949 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
950 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
951 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
953 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
954 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
956 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
957 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
959 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
961 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
962 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
964 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
970 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972 MVT VT = (MVT::SimpleValueType)i;
973 // Do not attempt to custom lower non-power-of-2 vectors
974 if (!isPowerOf2_32(VT.getVectorNumElements()))
976 // Do not attempt to custom lower non-128-bit vectors
977 if (!VT.is128BitVector())
979 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
980 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
984 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
986 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
991 if (Subtarget->is64Bit()) {
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
996 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998 MVT VT = (MVT::SimpleValueType)i;
1000 // Do not attempt to promote non-128-bit vectors
1001 if (!VT.is128BitVector())
1004 setOperationAction(ISD::AND, VT, Promote);
1005 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1006 setOperationAction(ISD::OR, VT, Promote);
1007 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1008 setOperationAction(ISD::XOR, VT, Promote);
1009 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1010 setOperationAction(ISD::LOAD, VT, Promote);
1011 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1012 setOperationAction(ISD::SELECT, VT, Promote);
1013 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1016 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1018 // Custom lower v2i64 and v2f64 selects.
1019 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1020 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1021 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1022 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1024 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1025 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1029 // As there is no 64-bit GPR available, we need build a special custom
1030 // sequence to convert from v2i32 to v2f32.
1031 if (!Subtarget->is64Bit())
1032 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1034 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1037 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1039 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1040 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1041 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1044 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1045 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1046 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1047 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1048 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1049 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1050 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1051 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1052 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1053 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1054 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1056 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1059 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1060 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1061 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1063 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1064 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1065 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1067 // FIXME: Do we need to handle scalar-to-vector here?
1068 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1071 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1072 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1073 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1074 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1075 // There is no BLENDI for byte vectors. We don't need to custom lower
1076 // some vselects for now.
1077 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1079 // i8 and i16 vectors are custom , because the source register and source
1080 // source memory operand types are not the same width. f32 vectors are
1081 // custom since the immediate controlling the insert encodes additional
1083 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1085 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1086 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1088 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1089 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1090 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1093 // FIXME: these should be Legal but thats only for the case where
1094 // the index is constant. For now custom expand to deal with that.
1095 if (Subtarget->is64Bit()) {
1096 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1101 if (Subtarget->hasSSE2()) {
1102 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1103 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1105 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1106 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1108 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1109 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1111 // In the customized shift lowering, the legal cases in AVX2 will be
1113 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1114 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1116 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1117 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1119 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1122 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1123 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1126 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1127 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1128 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1130 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1131 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1132 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1134 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1145 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1147 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1158 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1160 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1161 // even though v8i16 is a legal type.
1162 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1163 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1164 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1166 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1167 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1168 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1170 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1171 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1173 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1175 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1184 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1186 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1187 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1189 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1190 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1191 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1193 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1194 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1195 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1196 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1198 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1199 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1200 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1201 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1202 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1203 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1204 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1205 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1206 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1207 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1208 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1209 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1211 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1212 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1213 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1214 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1215 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1216 setOperationAction(ISD::FMA, MVT::f32, Legal);
1217 setOperationAction(ISD::FMA, MVT::f64, Legal);
1220 if (Subtarget->hasInt256()) {
1221 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1222 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1223 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1224 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1226 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1227 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1228 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1229 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1231 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1232 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1233 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1234 // Don't lower v32i8 because there is no 128-bit byte mul
1236 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1237 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1238 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1239 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1241 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1242 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1244 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1245 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1246 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1247 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1249 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1250 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1252 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1254 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1255 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1256 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1257 // Don't lower v32i8 because there is no 128-bit byte mul
1260 // In the customized shift lowering, the legal cases in AVX2 will be
1262 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1263 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1265 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1266 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1268 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1270 // Custom lower several nodes for 256-bit types.
1271 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1272 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1273 MVT VT = (MVT::SimpleValueType)i;
1275 // Extract subvector is special because the value type
1276 // (result) is 128-bit but the source is 256-bit wide.
1277 if (VT.is128BitVector())
1278 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1280 // Do not attempt to custom lower other non-256-bit vectors
1281 if (!VT.is256BitVector())
1284 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1285 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1286 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1287 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1288 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1289 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1290 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1293 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1295 MVT VT = (MVT::SimpleValueType)i;
1297 // Do not attempt to promote non-256-bit vectors
1298 if (!VT.is256BitVector())
1301 setOperationAction(ISD::AND, VT, Promote);
1302 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1303 setOperationAction(ISD::OR, VT, Promote);
1304 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1305 setOperationAction(ISD::XOR, VT, Promote);
1306 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1307 setOperationAction(ISD::LOAD, VT, Promote);
1308 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1309 setOperationAction(ISD::SELECT, VT, Promote);
1310 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1314 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1315 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1316 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1317 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1318 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1320 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1321 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1322 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1324 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1325 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1326 setOperationAction(ISD::XOR, MVT::i1, Legal);
1327 setOperationAction(ISD::OR, MVT::i1, Legal);
1328 setOperationAction(ISD::AND, MVT::i1, Legal);
1329 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1330 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1331 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1332 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1333 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1334 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1336 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1337 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1338 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1339 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1340 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1341 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1343 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1344 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1346 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1347 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1348 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1349 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1350 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1353 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1354 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1355 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1356 if (Subtarget->is64Bit()) {
1357 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1358 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1359 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1360 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1362 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1363 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1364 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1365 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1366 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1367 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1368 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1370 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1371 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1373 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1374 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1375 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1376 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1377 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1378 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1379 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1380 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1381 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1382 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1383 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1384 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1385 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1388 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1389 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1390 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1391 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1392 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1394 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1395 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1397 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1403 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1404 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1405 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1406 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1407 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1409 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1410 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1412 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1413 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1415 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1417 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1418 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1420 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1421 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1423 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1424 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1426 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1427 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1428 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1429 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1430 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1431 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1433 // Custom lower several nodes.
1434 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1435 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1436 MVT VT = (MVT::SimpleValueType)i;
1438 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1439 // Extract subvector is special because the value type
1440 // (result) is 256/128-bit but the source is 512-bit wide.
1441 if (VT.is128BitVector() || VT.is256BitVector())
1442 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1444 if (VT.getVectorElementType() == MVT::i1)
1445 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1447 // Do not attempt to custom lower other non-512-bit vectors
1448 if (!VT.is512BitVector())
1451 if ( EltSize >= 32) {
1452 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1454 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1455 setOperationAction(ISD::VSELECT, VT, Legal);
1456 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1457 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1458 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1461 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1462 MVT VT = (MVT::SimpleValueType)i;
1464 // Do not attempt to promote non-256-bit vectors
1465 if (!VT.is512BitVector())
1468 setOperationAction(ISD::SELECT, VT, Promote);
1469 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1473 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1474 // of this type with custom code.
1475 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1476 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1477 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1481 // We want to custom lower some of our intrinsics.
1482 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1483 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1484 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1485 if (!Subtarget->is64Bit())
1486 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1488 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1489 // handle type legalization for these operations here.
1491 // FIXME: We really should do custom legalization for addition and
1492 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1493 // than generic legalization for 64-bit multiplication-with-overflow, though.
1494 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1495 // Add/Sub/Mul with overflow operations are custom lowered.
1497 setOperationAction(ISD::SADDO, VT, Custom);
1498 setOperationAction(ISD::UADDO, VT, Custom);
1499 setOperationAction(ISD::SSUBO, VT, Custom);
1500 setOperationAction(ISD::USUBO, VT, Custom);
1501 setOperationAction(ISD::SMULO, VT, Custom);
1502 setOperationAction(ISD::UMULO, VT, Custom);
1505 // There are no 8-bit 3-address imul/mul instructions
1506 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1507 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1509 if (!Subtarget->is64Bit()) {
1510 // These libcalls are not available in 32-bit.
1511 setLibcallName(RTLIB::SHL_I128, nullptr);
1512 setLibcallName(RTLIB::SRL_I128, nullptr);
1513 setLibcallName(RTLIB::SRA_I128, nullptr);
1516 // Combine sin / cos into one node or libcall if possible.
1517 if (Subtarget->hasSinCos()) {
1518 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1519 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1520 if (Subtarget->isTargetDarwin()) {
1521 // For MacOSX, we don't want to the normal expansion of a libcall to
1522 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1524 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1525 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1529 if (Subtarget->isTargetWin64()) {
1530 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1531 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1532 setOperationAction(ISD::SREM, MVT::i128, Custom);
1533 setOperationAction(ISD::UREM, MVT::i128, Custom);
1534 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1535 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1538 // We have target-specific dag combine patterns for the following nodes:
1539 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1540 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1541 setTargetDAGCombine(ISD::VSELECT);
1542 setTargetDAGCombine(ISD::SELECT);
1543 setTargetDAGCombine(ISD::SHL);
1544 setTargetDAGCombine(ISD::SRA);
1545 setTargetDAGCombine(ISD::SRL);
1546 setTargetDAGCombine(ISD::OR);
1547 setTargetDAGCombine(ISD::AND);
1548 setTargetDAGCombine(ISD::ADD);
1549 setTargetDAGCombine(ISD::FADD);
1550 setTargetDAGCombine(ISD::FSUB);
1551 setTargetDAGCombine(ISD::FMA);
1552 setTargetDAGCombine(ISD::SUB);
1553 setTargetDAGCombine(ISD::LOAD);
1554 setTargetDAGCombine(ISD::STORE);
1555 setTargetDAGCombine(ISD::ZERO_EXTEND);
1556 setTargetDAGCombine(ISD::ANY_EXTEND);
1557 setTargetDAGCombine(ISD::SIGN_EXTEND);
1558 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1559 setTargetDAGCombine(ISD::TRUNCATE);
1560 setTargetDAGCombine(ISD::SINT_TO_FP);
1561 setTargetDAGCombine(ISD::SETCC);
1562 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1563 if (Subtarget->is64Bit())
1564 setTargetDAGCombine(ISD::MUL);
1565 setTargetDAGCombine(ISD::XOR);
1567 computeRegisterProperties();
1569 // On Darwin, -Os means optimize for size without hurting performance,
1570 // do not reduce the limit.
1571 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1572 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1573 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1574 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1575 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1576 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1577 setPrefLoopAlignment(4); // 2^4 bytes.
1579 // Predictable cmov don't hurt on atom because it's in-order.
1580 PredictableSelectIsExpensive = !Subtarget->isAtom();
1582 setPrefFunctionAlignment(4); // 2^4 bytes.
1585 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1587 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1589 if (Subtarget->hasAVX512())
1590 switch(VT.getVectorNumElements()) {
1591 case 8: return MVT::v8i1;
1592 case 16: return MVT::v16i1;
1595 return VT.changeVectorElementTypeToInteger();
1598 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1599 /// the desired ByVal argument alignment.
1600 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1603 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1604 if (VTy->getBitWidth() == 128)
1606 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1607 unsigned EltAlign = 0;
1608 getMaxByValAlign(ATy->getElementType(), EltAlign);
1609 if (EltAlign > MaxAlign)
1610 MaxAlign = EltAlign;
1611 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1612 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1613 unsigned EltAlign = 0;
1614 getMaxByValAlign(STy->getElementType(i), EltAlign);
1615 if (EltAlign > MaxAlign)
1616 MaxAlign = EltAlign;
1623 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1624 /// function arguments in the caller parameter area. For X86, aggregates
1625 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1626 /// are at 4-byte boundaries.
1627 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1628 if (Subtarget->is64Bit()) {
1629 // Max of 8 and alignment of type.
1630 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1637 if (Subtarget->hasSSE1())
1638 getMaxByValAlign(Ty, Align);
1642 /// getOptimalMemOpType - Returns the target specific optimal type for load
1643 /// and store operations as a result of memset, memcpy, and memmove
1644 /// lowering. If DstAlign is zero that means it's safe to destination
1645 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1646 /// means there isn't a need to check it against alignment requirement,
1647 /// probably because the source does not need to be loaded. If 'IsMemset' is
1648 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1649 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1650 /// source is constant so it does not need to be loaded.
1651 /// It returns EVT::Other if the type should be determined using generic
1652 /// target-independent logic.
1654 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1655 unsigned DstAlign, unsigned SrcAlign,
1656 bool IsMemset, bool ZeroMemset,
1658 MachineFunction &MF) const {
1659 const Function *F = MF.getFunction();
1660 if ((!IsMemset || ZeroMemset) &&
1661 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1662 Attribute::NoImplicitFloat)) {
1664 (Subtarget->isUnalignedMemAccessFast() ||
1665 ((DstAlign == 0 || DstAlign >= 16) &&
1666 (SrcAlign == 0 || SrcAlign >= 16)))) {
1668 if (Subtarget->hasInt256())
1670 if (Subtarget->hasFp256())
1673 if (Subtarget->hasSSE2())
1675 if (Subtarget->hasSSE1())
1677 } else if (!MemcpyStrSrc && Size >= 8 &&
1678 !Subtarget->is64Bit() &&
1679 Subtarget->hasSSE2()) {
1680 // Do not use f64 to lower memcpy if source is string constant. It's
1681 // better to use i32 to avoid the loads.
1685 if (Subtarget->is64Bit() && Size >= 8)
1690 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1692 return X86ScalarSSEf32;
1693 else if (VT == MVT::f64)
1694 return X86ScalarSSEf64;
1699 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1703 *Fast = Subtarget->isUnalignedMemAccessFast();
1707 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1708 /// current function. The returned value is a member of the
1709 /// MachineJumpTableInfo::JTEntryKind enum.
1710 unsigned X86TargetLowering::getJumpTableEncoding() const {
1711 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1713 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1714 Subtarget->isPICStyleGOT())
1715 return MachineJumpTableInfo::EK_Custom32;
1717 // Otherwise, use the normal jump table encoding heuristics.
1718 return TargetLowering::getJumpTableEncoding();
1722 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1723 const MachineBasicBlock *MBB,
1724 unsigned uid,MCContext &Ctx) const{
1725 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1726 Subtarget->isPICStyleGOT());
1727 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1729 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1730 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1733 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1735 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1736 SelectionDAG &DAG) const {
1737 if (!Subtarget->is64Bit())
1738 // This doesn't have SDLoc associated with it, but is not really the
1739 // same as a Register.
1740 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1744 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1745 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1747 const MCExpr *X86TargetLowering::
1748 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1749 MCContext &Ctx) const {
1750 // X86-64 uses RIP relative addressing based on the jump table label.
1751 if (Subtarget->isPICStyleRIPRel())
1752 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1754 // Otherwise, the reference is relative to the PIC base.
1755 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1758 // FIXME: Why this routine is here? Move to RegInfo!
1759 std::pair<const TargetRegisterClass*, uint8_t>
1760 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1761 const TargetRegisterClass *RRC = nullptr;
1763 switch (VT.SimpleTy) {
1765 return TargetLowering::findRepresentativeClass(VT);
1766 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1767 RRC = Subtarget->is64Bit() ?
1768 (const TargetRegisterClass*)&X86::GR64RegClass :
1769 (const TargetRegisterClass*)&X86::GR32RegClass;
1772 RRC = &X86::VR64RegClass;
1774 case MVT::f32: case MVT::f64:
1775 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1776 case MVT::v4f32: case MVT::v2f64:
1777 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1779 RRC = &X86::VR128RegClass;
1782 return std::make_pair(RRC, Cost);
1785 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1786 unsigned &Offset) const {
1787 if (!Subtarget->isTargetLinux())
1790 if (Subtarget->is64Bit()) {
1791 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1793 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1805 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1806 unsigned DestAS) const {
1807 assert(SrcAS != DestAS && "Expected different address spaces!");
1809 return SrcAS < 256 && DestAS < 256;
1812 //===----------------------------------------------------------------------===//
1813 // Return Value Calling Convention Implementation
1814 //===----------------------------------------------------------------------===//
1816 #include "X86GenCallingConv.inc"
1819 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1820 MachineFunction &MF, bool isVarArg,
1821 const SmallVectorImpl<ISD::OutputArg> &Outs,
1822 LLVMContext &Context) const {
1823 SmallVector<CCValAssign, 16> RVLocs;
1824 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1826 return CCInfo.CheckReturn(Outs, RetCC_X86);
1829 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1830 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1835 X86TargetLowering::LowerReturn(SDValue Chain,
1836 CallingConv::ID CallConv, bool isVarArg,
1837 const SmallVectorImpl<ISD::OutputArg> &Outs,
1838 const SmallVectorImpl<SDValue> &OutVals,
1839 SDLoc dl, SelectionDAG &DAG) const {
1840 MachineFunction &MF = DAG.getMachineFunction();
1841 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1843 SmallVector<CCValAssign, 16> RVLocs;
1844 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1845 RVLocs, *DAG.getContext());
1846 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1849 SmallVector<SDValue, 6> RetOps;
1850 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1851 // Operand #1 = Bytes To Pop
1852 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1855 // Copy the result values into the output registers.
1856 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1857 CCValAssign &VA = RVLocs[i];
1858 assert(VA.isRegLoc() && "Can only return in registers!");
1859 SDValue ValToCopy = OutVals[i];
1860 EVT ValVT = ValToCopy.getValueType();
1862 // Promote values to the appropriate types
1863 if (VA.getLocInfo() == CCValAssign::SExt)
1864 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1865 else if (VA.getLocInfo() == CCValAssign::ZExt)
1866 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1867 else if (VA.getLocInfo() == CCValAssign::AExt)
1868 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1869 else if (VA.getLocInfo() == CCValAssign::BCvt)
1870 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1872 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1873 "Unexpected FP-extend for return value.");
1875 // If this is x86-64, and we disabled SSE, we can't return FP values,
1876 // or SSE or MMX vectors.
1877 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1878 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1879 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1880 report_fatal_error("SSE register return with SSE disabled");
1882 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1883 // llvm-gcc has never done it right and no one has noticed, so this
1884 // should be OK for now.
1885 if (ValVT == MVT::f64 &&
1886 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1887 report_fatal_error("SSE2 register return with SSE2 disabled");
1889 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1890 // the RET instruction and handled by the FP Stackifier.
1891 if (VA.getLocReg() == X86::ST0 ||
1892 VA.getLocReg() == X86::ST1) {
1893 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1894 // change the value to the FP stack register class.
1895 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1896 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1897 RetOps.push_back(ValToCopy);
1898 // Don't emit a copytoreg.
1902 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1903 // which is returned in RAX / RDX.
1904 if (Subtarget->is64Bit()) {
1905 if (ValVT == MVT::x86mmx) {
1906 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1907 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1908 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1910 // If we don't have SSE2 available, convert to v4f32 so the generated
1911 // register is legal.
1912 if (!Subtarget->hasSSE2())
1913 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1918 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1919 Flag = Chain.getValue(1);
1920 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1923 // The x86-64 ABIs require that for returning structs by value we copy
1924 // the sret argument into %rax/%eax (depending on ABI) for the return.
1925 // Win32 requires us to put the sret argument to %eax as well.
1926 // We saved the argument into a virtual register in the entry block,
1927 // so now we copy the value out and into %rax/%eax.
1928 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1929 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1930 MachineFunction &MF = DAG.getMachineFunction();
1931 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1932 unsigned Reg = FuncInfo->getSRetReturnReg();
1934 "SRetReturnReg should have been set in LowerFormalArguments().");
1935 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1938 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1939 X86::RAX : X86::EAX;
1940 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1941 Flag = Chain.getValue(1);
1943 // RAX/EAX now acts like a return value.
1944 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1947 RetOps[0] = Chain; // Update chain.
1949 // Add the flag if we have it.
1951 RetOps.push_back(Flag);
1953 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1956 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1957 if (N->getNumValues() != 1)
1959 if (!N->hasNUsesOfValue(1, 0))
1962 SDValue TCChain = Chain;
1963 SDNode *Copy = *N->use_begin();
1964 if (Copy->getOpcode() == ISD::CopyToReg) {
1965 // If the copy has a glue operand, we conservatively assume it isn't safe to
1966 // perform a tail call.
1967 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1969 TCChain = Copy->getOperand(0);
1970 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1973 bool HasRet = false;
1974 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1976 if (UI->getOpcode() != X86ISD::RET_FLAG)
1989 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1990 ISD::NodeType ExtendKind) const {
1992 // TODO: Is this also valid on 32-bit?
1993 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1994 ReturnMVT = MVT::i8;
1996 ReturnMVT = MVT::i32;
1998 MVT MinVT = getRegisterType(ReturnMVT);
1999 return VT.bitsLT(MinVT) ? MinVT : VT;
2002 /// LowerCallResult - Lower the result values of a call into the
2003 /// appropriate copies out of appropriate physical registers.
2006 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2007 CallingConv::ID CallConv, bool isVarArg,
2008 const SmallVectorImpl<ISD::InputArg> &Ins,
2009 SDLoc dl, SelectionDAG &DAG,
2010 SmallVectorImpl<SDValue> &InVals) const {
2012 // Assign locations to each value returned by this call.
2013 SmallVector<CCValAssign, 16> RVLocs;
2014 bool Is64Bit = Subtarget->is64Bit();
2015 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2016 getTargetMachine(), RVLocs, *DAG.getContext());
2017 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2019 // Copy all of the result registers out of their specified physreg.
2020 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2021 CCValAssign &VA = RVLocs[i];
2022 EVT CopyVT = VA.getValVT();
2024 // If this is x86-64, and we disabled SSE, we can't return FP values
2025 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2026 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2027 report_fatal_error("SSE register return with SSE disabled");
2032 // If this is a call to a function that returns an fp value on the floating
2033 // point stack, we must guarantee the value is popped from the stack, so
2034 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2035 // if the return value is not used. We use the FpPOP_RETVAL instruction
2037 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2038 // If we prefer to use the value in xmm registers, copy it out as f80 and
2039 // use a truncate to move it from fp stack reg to xmm reg.
2040 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2041 SDValue Ops[] = { Chain, InFlag };
2042 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2043 MVT::Other, MVT::Glue, Ops), 1);
2044 Val = Chain.getValue(0);
2046 // Round the f80 to the right size, which also moves it to the appropriate
2048 if (CopyVT != VA.getValVT())
2049 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2050 // This truncation won't change the value.
2051 DAG.getIntPtrConstant(1));
2053 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2054 CopyVT, InFlag).getValue(1);
2055 Val = Chain.getValue(0);
2057 InFlag = Chain.getValue(2);
2058 InVals.push_back(Val);
2064 //===----------------------------------------------------------------------===//
2065 // C & StdCall & Fast Calling Convention implementation
2066 //===----------------------------------------------------------------------===//
2067 // StdCall calling convention seems to be standard for many Windows' API
2068 // routines and around. It differs from C calling convention just a little:
2069 // callee should clean up the stack, not caller. Symbols should be also
2070 // decorated in some fancy way :) It doesn't support any vector arguments.
2071 // For info on fast calling convention see Fast Calling Convention (tail call)
2072 // implementation LowerX86_32FastCCCallTo.
2074 /// CallIsStructReturn - Determines whether a call uses struct return
2076 enum StructReturnType {
2081 static StructReturnType
2082 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2084 return NotStructReturn;
2086 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2087 if (!Flags.isSRet())
2088 return NotStructReturn;
2089 if (Flags.isInReg())
2090 return RegStructReturn;
2091 return StackStructReturn;
2094 /// ArgsAreStructReturn - Determines whether a function uses struct
2095 /// return semantics.
2096 static StructReturnType
2097 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2099 return NotStructReturn;
2101 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2102 if (!Flags.isSRet())
2103 return NotStructReturn;
2104 if (Flags.isInReg())
2105 return RegStructReturn;
2106 return StackStructReturn;
2109 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2110 /// by "Src" to address "Dst" with size and alignment information specified by
2111 /// the specific parameter attribute. The copy will be passed as a byval
2112 /// function parameter.
2114 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2115 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2117 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2119 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2120 /*isVolatile*/false, /*AlwaysInline=*/true,
2121 MachinePointerInfo(), MachinePointerInfo());
2124 /// IsTailCallConvention - Return true if the calling convention is one that
2125 /// supports tail call optimization.
2126 static bool IsTailCallConvention(CallingConv::ID CC) {
2127 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2128 CC == CallingConv::HiPE);
2131 /// \brief Return true if the calling convention is a C calling convention.
2132 static bool IsCCallConvention(CallingConv::ID CC) {
2133 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2134 CC == CallingConv::X86_64_SysV);
2137 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2138 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2142 CallingConv::ID CalleeCC = CS.getCallingConv();
2143 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2149 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2150 /// a tailcall target by changing its ABI.
2151 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2152 bool GuaranteedTailCallOpt) {
2153 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2157 X86TargetLowering::LowerMemArgument(SDValue Chain,
2158 CallingConv::ID CallConv,
2159 const SmallVectorImpl<ISD::InputArg> &Ins,
2160 SDLoc dl, SelectionDAG &DAG,
2161 const CCValAssign &VA,
2162 MachineFrameInfo *MFI,
2164 // Create the nodes corresponding to a load from this parameter slot.
2165 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2166 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2167 getTargetMachine().Options.GuaranteedTailCallOpt);
2168 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2171 // If value is passed by pointer we have address passed instead of the value
2173 if (VA.getLocInfo() == CCValAssign::Indirect)
2174 ValVT = VA.getLocVT();
2176 ValVT = VA.getValVT();
2178 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2179 // changed with more analysis.
2180 // In case of tail call optimization mark all arguments mutable. Since they
2181 // could be overwritten by lowering of arguments in case of a tail call.
2182 if (Flags.isByVal()) {
2183 unsigned Bytes = Flags.getByValSize();
2184 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2185 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2186 return DAG.getFrameIndex(FI, getPointerTy());
2188 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2189 VA.getLocMemOffset(), isImmutable);
2190 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2191 return DAG.getLoad(ValVT, dl, Chain, FIN,
2192 MachinePointerInfo::getFixedStack(FI),
2193 false, false, false, 0);
2198 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2199 CallingConv::ID CallConv,
2201 const SmallVectorImpl<ISD::InputArg> &Ins,
2204 SmallVectorImpl<SDValue> &InVals)
2206 MachineFunction &MF = DAG.getMachineFunction();
2207 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2209 const Function* Fn = MF.getFunction();
2210 if (Fn->hasExternalLinkage() &&
2211 Subtarget->isTargetCygMing() &&
2212 Fn->getName() == "main")
2213 FuncInfo->setForceFramePointer(true);
2215 MachineFrameInfo *MFI = MF.getFrameInfo();
2216 bool Is64Bit = Subtarget->is64Bit();
2217 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2219 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2220 "Var args not supported with calling convention fastcc, ghc or hipe");
2222 // Assign locations to all of the incoming arguments.
2223 SmallVector<CCValAssign, 16> ArgLocs;
2224 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2225 ArgLocs, *DAG.getContext());
2227 // Allocate shadow area for Win64
2229 CCInfo.AllocateStack(32, 8);
2231 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2233 unsigned LastVal = ~0U;
2235 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2236 CCValAssign &VA = ArgLocs[i];
2237 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2239 assert(VA.getValNo() != LastVal &&
2240 "Don't support value assigned to multiple locs yet");
2242 LastVal = VA.getValNo();
2244 if (VA.isRegLoc()) {
2245 EVT RegVT = VA.getLocVT();
2246 const TargetRegisterClass *RC;
2247 if (RegVT == MVT::i32)
2248 RC = &X86::GR32RegClass;
2249 else if (Is64Bit && RegVT == MVT::i64)
2250 RC = &X86::GR64RegClass;
2251 else if (RegVT == MVT::f32)
2252 RC = &X86::FR32RegClass;
2253 else if (RegVT == MVT::f64)
2254 RC = &X86::FR64RegClass;
2255 else if (RegVT.is512BitVector())
2256 RC = &X86::VR512RegClass;
2257 else if (RegVT.is256BitVector())
2258 RC = &X86::VR256RegClass;
2259 else if (RegVT.is128BitVector())
2260 RC = &X86::VR128RegClass;
2261 else if (RegVT == MVT::x86mmx)
2262 RC = &X86::VR64RegClass;
2263 else if (RegVT == MVT::i1)
2264 RC = &X86::VK1RegClass;
2265 else if (RegVT == MVT::v8i1)
2266 RC = &X86::VK8RegClass;
2267 else if (RegVT == MVT::v16i1)
2268 RC = &X86::VK16RegClass;
2270 llvm_unreachable("Unknown argument type!");
2272 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2273 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2275 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2276 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2278 if (VA.getLocInfo() == CCValAssign::SExt)
2279 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2280 DAG.getValueType(VA.getValVT()));
2281 else if (VA.getLocInfo() == CCValAssign::ZExt)
2282 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2283 DAG.getValueType(VA.getValVT()));
2284 else if (VA.getLocInfo() == CCValAssign::BCvt)
2285 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2287 if (VA.isExtInLoc()) {
2288 // Handle MMX values passed in XMM regs.
2289 if (RegVT.isVector())
2290 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2292 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2295 assert(VA.isMemLoc());
2296 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2299 // If value is passed via pointer - do a load.
2300 if (VA.getLocInfo() == CCValAssign::Indirect)
2301 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2302 MachinePointerInfo(), false, false, false, 0);
2304 InVals.push_back(ArgValue);
2307 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2308 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2309 // The x86-64 ABIs require that for returning structs by value we copy
2310 // the sret argument into %rax/%eax (depending on ABI) for the return.
2311 // Win32 requires us to put the sret argument to %eax as well.
2312 // Save the argument into a virtual register so that we can access it
2313 // from the return points.
2314 if (Ins[i].Flags.isSRet()) {
2315 unsigned Reg = FuncInfo->getSRetReturnReg();
2317 MVT PtrTy = getPointerTy();
2318 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2319 FuncInfo->setSRetReturnReg(Reg);
2321 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2322 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2328 unsigned StackSize = CCInfo.getNextStackOffset();
2329 // Align stack specially for tail calls.
2330 if (FuncIsMadeTailCallSafe(CallConv,
2331 MF.getTarget().Options.GuaranteedTailCallOpt))
2332 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2334 // If the function takes variable number of arguments, make a frame index for
2335 // the start of the first vararg value... for expansion of llvm.va_start.
2337 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2338 CallConv != CallingConv::X86_ThisCall)) {
2339 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2342 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2344 // FIXME: We should really autogenerate these arrays
2345 static const MCPhysReg GPR64ArgRegsWin64[] = {
2346 X86::RCX, X86::RDX, X86::R8, X86::R9
2348 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2349 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2351 static const MCPhysReg XMMArgRegs64Bit[] = {
2352 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2353 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2355 const MCPhysReg *GPR64ArgRegs;
2356 unsigned NumXMMRegs = 0;
2359 // The XMM registers which might contain var arg parameters are shadowed
2360 // in their paired GPR. So we only need to save the GPR to their home
2362 TotalNumIntRegs = 4;
2363 GPR64ArgRegs = GPR64ArgRegsWin64;
2365 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2366 GPR64ArgRegs = GPR64ArgRegs64Bit;
2368 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2371 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2374 bool NoImplicitFloatOps = Fn->getAttributes().
2375 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2376 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2377 "SSE register cannot be used when SSE is disabled!");
2378 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2379 NoImplicitFloatOps) &&
2380 "SSE register cannot be used when SSE is disabled!");
2381 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2382 !Subtarget->hasSSE1())
2383 // Kernel mode asks for SSE to be disabled, so don't push them
2385 TotalNumXMMRegs = 0;
2388 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2389 // Get to the caller-allocated home save location. Add 8 to account
2390 // for the return address.
2391 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2392 FuncInfo->setRegSaveFrameIndex(
2393 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2394 // Fixup to set vararg frame on shadow area (4 x i64).
2396 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2398 // For X86-64, if there are vararg parameters that are passed via
2399 // registers, then we must store them to their spots on the stack so
2400 // they may be loaded by deferencing the result of va_next.
2401 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2402 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2403 FuncInfo->setRegSaveFrameIndex(
2404 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2408 // Store the integer parameter registers.
2409 SmallVector<SDValue, 8> MemOps;
2410 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2412 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2413 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2414 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2415 DAG.getIntPtrConstant(Offset));
2416 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2417 &X86::GR64RegClass);
2418 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2420 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2421 MachinePointerInfo::getFixedStack(
2422 FuncInfo->getRegSaveFrameIndex(), Offset),
2424 MemOps.push_back(Store);
2428 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2429 // Now store the XMM (fp + vector) parameter registers.
2430 SmallVector<SDValue, 11> SaveXMMOps;
2431 SaveXMMOps.push_back(Chain);
2433 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2434 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2435 SaveXMMOps.push_back(ALVal);
2437 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2438 FuncInfo->getRegSaveFrameIndex()));
2439 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2440 FuncInfo->getVarArgsFPOffset()));
2442 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2443 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2444 &X86::VR128RegClass);
2445 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2446 SaveXMMOps.push_back(Val);
2448 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2449 MVT::Other, SaveXMMOps));
2452 if (!MemOps.empty())
2453 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2457 // Some CCs need callee pop.
2458 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2459 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2460 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2462 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2463 // If this is an sret function, the return should pop the hidden pointer.
2464 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2465 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2466 argsAreStructReturn(Ins) == StackStructReturn)
2467 FuncInfo->setBytesToPopOnReturn(4);
2471 // RegSaveFrameIndex is X86-64 only.
2472 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2473 if (CallConv == CallingConv::X86_FastCall ||
2474 CallConv == CallingConv::X86_ThisCall)
2475 // fastcc functions can't have varargs.
2476 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2479 FuncInfo->setArgumentStackSize(StackSize);
2485 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2486 SDValue StackPtr, SDValue Arg,
2487 SDLoc dl, SelectionDAG &DAG,
2488 const CCValAssign &VA,
2489 ISD::ArgFlagsTy Flags) const {
2490 unsigned LocMemOffset = VA.getLocMemOffset();
2491 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2492 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2493 if (Flags.isByVal())
2494 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2496 return DAG.getStore(Chain, dl, Arg, PtrOff,
2497 MachinePointerInfo::getStack(LocMemOffset),
2501 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2502 /// optimization is performed and it is required.
2504 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2505 SDValue &OutRetAddr, SDValue Chain,
2506 bool IsTailCall, bool Is64Bit,
2507 int FPDiff, SDLoc dl) const {
2508 // Adjust the Return address stack slot.
2509 EVT VT = getPointerTy();
2510 OutRetAddr = getReturnAddressFrameIndex(DAG);
2512 // Load the "old" Return address.
2513 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2514 false, false, false, 0);
2515 return SDValue(OutRetAddr.getNode(), 1);
2518 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2519 /// optimization is performed and it is required (FPDiff!=0).
2520 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2521 SDValue Chain, SDValue RetAddrFrIdx,
2522 EVT PtrVT, unsigned SlotSize,
2523 int FPDiff, SDLoc dl) {
2524 // Store the return address to the appropriate stack slot.
2525 if (!FPDiff) return Chain;
2526 // Calculate the new stack slot for the return address.
2527 int NewReturnAddrFI =
2528 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2530 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2531 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2532 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2538 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2539 SmallVectorImpl<SDValue> &InVals) const {
2540 SelectionDAG &DAG = CLI.DAG;
2542 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2543 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2544 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2545 SDValue Chain = CLI.Chain;
2546 SDValue Callee = CLI.Callee;
2547 CallingConv::ID CallConv = CLI.CallConv;
2548 bool &isTailCall = CLI.IsTailCall;
2549 bool isVarArg = CLI.IsVarArg;
2551 MachineFunction &MF = DAG.getMachineFunction();
2552 bool Is64Bit = Subtarget->is64Bit();
2553 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2554 StructReturnType SR = callIsStructReturn(Outs);
2555 bool IsSibcall = false;
2557 if (MF.getTarget().Options.DisableTailCalls)
2560 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2562 // Force this to be a tail call. The verifier rules are enough to ensure
2563 // that we can lower this successfully without moving the return address
2566 } else if (isTailCall) {
2567 // Check if it's really possible to do a tail call.
2568 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2569 isVarArg, SR != NotStructReturn,
2570 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2571 Outs, OutVals, Ins, DAG);
2573 // Sibcalls are automatically detected tailcalls which do not require
2575 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2582 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2583 "Var args not supported with calling convention fastcc, ghc or hipe");
2585 // Analyze operands of the call, assigning locations to each operand.
2586 SmallVector<CCValAssign, 16> ArgLocs;
2587 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2588 ArgLocs, *DAG.getContext());
2590 // Allocate shadow area for Win64
2592 CCInfo.AllocateStack(32, 8);
2594 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2596 // Get a count of how many bytes are to be pushed on the stack.
2597 unsigned NumBytes = CCInfo.getNextStackOffset();
2599 // This is a sibcall. The memory operands are available in caller's
2600 // own caller's stack.
2602 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2603 IsTailCallConvention(CallConv))
2604 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2607 if (isTailCall && !IsSibcall && !IsMustTail) {
2608 // Lower arguments at fp - stackoffset + fpdiff.
2609 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2610 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2612 FPDiff = NumBytesCallerPushed - NumBytes;
2614 // Set the delta of movement of the returnaddr stackslot.
2615 // But only set if delta is greater than previous delta.
2616 if (FPDiff < X86Info->getTCReturnAddrDelta())
2617 X86Info->setTCReturnAddrDelta(FPDiff);
2620 unsigned NumBytesToPush = NumBytes;
2621 unsigned NumBytesToPop = NumBytes;
2623 // If we have an inalloca argument, all stack space has already been allocated
2624 // for us and be right at the top of the stack. We don't support multiple
2625 // arguments passed in memory when using inalloca.
2626 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2628 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2629 "an inalloca argument must be the only memory argument");
2633 Chain = DAG.getCALLSEQ_START(
2634 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2636 SDValue RetAddrFrIdx;
2637 // Load return address for tail calls.
2638 if (isTailCall && FPDiff)
2639 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2640 Is64Bit, FPDiff, dl);
2642 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2643 SmallVector<SDValue, 8> MemOpChains;
2646 // Walk the register/memloc assignments, inserting copies/loads. In the case
2647 // of tail call optimization arguments are handle later.
2648 const X86RegisterInfo *RegInfo =
2649 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2650 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2651 // Skip inalloca arguments, they have already been written.
2652 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2653 if (Flags.isInAlloca())
2656 CCValAssign &VA = ArgLocs[i];
2657 EVT RegVT = VA.getLocVT();
2658 SDValue Arg = OutVals[i];
2659 bool isByVal = Flags.isByVal();
2661 // Promote the value if needed.
2662 switch (VA.getLocInfo()) {
2663 default: llvm_unreachable("Unknown loc info!");
2664 case CCValAssign::Full: break;
2665 case CCValAssign::SExt:
2666 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2668 case CCValAssign::ZExt:
2669 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2671 case CCValAssign::AExt:
2672 if (RegVT.is128BitVector()) {
2673 // Special case: passing MMX values in XMM registers.
2674 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2675 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2676 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2678 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2680 case CCValAssign::BCvt:
2681 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2683 case CCValAssign::Indirect: {
2684 // Store the argument.
2685 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2686 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2687 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2688 MachinePointerInfo::getFixedStack(FI),
2695 if (VA.isRegLoc()) {
2696 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2697 if (isVarArg && IsWin64) {
2698 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2699 // shadow reg if callee is a varargs function.
2700 unsigned ShadowReg = 0;
2701 switch (VA.getLocReg()) {
2702 case X86::XMM0: ShadowReg = X86::RCX; break;
2703 case X86::XMM1: ShadowReg = X86::RDX; break;
2704 case X86::XMM2: ShadowReg = X86::R8; break;
2705 case X86::XMM3: ShadowReg = X86::R9; break;
2708 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2710 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2711 assert(VA.isMemLoc());
2712 if (!StackPtr.getNode())
2713 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2715 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2716 dl, DAG, VA, Flags));
2720 if (!MemOpChains.empty())
2721 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2723 if (Subtarget->isPICStyleGOT()) {
2724 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2727 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2728 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2730 // If we are tail calling and generating PIC/GOT style code load the
2731 // address of the callee into ECX. The value in ecx is used as target of
2732 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2733 // for tail calls on PIC/GOT architectures. Normally we would just put the
2734 // address of GOT into ebx and then call target@PLT. But for tail calls
2735 // ebx would be restored (since ebx is callee saved) before jumping to the
2738 // Note: The actual moving to ECX is done further down.
2739 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2740 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2741 !G->getGlobal()->hasProtectedVisibility())
2742 Callee = LowerGlobalAddress(Callee, DAG);
2743 else if (isa<ExternalSymbolSDNode>(Callee))
2744 Callee = LowerExternalSymbol(Callee, DAG);
2748 if (Is64Bit && isVarArg && !IsWin64) {
2749 // From AMD64 ABI document:
2750 // For calls that may call functions that use varargs or stdargs
2751 // (prototype-less calls or calls to functions containing ellipsis (...) in
2752 // the declaration) %al is used as hidden argument to specify the number
2753 // of SSE registers used. The contents of %al do not need to match exactly
2754 // the number of registers, but must be an ubound on the number of SSE
2755 // registers used and is in the range 0 - 8 inclusive.
2757 // Count the number of XMM registers allocated.
2758 static const MCPhysReg XMMArgRegs[] = {
2759 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2760 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2762 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2763 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2764 && "SSE registers cannot be used when SSE is disabled");
2766 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2767 DAG.getConstant(NumXMMRegs, MVT::i8)));
2770 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2771 // don't need this because the eligibility check rejects calls that require
2772 // shuffling arguments passed in memory.
2773 if (!IsSibcall && isTailCall) {
2774 // Force all the incoming stack arguments to be loaded from the stack
2775 // before any new outgoing arguments are stored to the stack, because the
2776 // outgoing stack slots may alias the incoming argument stack slots, and
2777 // the alias isn't otherwise explicit. This is slightly more conservative
2778 // than necessary, because it means that each store effectively depends
2779 // on every argument instead of just those arguments it would clobber.
2780 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2782 SmallVector<SDValue, 8> MemOpChains2;
2785 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2786 CCValAssign &VA = ArgLocs[i];
2789 assert(VA.isMemLoc());
2790 SDValue Arg = OutVals[i];
2791 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2792 // Skip inalloca arguments. They don't require any work.
2793 if (Flags.isInAlloca())
2795 // Create frame index.
2796 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2797 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2798 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2799 FIN = DAG.getFrameIndex(FI, getPointerTy());
2801 if (Flags.isByVal()) {
2802 // Copy relative to framepointer.
2803 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2804 if (!StackPtr.getNode())
2805 StackPtr = DAG.getCopyFromReg(Chain, dl,
2806 RegInfo->getStackRegister(),
2808 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2810 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2814 // Store relative to framepointer.
2815 MemOpChains2.push_back(
2816 DAG.getStore(ArgChain, dl, Arg, FIN,
2817 MachinePointerInfo::getFixedStack(FI),
2822 if (!MemOpChains2.empty())
2823 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2825 // Store the return address to the appropriate stack slot.
2826 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2827 getPointerTy(), RegInfo->getSlotSize(),
2831 // Build a sequence of copy-to-reg nodes chained together with token chain
2832 // and flag operands which copy the outgoing args into registers.
2834 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2835 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2836 RegsToPass[i].second, InFlag);
2837 InFlag = Chain.getValue(1);
2840 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2841 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2842 // In the 64-bit large code model, we have to make all calls
2843 // through a register, since the call instruction's 32-bit
2844 // pc-relative offset may not be large enough to hold the whole
2846 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2847 // If the callee is a GlobalAddress node (quite common, every direct call
2848 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2851 // We should use extra load for direct calls to dllimported functions in
2853 const GlobalValue *GV = G->getGlobal();
2854 if (!GV->hasDLLImportStorageClass()) {
2855 unsigned char OpFlags = 0;
2856 bool ExtraLoad = false;
2857 unsigned WrapperKind = ISD::DELETED_NODE;
2859 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2860 // external symbols most go through the PLT in PIC mode. If the symbol
2861 // has hidden or protected visibility, or if it is static or local, then
2862 // we don't need to use the PLT - we can directly call it.
2863 if (Subtarget->isTargetELF() &&
2864 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2865 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2866 OpFlags = X86II::MO_PLT;
2867 } else if (Subtarget->isPICStyleStubAny() &&
2868 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2869 (!Subtarget->getTargetTriple().isMacOSX() ||
2870 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2871 // PC-relative references to external symbols should go through $stub,
2872 // unless we're building with the leopard linker or later, which
2873 // automatically synthesizes these stubs.
2874 OpFlags = X86II::MO_DARWIN_STUB;
2875 } else if (Subtarget->isPICStyleRIPRel() &&
2876 isa<Function>(GV) &&
2877 cast<Function>(GV)->getAttributes().
2878 hasAttribute(AttributeSet::FunctionIndex,
2879 Attribute::NonLazyBind)) {
2880 // If the function is marked as non-lazy, generate an indirect call
2881 // which loads from the GOT directly. This avoids runtime overhead
2882 // at the cost of eager binding (and one extra byte of encoding).
2883 OpFlags = X86II::MO_GOTPCREL;
2884 WrapperKind = X86ISD::WrapperRIP;
2888 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2889 G->getOffset(), OpFlags);
2891 // Add a wrapper if needed.
2892 if (WrapperKind != ISD::DELETED_NODE)
2893 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2894 // Add extra indirection if needed.
2896 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2897 MachinePointerInfo::getGOT(),
2898 false, false, false, 0);
2900 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2901 unsigned char OpFlags = 0;
2903 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2904 // external symbols should go through the PLT.
2905 if (Subtarget->isTargetELF() &&
2906 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2907 OpFlags = X86II::MO_PLT;
2908 } else if (Subtarget->isPICStyleStubAny() &&
2909 (!Subtarget->getTargetTriple().isMacOSX() ||
2910 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2911 // PC-relative references to external symbols should go through $stub,
2912 // unless we're building with the leopard linker or later, which
2913 // automatically synthesizes these stubs.
2914 OpFlags = X86II::MO_DARWIN_STUB;
2917 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2921 // Returns a chain & a flag for retval copy to use.
2922 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2923 SmallVector<SDValue, 8> Ops;
2925 if (!IsSibcall && isTailCall) {
2926 Chain = DAG.getCALLSEQ_END(Chain,
2927 DAG.getIntPtrConstant(NumBytesToPop, true),
2928 DAG.getIntPtrConstant(0, true), InFlag, dl);
2929 InFlag = Chain.getValue(1);
2932 Ops.push_back(Chain);
2933 Ops.push_back(Callee);
2936 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2938 // Add argument registers to the end of the list so that they are known live
2940 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2941 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2942 RegsToPass[i].second.getValueType()));
2944 // Add a register mask operand representing the call-preserved registers.
2945 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2946 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2947 assert(Mask && "Missing call preserved mask for calling convention");
2948 Ops.push_back(DAG.getRegisterMask(Mask));
2950 if (InFlag.getNode())
2951 Ops.push_back(InFlag);
2955 //// If this is the first return lowered for this function, add the regs
2956 //// to the liveout set for the function.
2957 // This isn't right, although it's probably harmless on x86; liveouts
2958 // should be computed from returns not tail calls. Consider a void
2959 // function making a tail call to a function returning int.
2960 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2963 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2964 InFlag = Chain.getValue(1);
2966 // Create the CALLSEQ_END node.
2967 unsigned NumBytesForCalleeToPop;
2968 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2969 getTargetMachine().Options.GuaranteedTailCallOpt))
2970 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2971 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2972 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2973 SR == StackStructReturn)
2974 // If this is a call to a struct-return function, the callee
2975 // pops the hidden struct pointer, so we have to push it back.
2976 // This is common for Darwin/X86, Linux & Mingw32 targets.
2977 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2978 NumBytesForCalleeToPop = 4;
2980 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2982 // Returns a flag for retval copy to use.
2984 Chain = DAG.getCALLSEQ_END(Chain,
2985 DAG.getIntPtrConstant(NumBytesToPop, true),
2986 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2989 InFlag = Chain.getValue(1);
2992 // Handle result values, copying them out of physregs into vregs that we
2994 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2995 Ins, dl, DAG, InVals);
2998 //===----------------------------------------------------------------------===//
2999 // Fast Calling Convention (tail call) implementation
3000 //===----------------------------------------------------------------------===//
3002 // Like std call, callee cleans arguments, convention except that ECX is
3003 // reserved for storing the tail called function address. Only 2 registers are
3004 // free for argument passing (inreg). Tail call optimization is performed
3006 // * tailcallopt is enabled
3007 // * caller/callee are fastcc
3008 // On X86_64 architecture with GOT-style position independent code only local
3009 // (within module) calls are supported at the moment.
3010 // To keep the stack aligned according to platform abi the function
3011 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3012 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3013 // If a tail called function callee has more arguments than the caller the
3014 // caller needs to make sure that there is room to move the RETADDR to. This is
3015 // achieved by reserving an area the size of the argument delta right after the
3016 // original REtADDR, but before the saved framepointer or the spilled registers
3017 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3029 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3030 /// for a 16 byte align requirement.
3032 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3033 SelectionDAG& DAG) const {
3034 MachineFunction &MF = DAG.getMachineFunction();
3035 const TargetMachine &TM = MF.getTarget();
3036 const X86RegisterInfo *RegInfo =
3037 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3038 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3039 unsigned StackAlignment = TFI.getStackAlignment();
3040 uint64_t AlignMask = StackAlignment - 1;
3041 int64_t Offset = StackSize;
3042 unsigned SlotSize = RegInfo->getSlotSize();
3043 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3044 // Number smaller than 12 so just add the difference.
3045 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3047 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3048 Offset = ((~AlignMask) & Offset) + StackAlignment +
3049 (StackAlignment-SlotSize);
3054 /// MatchingStackOffset - Return true if the given stack call argument is
3055 /// already available in the same position (relatively) of the caller's
3056 /// incoming argument stack.
3058 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3059 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3060 const X86InstrInfo *TII) {
3061 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3063 if (Arg.getOpcode() == ISD::CopyFromReg) {
3064 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3065 if (!TargetRegisterInfo::isVirtualRegister(VR))
3067 MachineInstr *Def = MRI->getVRegDef(VR);
3070 if (!Flags.isByVal()) {
3071 if (!TII->isLoadFromStackSlot(Def, FI))
3074 unsigned Opcode = Def->getOpcode();
3075 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3076 Def->getOperand(1).isFI()) {
3077 FI = Def->getOperand(1).getIndex();
3078 Bytes = Flags.getByValSize();
3082 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3083 if (Flags.isByVal())
3084 // ByVal argument is passed in as a pointer but it's now being
3085 // dereferenced. e.g.
3086 // define @foo(%struct.X* %A) {
3087 // tail call @bar(%struct.X* byval %A)
3090 SDValue Ptr = Ld->getBasePtr();
3091 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3094 FI = FINode->getIndex();
3095 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3096 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3097 FI = FINode->getIndex();
3098 Bytes = Flags.getByValSize();
3102 assert(FI != INT_MAX);
3103 if (!MFI->isFixedObjectIndex(FI))
3105 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3108 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3109 /// for tail call optimization. Targets which want to do tail call
3110 /// optimization should implement this function.
3112 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3113 CallingConv::ID CalleeCC,
3115 bool isCalleeStructRet,
3116 bool isCallerStructRet,
3118 const SmallVectorImpl<ISD::OutputArg> &Outs,
3119 const SmallVectorImpl<SDValue> &OutVals,
3120 const SmallVectorImpl<ISD::InputArg> &Ins,
3121 SelectionDAG &DAG) const {
3122 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3125 // If -tailcallopt is specified, make fastcc functions tail-callable.
3126 const MachineFunction &MF = DAG.getMachineFunction();
3127 const Function *CallerF = MF.getFunction();
3129 // If the function return type is x86_fp80 and the callee return type is not,
3130 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3131 // perform a tailcall optimization here.
3132 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3135 CallingConv::ID CallerCC = CallerF->getCallingConv();
3136 bool CCMatch = CallerCC == CalleeCC;
3137 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3138 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3140 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3141 if (IsTailCallConvention(CalleeCC) && CCMatch)
3146 // Look for obvious safe cases to perform tail call optimization that do not
3147 // require ABI changes. This is what gcc calls sibcall.
3149 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3150 // emit a special epilogue.
3151 const X86RegisterInfo *RegInfo =
3152 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3153 if (RegInfo->needsStackRealignment(MF))
3156 // Also avoid sibcall optimization if either caller or callee uses struct
3157 // return semantics.
3158 if (isCalleeStructRet || isCallerStructRet)
3161 // An stdcall/thiscall caller is expected to clean up its arguments; the
3162 // callee isn't going to do that.
3163 // FIXME: this is more restrictive than needed. We could produce a tailcall
3164 // when the stack adjustment matches. For example, with a thiscall that takes
3165 // only one argument.
3166 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3167 CallerCC == CallingConv::X86_ThisCall))
3170 // Do not sibcall optimize vararg calls unless all arguments are passed via
3172 if (isVarArg && !Outs.empty()) {
3174 // Optimizing for varargs on Win64 is unlikely to be safe without
3175 // additional testing.
3176 if (IsCalleeWin64 || IsCallerWin64)
3179 SmallVector<CCValAssign, 16> ArgLocs;
3180 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3181 getTargetMachine(), ArgLocs, *DAG.getContext());
3183 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3184 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3185 if (!ArgLocs[i].isRegLoc())
3189 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3190 // stack. Therefore, if it's not used by the call it is not safe to optimize
3191 // this into a sibcall.
3192 bool Unused = false;
3193 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3200 SmallVector<CCValAssign, 16> RVLocs;
3201 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3202 getTargetMachine(), RVLocs, *DAG.getContext());
3203 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3204 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3205 CCValAssign &VA = RVLocs[i];
3206 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3211 // If the calling conventions do not match, then we'd better make sure the
3212 // results are returned in the same way as what the caller expects.
3214 SmallVector<CCValAssign, 16> RVLocs1;
3215 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3216 getTargetMachine(), RVLocs1, *DAG.getContext());
3217 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3219 SmallVector<CCValAssign, 16> RVLocs2;
3220 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3221 getTargetMachine(), RVLocs2, *DAG.getContext());
3222 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3224 if (RVLocs1.size() != RVLocs2.size())
3226 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3227 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3229 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3231 if (RVLocs1[i].isRegLoc()) {
3232 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3235 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3241 // If the callee takes no arguments then go on to check the results of the
3243 if (!Outs.empty()) {
3244 // Check if stack adjustment is needed. For now, do not do this if any
3245 // argument is passed on the stack.
3246 SmallVector<CCValAssign, 16> ArgLocs;
3247 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3248 getTargetMachine(), ArgLocs, *DAG.getContext());
3250 // Allocate shadow area for Win64
3252 CCInfo.AllocateStack(32, 8);
3254 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3255 if (CCInfo.getNextStackOffset()) {
3256 MachineFunction &MF = DAG.getMachineFunction();
3257 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3260 // Check if the arguments are already laid out in the right way as
3261 // the caller's fixed stack objects.
3262 MachineFrameInfo *MFI = MF.getFrameInfo();
3263 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3264 const X86InstrInfo *TII =
3265 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3266 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3267 CCValAssign &VA = ArgLocs[i];
3268 SDValue Arg = OutVals[i];
3269 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3270 if (VA.getLocInfo() == CCValAssign::Indirect)
3272 if (!VA.isRegLoc()) {
3273 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3280 // If the tailcall address may be in a register, then make sure it's
3281 // possible to register allocate for it. In 32-bit, the call address can
3282 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3283 // callee-saved registers are restored. These happen to be the same
3284 // registers used to pass 'inreg' arguments so watch out for those.
3285 if (!Subtarget->is64Bit() &&
3286 ((!isa<GlobalAddressSDNode>(Callee) &&
3287 !isa<ExternalSymbolSDNode>(Callee)) ||
3288 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3289 unsigned NumInRegs = 0;
3290 // In PIC we need an extra register to formulate the address computation
3292 unsigned MaxInRegs =
3293 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3295 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3296 CCValAssign &VA = ArgLocs[i];
3299 unsigned Reg = VA.getLocReg();
3302 case X86::EAX: case X86::EDX: case X86::ECX:
3303 if (++NumInRegs == MaxInRegs)
3315 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3316 const TargetLibraryInfo *libInfo) const {
3317 return X86::createFastISel(funcInfo, libInfo);
3320 //===----------------------------------------------------------------------===//
3321 // Other Lowering Hooks
3322 //===----------------------------------------------------------------------===//
3324 static bool MayFoldLoad(SDValue Op) {
3325 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3328 static bool MayFoldIntoStore(SDValue Op) {
3329 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3332 static bool isTargetShuffle(unsigned Opcode) {
3334 default: return false;
3335 case X86ISD::PSHUFD:
3336 case X86ISD::PSHUFHW:
3337 case X86ISD::PSHUFLW:
3339 case X86ISD::PALIGNR:
3340 case X86ISD::MOVLHPS:
3341 case X86ISD::MOVLHPD:
3342 case X86ISD::MOVHLPS:
3343 case X86ISD::MOVLPS:
3344 case X86ISD::MOVLPD:
3345 case X86ISD::MOVSHDUP:
3346 case X86ISD::MOVSLDUP:
3347 case X86ISD::MOVDDUP:
3350 case X86ISD::UNPCKL:
3351 case X86ISD::UNPCKH:
3352 case X86ISD::VPERMILP:
3353 case X86ISD::VPERM2X128:
3354 case X86ISD::VPERMI:
3359 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3360 SDValue V1, SelectionDAG &DAG) {
3362 default: llvm_unreachable("Unknown x86 shuffle node");
3363 case X86ISD::MOVSHDUP:
3364 case X86ISD::MOVSLDUP:
3365 case X86ISD::MOVDDUP:
3366 return DAG.getNode(Opc, dl, VT, V1);
3370 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3371 SDValue V1, unsigned TargetMask,
3372 SelectionDAG &DAG) {
3374 default: llvm_unreachable("Unknown x86 shuffle node");
3375 case X86ISD::PSHUFD:
3376 case X86ISD::PSHUFHW:
3377 case X86ISD::PSHUFLW:
3378 case X86ISD::VPERMILP:
3379 case X86ISD::VPERMI:
3380 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3384 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3385 SDValue V1, SDValue V2, unsigned TargetMask,
3386 SelectionDAG &DAG) {
3388 default: llvm_unreachable("Unknown x86 shuffle node");
3389 case X86ISD::PALIGNR:
3391 case X86ISD::VPERM2X128:
3392 return DAG.getNode(Opc, dl, VT, V1, V2,
3393 DAG.getConstant(TargetMask, MVT::i8));
3397 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3398 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3400 default: llvm_unreachable("Unknown x86 shuffle node");
3401 case X86ISD::MOVLHPS:
3402 case X86ISD::MOVLHPD:
3403 case X86ISD::MOVHLPS:
3404 case X86ISD::MOVLPS:
3405 case X86ISD::MOVLPD:
3408 case X86ISD::UNPCKL:
3409 case X86ISD::UNPCKH:
3410 return DAG.getNode(Opc, dl, VT, V1, V2);
3414 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3415 MachineFunction &MF = DAG.getMachineFunction();
3416 const X86RegisterInfo *RegInfo =
3417 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3418 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3419 int ReturnAddrIndex = FuncInfo->getRAIndex();
3421 if (ReturnAddrIndex == 0) {
3422 // Set up a frame object for the return address.
3423 unsigned SlotSize = RegInfo->getSlotSize();
3424 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3427 FuncInfo->setRAIndex(ReturnAddrIndex);
3430 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3433 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3434 bool hasSymbolicDisplacement) {
3435 // Offset should fit into 32 bit immediate field.
3436 if (!isInt<32>(Offset))
3439 // If we don't have a symbolic displacement - we don't have any extra
3441 if (!hasSymbolicDisplacement)
3444 // FIXME: Some tweaks might be needed for medium code model.
3445 if (M != CodeModel::Small && M != CodeModel::Kernel)
3448 // For small code model we assume that latest object is 16MB before end of 31
3449 // bits boundary. We may also accept pretty large negative constants knowing
3450 // that all objects are in the positive half of address space.
3451 if (M == CodeModel::Small && Offset < 16*1024*1024)
3454 // For kernel code model we know that all object resist in the negative half
3455 // of 32bits address space. We may not accept negative offsets, since they may
3456 // be just off and we may accept pretty large positive ones.
3457 if (M == CodeModel::Kernel && Offset > 0)
3463 /// isCalleePop - Determines whether the callee is required to pop its
3464 /// own arguments. Callee pop is necessary to support tail calls.
3465 bool X86::isCalleePop(CallingConv::ID CallingConv,
3466 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3470 switch (CallingConv) {
3473 case CallingConv::X86_StdCall:
3475 case CallingConv::X86_FastCall:
3477 case CallingConv::X86_ThisCall:
3479 case CallingConv::Fast:
3481 case CallingConv::GHC:
3483 case CallingConv::HiPE:
3488 /// \brief Return true if the condition is an unsigned comparison operation.
3489 static bool isX86CCUnsigned(unsigned X86CC) {
3491 default: llvm_unreachable("Invalid integer condition!");
3492 case X86::COND_E: return true;
3493 case X86::COND_G: return false;
3494 case X86::COND_GE: return false;
3495 case X86::COND_L: return false;
3496 case X86::COND_LE: return false;
3497 case X86::COND_NE: return true;
3498 case X86::COND_B: return true;
3499 case X86::COND_A: return true;
3500 case X86::COND_BE: return true;
3501 case X86::COND_AE: return true;
3503 llvm_unreachable("covered switch fell through?!");
3506 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3507 /// specific condition code, returning the condition code and the LHS/RHS of the
3508 /// comparison to make.
3509 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3510 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3512 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3513 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3514 // X > -1 -> X == 0, jump !sign.
3515 RHS = DAG.getConstant(0, RHS.getValueType());
3516 return X86::COND_NS;
3518 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3519 // X < 0 -> X == 0, jump on sign.
3522 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3524 RHS = DAG.getConstant(0, RHS.getValueType());
3525 return X86::COND_LE;
3529 switch (SetCCOpcode) {
3530 default: llvm_unreachable("Invalid integer condition!");
3531 case ISD::SETEQ: return X86::COND_E;
3532 case ISD::SETGT: return X86::COND_G;
3533 case ISD::SETGE: return X86::COND_GE;
3534 case ISD::SETLT: return X86::COND_L;
3535 case ISD::SETLE: return X86::COND_LE;
3536 case ISD::SETNE: return X86::COND_NE;
3537 case ISD::SETULT: return X86::COND_B;
3538 case ISD::SETUGT: return X86::COND_A;
3539 case ISD::SETULE: return X86::COND_BE;
3540 case ISD::SETUGE: return X86::COND_AE;
3544 // First determine if it is required or is profitable to flip the operands.
3546 // If LHS is a foldable load, but RHS is not, flip the condition.
3547 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3548 !ISD::isNON_EXTLoad(RHS.getNode())) {
3549 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3550 std::swap(LHS, RHS);
3553 switch (SetCCOpcode) {
3559 std::swap(LHS, RHS);
3563 // On a floating point condition, the flags are set as follows:
3565 // 0 | 0 | 0 | X > Y
3566 // 0 | 0 | 1 | X < Y
3567 // 1 | 0 | 0 | X == Y
3568 // 1 | 1 | 1 | unordered
3569 switch (SetCCOpcode) {
3570 default: llvm_unreachable("Condcode should be pre-legalized away");
3572 case ISD::SETEQ: return X86::COND_E;
3573 case ISD::SETOLT: // flipped
3575 case ISD::SETGT: return X86::COND_A;
3576 case ISD::SETOLE: // flipped
3578 case ISD::SETGE: return X86::COND_AE;
3579 case ISD::SETUGT: // flipped
3581 case ISD::SETLT: return X86::COND_B;
3582 case ISD::SETUGE: // flipped
3584 case ISD::SETLE: return X86::COND_BE;
3586 case ISD::SETNE: return X86::COND_NE;
3587 case ISD::SETUO: return X86::COND_P;
3588 case ISD::SETO: return X86::COND_NP;
3590 case ISD::SETUNE: return X86::COND_INVALID;
3594 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3595 /// code. Current x86 isa includes the following FP cmov instructions:
3596 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3597 static bool hasFPCMov(unsigned X86CC) {
3613 /// isFPImmLegal - Returns true if the target can instruction select the
3614 /// specified FP immediate natively. If false, the legalizer will
3615 /// materialize the FP immediate as a load from a constant pool.
3616 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3617 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3618 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3624 /// \brief Returns true if it is beneficial to convert a load of a constant
3625 /// to just the constant itself.
3626 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3628 assert(Ty->isIntegerTy());
3630 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3631 if (BitSize == 0 || BitSize > 64)
3636 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3637 /// the specified range (L, H].
3638 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3639 return (Val < 0) || (Val >= Low && Val < Hi);
3642 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3643 /// specified value.
3644 static bool isUndefOrEqual(int Val, int CmpVal) {
3645 return (Val < 0 || Val == CmpVal);
3648 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3649 /// from position Pos and ending in Pos+Size, falls within the specified
3650 /// sequential range (L, L+Pos]. or is undef.
3651 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3652 unsigned Pos, unsigned Size, int Low) {
3653 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3654 if (!isUndefOrEqual(Mask[i], Low))
3659 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3660 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3661 /// the second operand.
3662 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3663 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3664 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3665 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3666 return (Mask[0] < 2 && Mask[1] < 2);
3670 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3671 /// is suitable for input to PSHUFHW.
3672 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3673 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3676 // Lower quadword copied in order or undef.
3677 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3680 // Upper quadword shuffled.
3681 for (unsigned i = 4; i != 8; ++i)
3682 if (!isUndefOrInRange(Mask[i], 4, 8))
3685 if (VT == MVT::v16i16) {
3686 // Lower quadword copied in order or undef.
3687 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3690 // Upper quadword shuffled.
3691 for (unsigned i = 12; i != 16; ++i)
3692 if (!isUndefOrInRange(Mask[i], 12, 16))
3699 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3700 /// is suitable for input to PSHUFLW.
3701 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3702 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3705 // Upper quadword copied in order.
3706 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3709 // Lower quadword shuffled.
3710 for (unsigned i = 0; i != 4; ++i)
3711 if (!isUndefOrInRange(Mask[i], 0, 4))
3714 if (VT == MVT::v16i16) {
3715 // Upper quadword copied in order.
3716 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3719 // Lower quadword shuffled.
3720 for (unsigned i = 8; i != 12; ++i)
3721 if (!isUndefOrInRange(Mask[i], 8, 12))
3728 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3729 /// is suitable for input to PALIGNR.
3730 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3731 const X86Subtarget *Subtarget) {
3732 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3733 (VT.is256BitVector() && !Subtarget->hasInt256()))
3736 unsigned NumElts = VT.getVectorNumElements();
3737 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3738 unsigned NumLaneElts = NumElts/NumLanes;
3740 // Do not handle 64-bit element shuffles with palignr.
3741 if (NumLaneElts == 2)
3744 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3746 for (i = 0; i != NumLaneElts; ++i) {
3751 // Lane is all undef, go to next lane
3752 if (i == NumLaneElts)
3755 int Start = Mask[i+l];
3757 // Make sure its in this lane in one of the sources
3758 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3759 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3762 // If not lane 0, then we must match lane 0
3763 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3766 // Correct second source to be contiguous with first source
3767 if (Start >= (int)NumElts)
3768 Start -= NumElts - NumLaneElts;
3770 // Make sure we're shifting in the right direction.
3771 if (Start <= (int)(i+l))
3776 // Check the rest of the elements to see if they are consecutive.
3777 for (++i; i != NumLaneElts; ++i) {
3778 int Idx = Mask[i+l];
3780 // Make sure its in this lane
3781 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3782 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3785 // If not lane 0, then we must match lane 0
3786 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3789 if (Idx >= (int)NumElts)
3790 Idx -= NumElts - NumLaneElts;
3792 if (!isUndefOrEqual(Idx, Start+i))
3801 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3802 /// the two vector operands have swapped position.
3803 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3804 unsigned NumElems) {
3805 for (unsigned i = 0; i != NumElems; ++i) {
3809 else if (idx < (int)NumElems)
3810 Mask[i] = idx + NumElems;
3812 Mask[i] = idx - NumElems;
3816 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3817 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3818 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3819 /// reverse of what x86 shuffles want.
3820 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3822 unsigned NumElems = VT.getVectorNumElements();
3823 unsigned NumLanes = VT.getSizeInBits()/128;
3824 unsigned NumLaneElems = NumElems/NumLanes;
3826 if (NumLaneElems != 2 && NumLaneElems != 4)
3829 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3830 bool symetricMaskRequired =
3831 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3833 // VSHUFPSY divides the resulting vector into 4 chunks.
3834 // The sources are also splitted into 4 chunks, and each destination
3835 // chunk must come from a different source chunk.
3837 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3838 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3840 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3841 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3843 // VSHUFPDY divides the resulting vector into 4 chunks.
3844 // The sources are also splitted into 4 chunks, and each destination
3845 // chunk must come from a different source chunk.
3847 // SRC1 => X3 X2 X1 X0
3848 // SRC2 => Y3 Y2 Y1 Y0
3850 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3852 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3853 unsigned HalfLaneElems = NumLaneElems/2;
3854 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3855 for (unsigned i = 0; i != NumLaneElems; ++i) {
3856 int Idx = Mask[i+l];
3857 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3858 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3860 // For VSHUFPSY, the mask of the second half must be the same as the
3861 // first but with the appropriate offsets. This works in the same way as
3862 // VPERMILPS works with masks.
3863 if (!symetricMaskRequired || Idx < 0)
3865 if (MaskVal[i] < 0) {
3866 MaskVal[i] = Idx - l;
3869 if ((signed)(Idx - l) != MaskVal[i])
3877 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3878 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3879 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3880 if (!VT.is128BitVector())
3883 unsigned NumElems = VT.getVectorNumElements();
3888 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3889 return isUndefOrEqual(Mask[0], 6) &&
3890 isUndefOrEqual(Mask[1], 7) &&
3891 isUndefOrEqual(Mask[2], 2) &&
3892 isUndefOrEqual(Mask[3], 3);
3895 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3896 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3898 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3899 if (!VT.is128BitVector())
3902 unsigned NumElems = VT.getVectorNumElements();
3907 return isUndefOrEqual(Mask[0], 2) &&
3908 isUndefOrEqual(Mask[1], 3) &&
3909 isUndefOrEqual(Mask[2], 2) &&
3910 isUndefOrEqual(Mask[3], 3);
3913 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3914 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3915 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3916 if (!VT.is128BitVector())
3919 unsigned NumElems = VT.getVectorNumElements();
3921 if (NumElems != 2 && NumElems != 4)
3924 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3925 if (!isUndefOrEqual(Mask[i], i + NumElems))
3928 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3929 if (!isUndefOrEqual(Mask[i], i))
3935 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3937 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3938 if (!VT.is128BitVector())
3941 unsigned NumElems = VT.getVectorNumElements();
3943 if (NumElems != 2 && NumElems != 4)
3946 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3947 if (!isUndefOrEqual(Mask[i], i))
3950 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3951 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3957 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3958 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3959 /// i. e: If all but one element come from the same vector.
3960 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3961 // TODO: Deal with AVX's VINSERTPS
3962 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3965 unsigned CorrectPosV1 = 0;
3966 unsigned CorrectPosV2 = 0;
3967 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3968 if (Mask[i] == -1) {
3976 else if (Mask[i] == i + 4)
3980 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3981 // We have 3 elements (undefs count as elements from any vector) from one
3982 // vector, and one from another.
3989 // Some special combinations that can be optimized.
3992 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3993 SelectionDAG &DAG) {
3994 MVT VT = SVOp->getSimpleValueType(0);
3997 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4000 ArrayRef<int> Mask = SVOp->getMask();
4002 // These are the special masks that may be optimized.
4003 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4004 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4005 bool MatchEvenMask = true;
4006 bool MatchOddMask = true;
4007 for (int i=0; i<8; ++i) {
4008 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4009 MatchEvenMask = false;
4010 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4011 MatchOddMask = false;
4014 if (!MatchEvenMask && !MatchOddMask)
4017 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4019 SDValue Op0 = SVOp->getOperand(0);
4020 SDValue Op1 = SVOp->getOperand(1);
4022 if (MatchEvenMask) {
4023 // Shift the second operand right to 32 bits.
4024 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4025 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4027 // Shift the first operand left to 32 bits.
4028 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4029 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4031 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4032 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4035 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4037 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4038 bool HasInt256, bool V2IsSplat = false) {
4040 assert(VT.getSizeInBits() >= 128 &&
4041 "Unsupported vector type for unpckl");
4043 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4045 unsigned NumOf256BitLanes;
4046 unsigned NumElts = VT.getVectorNumElements();
4047 if (VT.is256BitVector()) {
4048 if (NumElts != 4 && NumElts != 8 &&
4049 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4052 NumOf256BitLanes = 1;
4053 } else if (VT.is512BitVector()) {
4054 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4055 "Unsupported vector type for unpckh");
4057 NumOf256BitLanes = 2;
4060 NumOf256BitLanes = 1;
4063 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4064 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4066 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4067 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4068 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4069 int BitI = Mask[l256*NumEltsInStride+l+i];
4070 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4071 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4073 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4075 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4083 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4084 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4085 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4086 bool HasInt256, bool V2IsSplat = false) {
4087 assert(VT.getSizeInBits() >= 128 &&
4088 "Unsupported vector type for unpckh");
4090 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4092 unsigned NumOf256BitLanes;
4093 unsigned NumElts = VT.getVectorNumElements();
4094 if (VT.is256BitVector()) {
4095 if (NumElts != 4 && NumElts != 8 &&
4096 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4099 NumOf256BitLanes = 1;
4100 } else if (VT.is512BitVector()) {
4101 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4102 "Unsupported vector type for unpckh");
4104 NumOf256BitLanes = 2;
4107 NumOf256BitLanes = 1;
4110 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4111 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4113 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4114 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4115 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4116 int BitI = Mask[l256*NumEltsInStride+l+i];
4117 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4118 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4120 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4122 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4130 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4131 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4133 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4134 unsigned NumElts = VT.getVectorNumElements();
4135 bool Is256BitVec = VT.is256BitVector();
4137 if (VT.is512BitVector())
4139 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4140 "Unsupported vector type for unpckh");
4142 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4143 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4146 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4147 // FIXME: Need a better way to get rid of this, there's no latency difference
4148 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4149 // the former later. We should also remove the "_undef" special mask.
4150 if (NumElts == 4 && Is256BitVec)
4153 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4154 // independently on 128-bit lanes.
4155 unsigned NumLanes = VT.getSizeInBits()/128;
4156 unsigned NumLaneElts = NumElts/NumLanes;
4158 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4159 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4160 int BitI = Mask[l+i];
4161 int BitI1 = Mask[l+i+1];
4163 if (!isUndefOrEqual(BitI, j))
4165 if (!isUndefOrEqual(BitI1, j))
4173 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4174 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4176 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4177 unsigned NumElts = VT.getVectorNumElements();
4179 if (VT.is512BitVector())
4182 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4183 "Unsupported vector type for unpckh");
4185 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4186 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4189 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4190 // independently on 128-bit lanes.
4191 unsigned NumLanes = VT.getSizeInBits()/128;
4192 unsigned NumLaneElts = NumElts/NumLanes;
4194 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4195 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4196 int BitI = Mask[l+i];
4197 int BitI1 = Mask[l+i+1];
4198 if (!isUndefOrEqual(BitI, j))
4200 if (!isUndefOrEqual(BitI1, j))
4207 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4208 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4209 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4210 if (!VT.is512BitVector())
4213 unsigned NumElts = VT.getVectorNumElements();
4214 unsigned HalfSize = NumElts/2;
4215 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4216 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4221 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4222 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4230 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4231 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4232 /// MOVSD, and MOVD, i.e. setting the lowest element.
4233 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4234 if (VT.getVectorElementType().getSizeInBits() < 32)
4236 if (!VT.is128BitVector())
4239 unsigned NumElts = VT.getVectorNumElements();
4241 if (!isUndefOrEqual(Mask[0], NumElts))
4244 for (unsigned i = 1; i != NumElts; ++i)
4245 if (!isUndefOrEqual(Mask[i], i))
4251 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4252 /// as permutations between 128-bit chunks or halves. As an example: this
4254 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4255 /// The first half comes from the second half of V1 and the second half from the
4256 /// the second half of V2.
4257 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4258 if (!HasFp256 || !VT.is256BitVector())
4261 // The shuffle result is divided into half A and half B. In total the two
4262 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4263 // B must come from C, D, E or F.
4264 unsigned HalfSize = VT.getVectorNumElements()/2;
4265 bool MatchA = false, MatchB = false;
4267 // Check if A comes from one of C, D, E, F.
4268 for (unsigned Half = 0; Half != 4; ++Half) {
4269 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4275 // Check if B comes from one of C, D, E, F.
4276 for (unsigned Half = 0; Half != 4; ++Half) {
4277 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4283 return MatchA && MatchB;
4286 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4287 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4288 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4289 MVT VT = SVOp->getSimpleValueType(0);
4291 unsigned HalfSize = VT.getVectorNumElements()/2;
4293 unsigned FstHalf = 0, SndHalf = 0;
4294 for (unsigned i = 0; i < HalfSize; ++i) {
4295 if (SVOp->getMaskElt(i) > 0) {
4296 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4300 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4301 if (SVOp->getMaskElt(i) > 0) {
4302 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4307 return (FstHalf | (SndHalf << 4));
4310 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4311 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4312 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4316 unsigned NumElts = VT.getVectorNumElements();
4318 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4319 for (unsigned i = 0; i != NumElts; ++i) {
4322 Imm8 |= Mask[i] << (i*2);
4327 unsigned LaneSize = 4;
4328 SmallVector<int, 4> MaskVal(LaneSize, -1);
4330 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4331 for (unsigned i = 0; i != LaneSize; ++i) {
4332 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4336 if (MaskVal[i] < 0) {
4337 MaskVal[i] = Mask[i+l] - l;
4338 Imm8 |= MaskVal[i] << (i*2);
4341 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4348 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4349 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4350 /// Note that VPERMIL mask matching is different depending whether theunderlying
4351 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4352 /// to the same elements of the low, but to the higher half of the source.
4353 /// In VPERMILPD the two lanes could be shuffled independently of each other
4354 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4355 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4356 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4357 if (VT.getSizeInBits() < 256 || EltSize < 32)
4359 bool symetricMaskRequired = (EltSize == 32);
4360 unsigned NumElts = VT.getVectorNumElements();
4362 unsigned NumLanes = VT.getSizeInBits()/128;
4363 unsigned LaneSize = NumElts/NumLanes;
4364 // 2 or 4 elements in one lane
4366 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4367 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4368 for (unsigned i = 0; i != LaneSize; ++i) {
4369 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4371 if (symetricMaskRequired) {
4372 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4373 ExpectedMaskVal[i] = Mask[i+l] - l;
4376 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4384 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4385 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4386 /// element of vector 2 and the other elements to come from vector 1 in order.
4387 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4388 bool V2IsSplat = false, bool V2IsUndef = false) {
4389 if (!VT.is128BitVector())
4392 unsigned NumOps = VT.getVectorNumElements();
4393 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4396 if (!isUndefOrEqual(Mask[0], 0))
4399 for (unsigned i = 1; i != NumOps; ++i)
4400 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4401 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4402 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4408 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4409 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4410 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4411 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4412 const X86Subtarget *Subtarget) {
4413 if (!Subtarget->hasSSE3())
4416 unsigned NumElems = VT.getVectorNumElements();
4418 if ((VT.is128BitVector() && NumElems != 4) ||
4419 (VT.is256BitVector() && NumElems != 8) ||
4420 (VT.is512BitVector() && NumElems != 16))
4423 // "i+1" is the value the indexed mask element must have
4424 for (unsigned i = 0; i != NumElems; i += 2)
4425 if (!isUndefOrEqual(Mask[i], i+1) ||
4426 !isUndefOrEqual(Mask[i+1], i+1))
4432 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4433 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4434 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4435 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4436 const X86Subtarget *Subtarget) {
4437 if (!Subtarget->hasSSE3())
4440 unsigned NumElems = VT.getVectorNumElements();
4442 if ((VT.is128BitVector() && NumElems != 4) ||
4443 (VT.is256BitVector() && NumElems != 8) ||
4444 (VT.is512BitVector() && NumElems != 16))
4447 // "i" is the value the indexed mask element must have
4448 for (unsigned i = 0; i != NumElems; i += 2)
4449 if (!isUndefOrEqual(Mask[i], i) ||
4450 !isUndefOrEqual(Mask[i+1], i))
4456 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4457 /// specifies a shuffle of elements that is suitable for input to 256-bit
4458 /// version of MOVDDUP.
4459 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4460 if (!HasFp256 || !VT.is256BitVector())
4463 unsigned NumElts = VT.getVectorNumElements();
4467 for (unsigned i = 0; i != NumElts/2; ++i)
4468 if (!isUndefOrEqual(Mask[i], 0))
4470 for (unsigned i = NumElts/2; i != NumElts; ++i)
4471 if (!isUndefOrEqual(Mask[i], NumElts/2))
4476 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4477 /// specifies a shuffle of elements that is suitable for input to 128-bit
4478 /// version of MOVDDUP.
4479 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4480 if (!VT.is128BitVector())
4483 unsigned e = VT.getVectorNumElements() / 2;
4484 for (unsigned i = 0; i != e; ++i)
4485 if (!isUndefOrEqual(Mask[i], i))
4487 for (unsigned i = 0; i != e; ++i)
4488 if (!isUndefOrEqual(Mask[e+i], i))
4493 /// isVEXTRACTIndex - Return true if the specified
4494 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4495 /// suitable for instruction that extract 128 or 256 bit vectors
4496 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4497 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4498 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4501 // The index should be aligned on a vecWidth-bit boundary.
4503 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4505 MVT VT = N->getSimpleValueType(0);
4506 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4507 bool Result = (Index * ElSize) % vecWidth == 0;
4512 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4513 /// operand specifies a subvector insert that is suitable for input to
4514 /// insertion of 128 or 256-bit subvectors
4515 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4516 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4517 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4519 // The index should be aligned on a vecWidth-bit boundary.
4521 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4523 MVT VT = N->getSimpleValueType(0);
4524 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4525 bool Result = (Index * ElSize) % vecWidth == 0;
4530 bool X86::isVINSERT128Index(SDNode *N) {
4531 return isVINSERTIndex(N, 128);
4534 bool X86::isVINSERT256Index(SDNode *N) {
4535 return isVINSERTIndex(N, 256);
4538 bool X86::isVEXTRACT128Index(SDNode *N) {
4539 return isVEXTRACTIndex(N, 128);
4542 bool X86::isVEXTRACT256Index(SDNode *N) {
4543 return isVEXTRACTIndex(N, 256);
4546 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4547 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4548 /// Handles 128-bit and 256-bit.
4549 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4550 MVT VT = N->getSimpleValueType(0);
4552 assert((VT.getSizeInBits() >= 128) &&
4553 "Unsupported vector type for PSHUF/SHUFP");
4555 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4556 // independently on 128-bit lanes.
4557 unsigned NumElts = VT.getVectorNumElements();
4558 unsigned NumLanes = VT.getSizeInBits()/128;
4559 unsigned NumLaneElts = NumElts/NumLanes;
4561 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4562 "Only supports 2, 4 or 8 elements per lane");
4564 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4566 for (unsigned i = 0; i != NumElts; ++i) {
4567 int Elt = N->getMaskElt(i);
4568 if (Elt < 0) continue;
4569 Elt &= NumLaneElts - 1;
4570 unsigned ShAmt = (i << Shift) % 8;
4571 Mask |= Elt << ShAmt;
4577 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4578 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4579 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4580 MVT VT = N->getSimpleValueType(0);
4582 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4583 "Unsupported vector type for PSHUFHW");
4585 unsigned NumElts = VT.getVectorNumElements();
4588 for (unsigned l = 0; l != NumElts; l += 8) {
4589 // 8 nodes per lane, but we only care about the last 4.
4590 for (unsigned i = 0; i < 4; ++i) {
4591 int Elt = N->getMaskElt(l+i+4);
4592 if (Elt < 0) continue;
4593 Elt &= 0x3; // only 2-bits.
4594 Mask |= Elt << (i * 2);
4601 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4602 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4603 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4604 MVT VT = N->getSimpleValueType(0);
4606 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4607 "Unsupported vector type for PSHUFHW");
4609 unsigned NumElts = VT.getVectorNumElements();
4612 for (unsigned l = 0; l != NumElts; l += 8) {
4613 // 8 nodes per lane, but we only care about the first 4.
4614 for (unsigned i = 0; i < 4; ++i) {
4615 int Elt = N->getMaskElt(l+i);
4616 if (Elt < 0) continue;
4617 Elt &= 0x3; // only 2-bits
4618 Mask |= Elt << (i * 2);
4625 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4626 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4627 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4628 MVT VT = SVOp->getSimpleValueType(0);
4629 unsigned EltSize = VT.is512BitVector() ? 1 :
4630 VT.getVectorElementType().getSizeInBits() >> 3;
4632 unsigned NumElts = VT.getVectorNumElements();
4633 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4634 unsigned NumLaneElts = NumElts/NumLanes;
4638 for (i = 0; i != NumElts; ++i) {
4639 Val = SVOp->getMaskElt(i);
4643 if (Val >= (int)NumElts)
4644 Val -= NumElts - NumLaneElts;
4646 assert(Val - i > 0 && "PALIGNR imm should be positive");
4647 return (Val - i) * EltSize;
4650 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4651 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4652 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4653 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4656 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4658 MVT VecVT = N->getOperand(0).getSimpleValueType();
4659 MVT ElVT = VecVT.getVectorElementType();
4661 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4662 return Index / NumElemsPerChunk;
4665 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4666 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4667 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4668 llvm_unreachable("Illegal insert subvector for VINSERT");
4671 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4673 MVT VecVT = N->getSimpleValueType(0);
4674 MVT ElVT = VecVT.getVectorElementType();
4676 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4677 return Index / NumElemsPerChunk;
4680 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4681 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4682 /// and VINSERTI128 instructions.
4683 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4684 return getExtractVEXTRACTImmediate(N, 128);
4687 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4688 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4689 /// and VINSERTI64x4 instructions.
4690 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4691 return getExtractVEXTRACTImmediate(N, 256);
4694 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4695 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4696 /// and VINSERTI128 instructions.
4697 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4698 return getInsertVINSERTImmediate(N, 128);
4701 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4702 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4703 /// and VINSERTI64x4 instructions.
4704 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4705 return getInsertVINSERTImmediate(N, 256);
4708 /// isZero - Returns true if Elt is a constant integer zero
4709 static bool isZero(SDValue V) {
4710 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4711 return C && C->isNullValue();
4714 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4716 bool X86::isZeroNode(SDValue Elt) {
4719 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4720 return CFP->getValueAPF().isPosZero();
4724 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4725 /// their permute mask.
4726 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4727 SelectionDAG &DAG) {
4728 MVT VT = SVOp->getSimpleValueType(0);
4729 unsigned NumElems = VT.getVectorNumElements();
4730 SmallVector<int, 8> MaskVec;
4732 for (unsigned i = 0; i != NumElems; ++i) {
4733 int Idx = SVOp->getMaskElt(i);
4735 if (Idx < (int)NumElems)
4740 MaskVec.push_back(Idx);
4742 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4743 SVOp->getOperand(0), &MaskVec[0]);
4746 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4747 /// match movhlps. The lower half elements should come from upper half of
4748 /// V1 (and in order), and the upper half elements should come from the upper
4749 /// half of V2 (and in order).
4750 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4751 if (!VT.is128BitVector())
4753 if (VT.getVectorNumElements() != 4)
4755 for (unsigned i = 0, e = 2; i != e; ++i)
4756 if (!isUndefOrEqual(Mask[i], i+2))
4758 for (unsigned i = 2; i != 4; ++i)
4759 if (!isUndefOrEqual(Mask[i], i+4))
4764 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4765 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4767 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4768 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4770 N = N->getOperand(0).getNode();
4771 if (!ISD::isNON_EXTLoad(N))
4774 *LD = cast<LoadSDNode>(N);
4778 // Test whether the given value is a vector value which will be legalized
4780 static bool WillBeConstantPoolLoad(SDNode *N) {
4781 if (N->getOpcode() != ISD::BUILD_VECTOR)
4784 // Check for any non-constant elements.
4785 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4786 switch (N->getOperand(i).getNode()->getOpcode()) {
4788 case ISD::ConstantFP:
4795 // Vectors of all-zeros and all-ones are materialized with special
4796 // instructions rather than being loaded.
4797 return !ISD::isBuildVectorAllZeros(N) &&
4798 !ISD::isBuildVectorAllOnes(N);
4801 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4802 /// match movlp{s|d}. The lower half elements should come from lower half of
4803 /// V1 (and in order), and the upper half elements should come from the upper
4804 /// half of V2 (and in order). And since V1 will become the source of the
4805 /// MOVLP, it must be either a vector load or a scalar load to vector.
4806 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4807 ArrayRef<int> Mask, MVT VT) {
4808 if (!VT.is128BitVector())
4811 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4813 // Is V2 is a vector load, don't do this transformation. We will try to use
4814 // load folding shufps op.
4815 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4818 unsigned NumElems = VT.getVectorNumElements();
4820 if (NumElems != 2 && NumElems != 4)
4822 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4823 if (!isUndefOrEqual(Mask[i], i))
4825 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4826 if (!isUndefOrEqual(Mask[i], i+NumElems))
4831 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4833 static bool isSplatVector(SDNode *N) {
4834 if (N->getOpcode() != ISD::BUILD_VECTOR)
4837 SDValue SplatValue = N->getOperand(0);
4838 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4839 if (N->getOperand(i) != SplatValue)
4844 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4845 /// to an zero vector.
4846 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4847 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4848 SDValue V1 = N->getOperand(0);
4849 SDValue V2 = N->getOperand(1);
4850 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4851 for (unsigned i = 0; i != NumElems; ++i) {
4852 int Idx = N->getMaskElt(i);
4853 if (Idx >= (int)NumElems) {
4854 unsigned Opc = V2.getOpcode();
4855 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4857 if (Opc != ISD::BUILD_VECTOR ||
4858 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4860 } else if (Idx >= 0) {
4861 unsigned Opc = V1.getOpcode();
4862 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4864 if (Opc != ISD::BUILD_VECTOR ||
4865 !X86::isZeroNode(V1.getOperand(Idx)))
4872 /// getZeroVector - Returns a vector of specified type with all zero elements.
4874 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4875 SelectionDAG &DAG, SDLoc dl) {
4876 assert(VT.isVector() && "Expected a vector type");
4878 // Always build SSE zero vectors as <4 x i32> bitcasted
4879 // to their dest type. This ensures they get CSE'd.
4881 if (VT.is128BitVector()) { // SSE
4882 if (Subtarget->hasSSE2()) { // SSE2
4883 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4884 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4886 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4887 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4889 } else if (VT.is256BitVector()) { // AVX
4890 if (Subtarget->hasInt256()) { // AVX2
4891 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4892 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4893 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4895 // 256-bit logic and arithmetic instructions in AVX are all
4896 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4897 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4898 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4899 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4901 } else if (VT.is512BitVector()) { // AVX-512
4902 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4903 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4904 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4905 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4906 } else if (VT.getScalarType() == MVT::i1) {
4907 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4908 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4909 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4910 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4912 llvm_unreachable("Unexpected vector type");
4914 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4917 /// getOnesVector - Returns a vector of specified type with all bits set.
4918 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4919 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4920 /// Then bitcast to their original type, ensuring they get CSE'd.
4921 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4923 assert(VT.isVector() && "Expected a vector type");
4925 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4927 if (VT.is256BitVector()) {
4928 if (HasInt256) { // AVX2
4929 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4930 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4932 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4933 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4935 } else if (VT.is128BitVector()) {
4936 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4938 llvm_unreachable("Unexpected vector type");
4940 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4943 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4944 /// that point to V2 points to its first element.
4945 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4946 for (unsigned i = 0; i != NumElems; ++i) {
4947 if (Mask[i] > (int)NumElems) {
4953 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4954 /// operation of specified width.
4955 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4957 unsigned NumElems = VT.getVectorNumElements();
4958 SmallVector<int, 8> Mask;
4959 Mask.push_back(NumElems);
4960 for (unsigned i = 1; i != NumElems; ++i)
4962 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4965 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4966 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4968 unsigned NumElems = VT.getVectorNumElements();
4969 SmallVector<int, 8> Mask;
4970 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4972 Mask.push_back(i + NumElems);
4974 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4977 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4978 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4980 unsigned NumElems = VT.getVectorNumElements();
4981 SmallVector<int, 8> Mask;
4982 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4983 Mask.push_back(i + Half);
4984 Mask.push_back(i + NumElems + Half);
4986 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4989 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4990 // a generic shuffle instruction because the target has no such instructions.
4991 // Generate shuffles which repeat i16 and i8 several times until they can be
4992 // represented by v4f32 and then be manipulated by target suported shuffles.
4993 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4994 MVT VT = V.getSimpleValueType();
4995 int NumElems = VT.getVectorNumElements();
4998 while (NumElems > 4) {
4999 if (EltNo < NumElems/2) {
5000 V = getUnpackl(DAG, dl, VT, V, V);
5002 V = getUnpackh(DAG, dl, VT, V, V);
5003 EltNo -= NumElems/2;
5010 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5011 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5012 MVT VT = V.getSimpleValueType();
5015 if (VT.is128BitVector()) {
5016 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5017 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5018 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5020 } else if (VT.is256BitVector()) {
5021 // To use VPERMILPS to splat scalars, the second half of indicies must
5022 // refer to the higher part, which is a duplication of the lower one,
5023 // because VPERMILPS can only handle in-lane permutations.
5024 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5025 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5027 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5028 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5031 llvm_unreachable("Vector size not supported");
5033 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5036 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5037 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5038 MVT SrcVT = SV->getSimpleValueType(0);
5039 SDValue V1 = SV->getOperand(0);
5042 int EltNo = SV->getSplatIndex();
5043 int NumElems = SrcVT.getVectorNumElements();
5044 bool Is256BitVec = SrcVT.is256BitVector();
5046 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5047 "Unknown how to promote splat for type");
5049 // Extract the 128-bit part containing the splat element and update
5050 // the splat element index when it refers to the higher register.
5052 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5053 if (EltNo >= NumElems/2)
5054 EltNo -= NumElems/2;
5057 // All i16 and i8 vector types can't be used directly by a generic shuffle
5058 // instruction because the target has no such instruction. Generate shuffles
5059 // which repeat i16 and i8 several times until they fit in i32, and then can
5060 // be manipulated by target suported shuffles.
5061 MVT EltVT = SrcVT.getVectorElementType();
5062 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5063 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5065 // Recreate the 256-bit vector and place the same 128-bit vector
5066 // into the low and high part. This is necessary because we want
5067 // to use VPERM* to shuffle the vectors
5069 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5072 return getLegalSplat(DAG, V1, EltNo);
5075 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5076 /// vector of zero or undef vector. This produces a shuffle where the low
5077 /// element of V2 is swizzled into the zero/undef vector, landing at element
5078 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5079 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5081 const X86Subtarget *Subtarget,
5082 SelectionDAG &DAG) {
5083 MVT VT = V2.getSimpleValueType();
5085 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5086 unsigned NumElems = VT.getVectorNumElements();
5087 SmallVector<int, 16> MaskVec;
5088 for (unsigned i = 0; i != NumElems; ++i)
5089 // If this is the insertion idx, put the low elt of V2 here.
5090 MaskVec.push_back(i == Idx ? NumElems : i);
5091 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5094 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5095 /// target specific opcode. Returns true if the Mask could be calculated.
5096 /// Sets IsUnary to true if only uses one source.
5097 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5098 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5099 unsigned NumElems = VT.getVectorNumElements();
5103 switch(N->getOpcode()) {
5105 ImmN = N->getOperand(N->getNumOperands()-1);
5106 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5108 case X86ISD::UNPCKH:
5109 DecodeUNPCKHMask(VT, Mask);
5111 case X86ISD::UNPCKL:
5112 DecodeUNPCKLMask(VT, Mask);
5114 case X86ISD::MOVHLPS:
5115 DecodeMOVHLPSMask(NumElems, Mask);
5117 case X86ISD::MOVLHPS:
5118 DecodeMOVLHPSMask(NumElems, Mask);
5120 case X86ISD::PALIGNR:
5121 ImmN = N->getOperand(N->getNumOperands()-1);
5122 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5124 case X86ISD::PSHUFD:
5125 case X86ISD::VPERMILP:
5126 ImmN = N->getOperand(N->getNumOperands()-1);
5127 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5130 case X86ISD::PSHUFHW:
5131 ImmN = N->getOperand(N->getNumOperands()-1);
5132 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5135 case X86ISD::PSHUFLW:
5136 ImmN = N->getOperand(N->getNumOperands()-1);
5137 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5140 case X86ISD::VPERMI:
5141 ImmN = N->getOperand(N->getNumOperands()-1);
5142 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5146 case X86ISD::MOVSD: {
5147 // The index 0 always comes from the first element of the second source,
5148 // this is why MOVSS and MOVSD are used in the first place. The other
5149 // elements come from the other positions of the first source vector
5150 Mask.push_back(NumElems);
5151 for (unsigned i = 1; i != NumElems; ++i) {
5156 case X86ISD::VPERM2X128:
5157 ImmN = N->getOperand(N->getNumOperands()-1);
5158 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5159 if (Mask.empty()) return false;
5161 case X86ISD::MOVDDUP:
5162 case X86ISD::MOVLHPD:
5163 case X86ISD::MOVLPD:
5164 case X86ISD::MOVLPS:
5165 case X86ISD::MOVSHDUP:
5166 case X86ISD::MOVSLDUP:
5167 // Not yet implemented
5169 default: llvm_unreachable("unknown target shuffle node");
5175 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5176 /// element of the result of the vector shuffle.
5177 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5180 return SDValue(); // Limit search depth.
5182 SDValue V = SDValue(N, 0);
5183 EVT VT = V.getValueType();
5184 unsigned Opcode = V.getOpcode();
5186 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5187 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5188 int Elt = SV->getMaskElt(Index);
5191 return DAG.getUNDEF(VT.getVectorElementType());
5193 unsigned NumElems = VT.getVectorNumElements();
5194 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5195 : SV->getOperand(1);
5196 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5199 // Recurse into target specific vector shuffles to find scalars.
5200 if (isTargetShuffle(Opcode)) {
5201 MVT ShufVT = V.getSimpleValueType();
5202 unsigned NumElems = ShufVT.getVectorNumElements();
5203 SmallVector<int, 16> ShuffleMask;
5206 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5209 int Elt = ShuffleMask[Index];
5211 return DAG.getUNDEF(ShufVT.getVectorElementType());
5213 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5215 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5219 // Actual nodes that may contain scalar elements
5220 if (Opcode == ISD::BITCAST) {
5221 V = V.getOperand(0);
5222 EVT SrcVT = V.getValueType();
5223 unsigned NumElems = VT.getVectorNumElements();
5225 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5229 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5230 return (Index == 0) ? V.getOperand(0)
5231 : DAG.getUNDEF(VT.getVectorElementType());
5233 if (V.getOpcode() == ISD::BUILD_VECTOR)
5234 return V.getOperand(Index);
5239 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5240 /// shuffle operation which come from a consecutively from a zero. The
5241 /// search can start in two different directions, from left or right.
5242 /// We count undefs as zeros until PreferredNum is reached.
5243 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5244 unsigned NumElems, bool ZerosFromLeft,
5246 unsigned PreferredNum = -1U) {
5247 unsigned NumZeros = 0;
5248 for (unsigned i = 0; i != NumElems; ++i) {
5249 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5250 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5254 if (X86::isZeroNode(Elt))
5256 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5257 NumZeros = std::min(NumZeros + 1, PreferredNum);
5265 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5266 /// correspond consecutively to elements from one of the vector operands,
5267 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5269 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5270 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5271 unsigned NumElems, unsigned &OpNum) {
5272 bool SeenV1 = false;
5273 bool SeenV2 = false;
5275 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5276 int Idx = SVOp->getMaskElt(i);
5277 // Ignore undef indicies
5281 if (Idx < (int)NumElems)
5286 // Only accept consecutive elements from the same vector
5287 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5291 OpNum = SeenV1 ? 0 : 1;
5295 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5296 /// logical left shift of a vector.
5297 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5298 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5300 SVOp->getSimpleValueType(0).getVectorNumElements();
5301 unsigned NumZeros = getNumOfConsecutiveZeros(
5302 SVOp, NumElems, false /* check zeros from right */, DAG,
5303 SVOp->getMaskElt(0));
5309 // Considering the elements in the mask that are not consecutive zeros,
5310 // check if they consecutively come from only one of the source vectors.
5312 // V1 = {X, A, B, C} 0
5314 // vector_shuffle V1, V2 <1, 2, 3, X>
5316 if (!isShuffleMaskConsecutive(SVOp,
5317 0, // Mask Start Index
5318 NumElems-NumZeros, // Mask End Index(exclusive)
5319 NumZeros, // Where to start looking in the src vector
5320 NumElems, // Number of elements in vector
5321 OpSrc)) // Which source operand ?
5326 ShVal = SVOp->getOperand(OpSrc);
5330 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5331 /// logical left shift of a vector.
5332 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5333 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5335 SVOp->getSimpleValueType(0).getVectorNumElements();
5336 unsigned NumZeros = getNumOfConsecutiveZeros(
5337 SVOp, NumElems, true /* check zeros from left */, DAG,
5338 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5344 // Considering the elements in the mask that are not consecutive zeros,
5345 // check if they consecutively come from only one of the source vectors.
5347 // 0 { A, B, X, X } = V2
5349 // vector_shuffle V1, V2 <X, X, 4, 5>
5351 if (!isShuffleMaskConsecutive(SVOp,
5352 NumZeros, // Mask Start Index
5353 NumElems, // Mask End Index(exclusive)
5354 0, // Where to start looking in the src vector
5355 NumElems, // Number of elements in vector
5356 OpSrc)) // Which source operand ?
5361 ShVal = SVOp->getOperand(OpSrc);
5365 /// isVectorShift - Returns true if the shuffle can be implemented as a
5366 /// logical left or right shift of a vector.
5367 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5368 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5369 // Although the logic below support any bitwidth size, there are no
5370 // shift instructions which handle more than 128-bit vectors.
5371 if (!SVOp->getSimpleValueType(0).is128BitVector())
5374 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5375 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5381 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5383 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5384 unsigned NumNonZero, unsigned NumZero,
5386 const X86Subtarget* Subtarget,
5387 const TargetLowering &TLI) {
5394 for (unsigned i = 0; i < 16; ++i) {
5395 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5396 if (ThisIsNonZero && First) {
5398 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5400 V = DAG.getUNDEF(MVT::v8i16);
5405 SDValue ThisElt, LastElt;
5406 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5407 if (LastIsNonZero) {
5408 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5409 MVT::i16, Op.getOperand(i-1));
5411 if (ThisIsNonZero) {
5412 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5413 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5414 ThisElt, DAG.getConstant(8, MVT::i8));
5416 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5420 if (ThisElt.getNode())
5421 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5422 DAG.getIntPtrConstant(i/2));
5426 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5429 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5431 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5432 unsigned NumNonZero, unsigned NumZero,
5434 const X86Subtarget* Subtarget,
5435 const TargetLowering &TLI) {
5442 for (unsigned i = 0; i < 8; ++i) {
5443 bool isNonZero = (NonZeros & (1 << i)) != 0;
5447 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5449 V = DAG.getUNDEF(MVT::v8i16);
5452 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5453 MVT::v8i16, V, Op.getOperand(i),
5454 DAG.getIntPtrConstant(i));
5461 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5462 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5463 unsigned NonZeros, unsigned NumNonZero,
5464 unsigned NumZero, SelectionDAG &DAG,
5465 const X86Subtarget *Subtarget,
5466 const TargetLowering &TLI) {
5467 // We know there's at least one non-zero element
5468 unsigned FirstNonZeroIdx = 0;
5469 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5470 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5471 X86::isZeroNode(FirstNonZero)) {
5473 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5476 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5477 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5480 SDValue V = FirstNonZero.getOperand(0);
5481 MVT VVT = V.getSimpleValueType();
5482 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5485 unsigned FirstNonZeroDst =
5486 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5487 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5488 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5489 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5491 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5492 SDValue Elem = Op.getOperand(Idx);
5493 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5496 // TODO: What else can be here? Deal with it.
5497 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5500 // TODO: Some optimizations are still possible here
5501 // ex: Getting one element from a vector, and the rest from another.
5502 if (Elem.getOperand(0) != V)
5505 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5508 else if (IncorrectIdx == -1U) {
5512 // There was already one element with an incorrect index.
5513 // We can't optimize this case to an insertps.
5517 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5519 EVT VT = Op.getSimpleValueType();
5520 unsigned ElementMoveMask = 0;
5521 if (IncorrectIdx == -1U)
5522 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5524 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5526 SDValue InsertpsMask =
5527 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5528 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5534 /// getVShift - Return a vector logical shift node.
5536 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5537 unsigned NumBits, SelectionDAG &DAG,
5538 const TargetLowering &TLI, SDLoc dl) {
5539 assert(VT.is128BitVector() && "Unknown type for VShift");
5540 EVT ShVT = MVT::v2i64;
5541 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5542 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5543 return DAG.getNode(ISD::BITCAST, dl, VT,
5544 DAG.getNode(Opc, dl, ShVT, SrcOp,
5545 DAG.getConstant(NumBits,
5546 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5550 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5552 // Check if the scalar load can be widened into a vector load. And if
5553 // the address is "base + cst" see if the cst can be "absorbed" into
5554 // the shuffle mask.
5555 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5556 SDValue Ptr = LD->getBasePtr();
5557 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5559 EVT PVT = LD->getValueType(0);
5560 if (PVT != MVT::i32 && PVT != MVT::f32)
5565 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5566 FI = FINode->getIndex();
5568 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5569 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5570 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5571 Offset = Ptr.getConstantOperandVal(1);
5572 Ptr = Ptr.getOperand(0);
5577 // FIXME: 256-bit vector instructions don't require a strict alignment,
5578 // improve this code to support it better.
5579 unsigned RequiredAlign = VT.getSizeInBits()/8;
5580 SDValue Chain = LD->getChain();
5581 // Make sure the stack object alignment is at least 16 or 32.
5582 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5583 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5584 if (MFI->isFixedObjectIndex(FI)) {
5585 // Can't change the alignment. FIXME: It's possible to compute
5586 // the exact stack offset and reference FI + adjust offset instead.
5587 // If someone *really* cares about this. That's the way to implement it.
5590 MFI->setObjectAlignment(FI, RequiredAlign);
5594 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5595 // Ptr + (Offset & ~15).
5598 if ((Offset % RequiredAlign) & 3)
5600 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5602 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5603 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5605 int EltNo = (Offset - StartOffset) >> 2;
5606 unsigned NumElems = VT.getVectorNumElements();
5608 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5609 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5610 LD->getPointerInfo().getWithOffset(StartOffset),
5611 false, false, false, 0);
5613 SmallVector<int, 8> Mask;
5614 for (unsigned i = 0; i != NumElems; ++i)
5615 Mask.push_back(EltNo);
5617 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5623 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5624 /// vector of type 'VT', see if the elements can be replaced by a single large
5625 /// load which has the same value as a build_vector whose operands are 'elts'.
5627 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5629 /// FIXME: we'd also like to handle the case where the last elements are zero
5630 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5631 /// There's even a handy isZeroNode for that purpose.
5632 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5633 SDLoc &DL, SelectionDAG &DAG,
5634 bool isAfterLegalize) {
5635 EVT EltVT = VT.getVectorElementType();
5636 unsigned NumElems = Elts.size();
5638 LoadSDNode *LDBase = nullptr;
5639 unsigned LastLoadedElt = -1U;
5641 // For each element in the initializer, see if we've found a load or an undef.
5642 // If we don't find an initial load element, or later load elements are
5643 // non-consecutive, bail out.
5644 for (unsigned i = 0; i < NumElems; ++i) {
5645 SDValue Elt = Elts[i];
5647 if (!Elt.getNode() ||
5648 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5651 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5653 LDBase = cast<LoadSDNode>(Elt.getNode());
5657 if (Elt.getOpcode() == ISD::UNDEF)
5660 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5661 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5666 // If we have found an entire vector of loads and undefs, then return a large
5667 // load of the entire vector width starting at the base pointer. If we found
5668 // consecutive loads for the low half, generate a vzext_load node.
5669 if (LastLoadedElt == NumElems - 1) {
5671 if (isAfterLegalize &&
5672 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5675 SDValue NewLd = SDValue();
5677 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5678 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5679 LDBase->getPointerInfo(),
5680 LDBase->isVolatile(), LDBase->isNonTemporal(),
5681 LDBase->isInvariant(), 0);
5682 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5683 LDBase->getPointerInfo(),
5684 LDBase->isVolatile(), LDBase->isNonTemporal(),
5685 LDBase->isInvariant(), LDBase->getAlignment());
5687 if (LDBase->hasAnyUseOfValue(1)) {
5688 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5690 SDValue(NewLd.getNode(), 1));
5691 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5692 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5693 SDValue(NewLd.getNode(), 1));
5698 if (NumElems == 4 && LastLoadedElt == 1 &&
5699 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5700 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5701 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5703 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5704 LDBase->getPointerInfo(),
5705 LDBase->getAlignment(),
5706 false/*isVolatile*/, true/*ReadMem*/,
5709 // Make sure the newly-created LOAD is in the same position as LDBase in
5710 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5711 // update uses of LDBase's output chain to use the TokenFactor.
5712 if (LDBase->hasAnyUseOfValue(1)) {
5713 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5714 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5715 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5716 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5717 SDValue(ResNode.getNode(), 1));
5720 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5725 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5726 /// to generate a splat value for the following cases:
5727 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5728 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5729 /// a scalar load, or a constant.
5730 /// The VBROADCAST node is returned when a pattern is found,
5731 /// or SDValue() otherwise.
5732 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5733 SelectionDAG &DAG) {
5734 if (!Subtarget->hasFp256())
5737 MVT VT = Op.getSimpleValueType();
5740 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5741 "Unsupported vector type for broadcast.");
5746 switch (Op.getOpcode()) {
5748 // Unknown pattern found.
5751 case ISD::BUILD_VECTOR: {
5752 // The BUILD_VECTOR node must be a splat.
5753 if (!isSplatVector(Op.getNode()))
5756 Ld = Op.getOperand(0);
5757 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5758 Ld.getOpcode() == ISD::ConstantFP);
5760 // The suspected load node has several users. Make sure that all
5761 // of its users are from the BUILD_VECTOR node.
5762 // Constants may have multiple users.
5763 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5768 case ISD::VECTOR_SHUFFLE: {
5769 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5771 // Shuffles must have a splat mask where the first element is
5773 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5776 SDValue Sc = Op.getOperand(0);
5777 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5778 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5780 if (!Subtarget->hasInt256())
5783 // Use the register form of the broadcast instruction available on AVX2.
5784 if (VT.getSizeInBits() >= 256)
5785 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5786 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5789 Ld = Sc.getOperand(0);
5790 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5791 Ld.getOpcode() == ISD::ConstantFP);
5793 // The scalar_to_vector node and the suspected
5794 // load node must have exactly one user.
5795 // Constants may have multiple users.
5797 // AVX-512 has register version of the broadcast
5798 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5799 Ld.getValueType().getSizeInBits() >= 32;
5800 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5807 bool IsGE256 = (VT.getSizeInBits() >= 256);
5809 // Handle the broadcasting a single constant scalar from the constant pool
5810 // into a vector. On Sandybridge it is still better to load a constant vector
5811 // from the constant pool and not to broadcast it from a scalar.
5812 if (ConstSplatVal && Subtarget->hasInt256()) {
5813 EVT CVT = Ld.getValueType();
5814 assert(!CVT.isVector() && "Must not broadcast a vector type");
5815 unsigned ScalarSize = CVT.getSizeInBits();
5817 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5818 const Constant *C = nullptr;
5819 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5820 C = CI->getConstantIntValue();
5821 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5822 C = CF->getConstantFPValue();
5824 assert(C && "Invalid constant type");
5826 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5827 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5828 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5829 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5830 MachinePointerInfo::getConstantPool(),
5831 false, false, false, Alignment);
5833 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5837 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5838 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5840 // Handle AVX2 in-register broadcasts.
5841 if (!IsLoad && Subtarget->hasInt256() &&
5842 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5843 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5845 // The scalar source must be a normal load.
5849 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5850 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5852 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5853 // double since there is no vbroadcastsd xmm
5854 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5855 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5856 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5859 // Unsupported broadcast.
5863 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5864 /// underlying vector and index.
5866 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5868 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5870 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5871 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5874 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5876 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5878 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5879 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5882 // In this case the vector is the extract_subvector expression and the index
5883 // is 2, as specified by the shuffle.
5884 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5885 SDValue ShuffleVec = SVOp->getOperand(0);
5886 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5887 assert(ShuffleVecVT.getVectorElementType() ==
5888 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5890 int ShuffleIdx = SVOp->getMaskElt(Idx);
5891 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5892 ExtractedFromVec = ShuffleVec;
5898 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5899 MVT VT = Op.getSimpleValueType();
5901 // Skip if insert_vec_elt is not supported.
5902 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5903 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5907 unsigned NumElems = Op.getNumOperands();
5911 SmallVector<unsigned, 4> InsertIndices;
5912 SmallVector<int, 8> Mask(NumElems, -1);
5914 for (unsigned i = 0; i != NumElems; ++i) {
5915 unsigned Opc = Op.getOperand(i).getOpcode();
5917 if (Opc == ISD::UNDEF)
5920 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5921 // Quit if more than 1 elements need inserting.
5922 if (InsertIndices.size() > 1)
5925 InsertIndices.push_back(i);
5929 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5930 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5931 // Quit if non-constant index.
5932 if (!isa<ConstantSDNode>(ExtIdx))
5934 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5936 // Quit if extracted from vector of different type.
5937 if (ExtractedFromVec.getValueType() != VT)
5940 if (!VecIn1.getNode())
5941 VecIn1 = ExtractedFromVec;
5942 else if (VecIn1 != ExtractedFromVec) {
5943 if (!VecIn2.getNode())
5944 VecIn2 = ExtractedFromVec;
5945 else if (VecIn2 != ExtractedFromVec)
5946 // Quit if more than 2 vectors to shuffle
5950 if (ExtractedFromVec == VecIn1)
5952 else if (ExtractedFromVec == VecIn2)
5953 Mask[i] = Idx + NumElems;
5956 if (!VecIn1.getNode())
5959 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5960 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5961 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5962 unsigned Idx = InsertIndices[i];
5963 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5964 DAG.getIntPtrConstant(Idx));
5970 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5972 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5974 MVT VT = Op.getSimpleValueType();
5975 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5976 "Unexpected type in LowerBUILD_VECTORvXi1!");
5979 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5980 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5981 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5982 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5985 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5986 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5987 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5988 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5991 bool AllContants = true;
5992 uint64_t Immediate = 0;
5993 int NonConstIdx = -1;
5994 bool IsSplat = true;
5995 unsigned NumNonConsts = 0;
5996 unsigned NumConsts = 0;
5997 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5998 SDValue In = Op.getOperand(idx);
5999 if (In.getOpcode() == ISD::UNDEF)
6001 if (!isa<ConstantSDNode>(In)) {
6002 AllContants = false;
6008 if (cast<ConstantSDNode>(In)->getZExtValue())
6009 Immediate |= (1ULL << idx);
6011 if (In != Op.getOperand(0))
6016 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6017 DAG.getConstant(Immediate, MVT::i16));
6018 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6019 DAG.getIntPtrConstant(0));
6022 if (NumNonConsts == 1 && NonConstIdx != 0) {
6025 SDValue VecAsImm = DAG.getConstant(Immediate,
6026 MVT::getIntegerVT(VT.getSizeInBits()));
6027 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6030 DstVec = DAG.getUNDEF(VT);
6031 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6032 Op.getOperand(NonConstIdx),
6033 DAG.getIntPtrConstant(NonConstIdx));
6035 if (!IsSplat && (NonConstIdx != 0))
6036 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6037 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6040 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6041 DAG.getConstant(-1, SelectVT),
6042 DAG.getConstant(0, SelectVT));
6044 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6045 DAG.getConstant((Immediate | 1), SelectVT),
6046 DAG.getConstant(Immediate, SelectVT));
6047 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6051 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6054 MVT VT = Op.getSimpleValueType();
6055 MVT ExtVT = VT.getVectorElementType();
6056 unsigned NumElems = Op.getNumOperands();
6058 // Generate vectors for predicate vectors.
6059 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6060 return LowerBUILD_VECTORvXi1(Op, DAG);
6062 // Vectors containing all zeros can be matched by pxor and xorps later
6063 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6064 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6065 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6066 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6069 return getZeroVector(VT, Subtarget, DAG, dl);
6072 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6073 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6074 // vpcmpeqd on 256-bit vectors.
6075 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6076 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6079 if (!VT.is512BitVector())
6080 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6083 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6084 if (Broadcast.getNode())
6087 unsigned EVTBits = ExtVT.getSizeInBits();
6089 unsigned NumZero = 0;
6090 unsigned NumNonZero = 0;
6091 unsigned NonZeros = 0;
6092 bool IsAllConstants = true;
6093 SmallSet<SDValue, 8> Values;
6094 for (unsigned i = 0; i < NumElems; ++i) {
6095 SDValue Elt = Op.getOperand(i);
6096 if (Elt.getOpcode() == ISD::UNDEF)
6099 if (Elt.getOpcode() != ISD::Constant &&
6100 Elt.getOpcode() != ISD::ConstantFP)
6101 IsAllConstants = false;
6102 if (X86::isZeroNode(Elt))
6105 NonZeros |= (1 << i);
6110 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6111 if (NumNonZero == 0)
6112 return DAG.getUNDEF(VT);
6114 // Special case for single non-zero, non-undef, element.
6115 if (NumNonZero == 1) {
6116 unsigned Idx = countTrailingZeros(NonZeros);
6117 SDValue Item = Op.getOperand(Idx);
6119 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6120 // the value are obviously zero, truncate the value to i32 and do the
6121 // insertion that way. Only do this if the value is non-constant or if the
6122 // value is a constant being inserted into element 0. It is cheaper to do
6123 // a constant pool load than it is to do a movd + shuffle.
6124 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6125 (!IsAllConstants || Idx == 0)) {
6126 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6128 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6129 EVT VecVT = MVT::v4i32;
6130 unsigned VecElts = 4;
6132 // Truncate the value (which may itself be a constant) to i32, and
6133 // convert it to a vector with movd (S2V+shuffle to zero extend).
6134 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6135 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6136 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6138 // Now we have our 32-bit value zero extended in the low element of
6139 // a vector. If Idx != 0, swizzle it into place.
6141 SmallVector<int, 4> Mask;
6142 Mask.push_back(Idx);
6143 for (unsigned i = 1; i != VecElts; ++i)
6145 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6148 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6152 // If we have a constant or non-constant insertion into the low element of
6153 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6154 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6155 // depending on what the source datatype is.
6158 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6160 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6161 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6162 if (VT.is256BitVector() || VT.is512BitVector()) {
6163 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6164 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6165 Item, DAG.getIntPtrConstant(0));
6167 assert(VT.is128BitVector() && "Expected an SSE value type!");
6168 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6169 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6170 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6173 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6174 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6175 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6176 if (VT.is256BitVector()) {
6177 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6178 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6180 assert(VT.is128BitVector() && "Expected an SSE value type!");
6181 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6183 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6187 // Is it a vector logical left shift?
6188 if (NumElems == 2 && Idx == 1 &&
6189 X86::isZeroNode(Op.getOperand(0)) &&
6190 !X86::isZeroNode(Op.getOperand(1))) {
6191 unsigned NumBits = VT.getSizeInBits();
6192 return getVShift(true, VT,
6193 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6194 VT, Op.getOperand(1)),
6195 NumBits/2, DAG, *this, dl);
6198 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6201 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6202 // is a non-constant being inserted into an element other than the low one,
6203 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6204 // movd/movss) to move this into the low element, then shuffle it into
6206 if (EVTBits == 32) {
6207 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6209 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6210 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6211 SmallVector<int, 8> MaskVec;
6212 for (unsigned i = 0; i != NumElems; ++i)
6213 MaskVec.push_back(i == Idx ? 0 : 1);
6214 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6218 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6219 if (Values.size() == 1) {
6220 if (EVTBits == 32) {
6221 // Instead of a shuffle like this:
6222 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6223 // Check if it's possible to issue this instead.
6224 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6225 unsigned Idx = countTrailingZeros(NonZeros);
6226 SDValue Item = Op.getOperand(Idx);
6227 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6228 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6233 // A vector full of immediates; various special cases are already
6234 // handled, so this is best done with a single constant-pool load.
6238 // For AVX-length vectors, build the individual 128-bit pieces and use
6239 // shuffles to put them in place.
6240 if (VT.is256BitVector() || VT.is512BitVector()) {
6241 SmallVector<SDValue, 64> V;
6242 for (unsigned i = 0; i != NumElems; ++i)
6243 V.push_back(Op.getOperand(i));
6245 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6247 // Build both the lower and upper subvector.
6248 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6249 makeArrayRef(&V[0], NumElems/2));
6250 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6251 makeArrayRef(&V[NumElems / 2], NumElems/2));
6253 // Recreate the wider vector with the lower and upper part.
6254 if (VT.is256BitVector())
6255 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6256 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6259 // Let legalizer expand 2-wide build_vectors.
6260 if (EVTBits == 64) {
6261 if (NumNonZero == 1) {
6262 // One half is zero or undef.
6263 unsigned Idx = countTrailingZeros(NonZeros);
6264 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6265 Op.getOperand(Idx));
6266 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6271 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6272 if (EVTBits == 8 && NumElems == 16) {
6273 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6275 if (V.getNode()) return V;
6278 if (EVTBits == 16 && NumElems == 8) {
6279 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6281 if (V.getNode()) return V;
6284 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6285 if (EVTBits == 32 && NumElems == 4) {
6286 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6287 NumZero, DAG, Subtarget, *this);
6292 // If element VT is == 32 bits, turn it into a number of shuffles.
6293 SmallVector<SDValue, 8> V(NumElems);
6294 if (NumElems == 4 && NumZero > 0) {
6295 for (unsigned i = 0; i < 4; ++i) {
6296 bool isZero = !(NonZeros & (1 << i));
6298 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6300 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6303 for (unsigned i = 0; i < 2; ++i) {
6304 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6307 V[i] = V[i*2]; // Must be a zero vector.
6310 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6313 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6316 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6321 bool Reverse1 = (NonZeros & 0x3) == 2;
6322 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6326 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6327 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6329 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6332 if (Values.size() > 1 && VT.is128BitVector()) {
6333 // Check for a build vector of consecutive loads.
6334 for (unsigned i = 0; i < NumElems; ++i)
6335 V[i] = Op.getOperand(i);
6337 // Check for elements which are consecutive loads.
6338 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6342 // Check for a build vector from mostly shuffle plus few inserting.
6343 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6347 // For SSE 4.1, use insertps to put the high elements into the low element.
6348 if (getSubtarget()->hasSSE41()) {
6350 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6351 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6353 Result = DAG.getUNDEF(VT);
6355 for (unsigned i = 1; i < NumElems; ++i) {
6356 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6357 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6358 Op.getOperand(i), DAG.getIntPtrConstant(i));
6363 // Otherwise, expand into a number of unpckl*, start by extending each of
6364 // our (non-undef) elements to the full vector width with the element in the
6365 // bottom slot of the vector (which generates no code for SSE).
6366 for (unsigned i = 0; i < NumElems; ++i) {
6367 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6368 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6370 V[i] = DAG.getUNDEF(VT);
6373 // Next, we iteratively mix elements, e.g. for v4f32:
6374 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6375 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6376 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6377 unsigned EltStride = NumElems >> 1;
6378 while (EltStride != 0) {
6379 for (unsigned i = 0; i < EltStride; ++i) {
6380 // If V[i+EltStride] is undef and this is the first round of mixing,
6381 // then it is safe to just drop this shuffle: V[i] is already in the
6382 // right place, the one element (since it's the first round) being
6383 // inserted as undef can be dropped. This isn't safe for successive
6384 // rounds because they will permute elements within both vectors.
6385 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6386 EltStride == NumElems/2)
6389 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6398 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6399 // to create 256-bit vectors from two other 128-bit ones.
6400 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6402 MVT ResVT = Op.getSimpleValueType();
6404 assert((ResVT.is256BitVector() ||
6405 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6407 SDValue V1 = Op.getOperand(0);
6408 SDValue V2 = Op.getOperand(1);
6409 unsigned NumElems = ResVT.getVectorNumElements();
6410 if(ResVT.is256BitVector())
6411 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6413 if (Op.getNumOperands() == 4) {
6414 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6415 ResVT.getVectorNumElements()/2);
6416 SDValue V3 = Op.getOperand(2);
6417 SDValue V4 = Op.getOperand(3);
6418 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6419 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6421 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6424 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6425 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6426 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6427 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6428 Op.getNumOperands() == 4)));
6430 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6431 // from two other 128-bit ones.
6433 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6434 return LowerAVXCONCAT_VECTORS(Op, DAG);
6437 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6438 bool hasInt256, unsigned *MaskOut = nullptr) {
6439 MVT EltVT = VT.getVectorElementType();
6441 // There is no blend with immediate in AVX-512.
6442 if (VT.is512BitVector())
6445 if (!hasSSE41 || EltVT == MVT::i8)
6447 if (!hasInt256 && VT == MVT::v16i16)
6450 unsigned MaskValue = 0;
6451 unsigned NumElems = VT.getVectorNumElements();
6452 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6453 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6454 unsigned NumElemsInLane = NumElems / NumLanes;
6456 // Blend for v16i16 should be symetric for the both lanes.
6457 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6459 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6460 int EltIdx = MaskVals[i];
6462 if ((EltIdx < 0 || EltIdx == (int)i) &&
6463 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6466 if (((unsigned)EltIdx == (i + NumElems)) &&
6467 (SndLaneEltIdx < 0 ||
6468 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6469 MaskValue |= (1 << i);
6475 *MaskOut = MaskValue;
6479 // Try to lower a shuffle node into a simple blend instruction.
6480 // This function assumes isBlendMask returns true for this
6481 // SuffleVectorSDNode
6482 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6484 const X86Subtarget *Subtarget,
6485 SelectionDAG &DAG) {
6486 MVT VT = SVOp->getSimpleValueType(0);
6487 MVT EltVT = VT.getVectorElementType();
6488 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6489 Subtarget->hasInt256() && "Trying to lower a "
6490 "VECTOR_SHUFFLE to a Blend but "
6491 "with the wrong mask"));
6492 SDValue V1 = SVOp->getOperand(0);
6493 SDValue V2 = SVOp->getOperand(1);
6495 unsigned NumElems = VT.getVectorNumElements();
6497 // Convert i32 vectors to floating point if it is not AVX2.
6498 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6500 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6501 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6503 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6504 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6507 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6508 DAG.getConstant(MaskValue, MVT::i32));
6509 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6512 /// In vector type \p VT, return true if the element at index \p InputIdx
6513 /// falls on a different 128-bit lane than \p OutputIdx.
6514 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6515 unsigned OutputIdx) {
6516 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6517 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6520 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6521 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6522 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6523 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6525 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6526 SelectionDAG &DAG) {
6527 MVT VT = V1.getSimpleValueType();
6528 assert(VT.is128BitVector() || VT.is256BitVector());
6530 MVT EltVT = VT.getVectorElementType();
6531 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6532 unsigned NumElts = VT.getVectorNumElements();
6534 SmallVector<SDValue, 32> PshufbMask;
6535 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6536 int InputIdx = MaskVals[OutputIdx];
6537 unsigned InputByteIdx;
6539 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6540 InputByteIdx = 0x80;
6542 // Cross lane is not allowed.
6543 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6545 InputByteIdx = InputIdx * EltSizeInBytes;
6546 // Index is an byte offset within the 128-bit lane.
6547 InputByteIdx &= 0xf;
6550 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6551 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6552 if (InputByteIdx != 0x80)
6557 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6559 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6560 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6561 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6564 // v8i16 shuffles - Prefer shuffles in the following order:
6565 // 1. [all] pshuflw, pshufhw, optional move
6566 // 2. [ssse3] 1 x pshufb
6567 // 3. [ssse3] 2 x pshufb + 1 x por
6568 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6570 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6571 SelectionDAG &DAG) {
6572 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6573 SDValue V1 = SVOp->getOperand(0);
6574 SDValue V2 = SVOp->getOperand(1);
6576 SmallVector<int, 8> MaskVals;
6578 // Determine if more than 1 of the words in each of the low and high quadwords
6579 // of the result come from the same quadword of one of the two inputs. Undef
6580 // mask values count as coming from any quadword, for better codegen.
6582 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6583 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6584 unsigned LoQuad[] = { 0, 0, 0, 0 };
6585 unsigned HiQuad[] = { 0, 0, 0, 0 };
6586 // Indices of quads used.
6587 std::bitset<4> InputQuads;
6588 for (unsigned i = 0; i < 8; ++i) {
6589 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6590 int EltIdx = SVOp->getMaskElt(i);
6591 MaskVals.push_back(EltIdx);
6600 InputQuads.set(EltIdx / 4);
6603 int BestLoQuad = -1;
6604 unsigned MaxQuad = 1;
6605 for (unsigned i = 0; i < 4; ++i) {
6606 if (LoQuad[i] > MaxQuad) {
6608 MaxQuad = LoQuad[i];
6612 int BestHiQuad = -1;
6614 for (unsigned i = 0; i < 4; ++i) {
6615 if (HiQuad[i] > MaxQuad) {
6617 MaxQuad = HiQuad[i];
6621 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6622 // of the two input vectors, shuffle them into one input vector so only a
6623 // single pshufb instruction is necessary. If there are more than 2 input
6624 // quads, disable the next transformation since it does not help SSSE3.
6625 bool V1Used = InputQuads[0] || InputQuads[1];
6626 bool V2Used = InputQuads[2] || InputQuads[3];
6627 if (Subtarget->hasSSSE3()) {
6628 if (InputQuads.count() == 2 && V1Used && V2Used) {
6629 BestLoQuad = InputQuads[0] ? 0 : 1;
6630 BestHiQuad = InputQuads[2] ? 2 : 3;
6632 if (InputQuads.count() > 2) {
6638 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6639 // the shuffle mask. If a quad is scored as -1, that means that it contains
6640 // words from all 4 input quadwords.
6642 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6644 BestLoQuad < 0 ? 0 : BestLoQuad,
6645 BestHiQuad < 0 ? 1 : BestHiQuad
6647 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6648 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6649 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6650 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6652 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6653 // source words for the shuffle, to aid later transformations.
6654 bool AllWordsInNewV = true;
6655 bool InOrder[2] = { true, true };
6656 for (unsigned i = 0; i != 8; ++i) {
6657 int idx = MaskVals[i];
6659 InOrder[i/4] = false;
6660 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6662 AllWordsInNewV = false;
6666 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6667 if (AllWordsInNewV) {
6668 for (int i = 0; i != 8; ++i) {
6669 int idx = MaskVals[i];
6672 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6673 if ((idx != i) && idx < 4)
6675 if ((idx != i) && idx > 3)
6684 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6685 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6686 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6687 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6688 unsigned TargetMask = 0;
6689 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6690 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6691 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6692 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6693 getShufflePSHUFLWImmediate(SVOp);
6694 V1 = NewV.getOperand(0);
6695 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6699 // Promote splats to a larger type which usually leads to more efficient code.
6700 // FIXME: Is this true if pshufb is available?
6701 if (SVOp->isSplat())
6702 return PromoteSplat(SVOp, DAG);
6704 // If we have SSSE3, and all words of the result are from 1 input vector,
6705 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6706 // is present, fall back to case 4.
6707 if (Subtarget->hasSSSE3()) {
6708 SmallVector<SDValue,16> pshufbMask;
6710 // If we have elements from both input vectors, set the high bit of the
6711 // shuffle mask element to zero out elements that come from V2 in the V1
6712 // mask, and elements that come from V1 in the V2 mask, so that the two
6713 // results can be OR'd together.
6714 bool TwoInputs = V1Used && V2Used;
6715 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6717 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6719 // Calculate the shuffle mask for the second input, shuffle it, and
6720 // OR it with the first shuffled input.
6721 CommuteVectorShuffleMask(MaskVals, 8);
6722 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6723 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6724 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6727 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6728 // and update MaskVals with new element order.
6729 std::bitset<8> InOrder;
6730 if (BestLoQuad >= 0) {
6731 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6732 for (int i = 0; i != 4; ++i) {
6733 int idx = MaskVals[i];
6736 } else if ((idx / 4) == BestLoQuad) {
6741 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6744 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6745 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6746 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6748 getShufflePSHUFLWImmediate(SVOp), DAG);
6752 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6753 // and update MaskVals with the new element order.
6754 if (BestHiQuad >= 0) {
6755 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6756 for (unsigned i = 4; i != 8; ++i) {
6757 int idx = MaskVals[i];
6760 } else if ((idx / 4) == BestHiQuad) {
6761 MaskV[i] = (idx & 3) + 4;
6765 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6768 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6769 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6770 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6772 getShufflePSHUFHWImmediate(SVOp), DAG);
6776 // In case BestHi & BestLo were both -1, which means each quadword has a word
6777 // from each of the four input quadwords, calculate the InOrder bitvector now
6778 // before falling through to the insert/extract cleanup.
6779 if (BestLoQuad == -1 && BestHiQuad == -1) {
6781 for (int i = 0; i != 8; ++i)
6782 if (MaskVals[i] < 0 || MaskVals[i] == i)
6786 // The other elements are put in the right place using pextrw and pinsrw.
6787 for (unsigned i = 0; i != 8; ++i) {
6790 int EltIdx = MaskVals[i];
6793 SDValue ExtOp = (EltIdx < 8) ?
6794 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6795 DAG.getIntPtrConstant(EltIdx)) :
6796 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6797 DAG.getIntPtrConstant(EltIdx - 8));
6798 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6799 DAG.getIntPtrConstant(i));
6804 /// \brief v16i16 shuffles
6806 /// FIXME: We only support generation of a single pshufb currently. We can
6807 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6808 /// well (e.g 2 x pshufb + 1 x por).
6810 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6811 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6812 SDValue V1 = SVOp->getOperand(0);
6813 SDValue V2 = SVOp->getOperand(1);
6816 if (V2.getOpcode() != ISD::UNDEF)
6819 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6820 return getPSHUFB(MaskVals, V1, dl, DAG);
6823 // v16i8 shuffles - Prefer shuffles in the following order:
6824 // 1. [ssse3] 1 x pshufb
6825 // 2. [ssse3] 2 x pshufb + 1 x por
6826 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6827 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6828 const X86Subtarget* Subtarget,
6829 SelectionDAG &DAG) {
6830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6831 SDValue V1 = SVOp->getOperand(0);
6832 SDValue V2 = SVOp->getOperand(1);
6834 ArrayRef<int> MaskVals = SVOp->getMask();
6836 // Promote splats to a larger type which usually leads to more efficient code.
6837 // FIXME: Is this true if pshufb is available?
6838 if (SVOp->isSplat())
6839 return PromoteSplat(SVOp, DAG);
6841 // If we have SSSE3, case 1 is generated when all result bytes come from
6842 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6843 // present, fall back to case 3.
6845 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6846 if (Subtarget->hasSSSE3()) {
6847 SmallVector<SDValue,16> pshufbMask;
6849 // If all result elements are from one input vector, then only translate
6850 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6852 // Otherwise, we have elements from both input vectors, and must zero out
6853 // elements that come from V2 in the first mask, and V1 in the second mask
6854 // so that we can OR them together.
6855 for (unsigned i = 0; i != 16; ++i) {
6856 int EltIdx = MaskVals[i];
6857 if (EltIdx < 0 || EltIdx >= 16)
6859 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6861 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6862 DAG.getNode(ISD::BUILD_VECTOR, dl,
6863 MVT::v16i8, pshufbMask));
6865 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6866 // the 2nd operand if it's undefined or zero.
6867 if (V2.getOpcode() == ISD::UNDEF ||
6868 ISD::isBuildVectorAllZeros(V2.getNode()))
6871 // Calculate the shuffle mask for the second input, shuffle it, and
6872 // OR it with the first shuffled input.
6874 for (unsigned i = 0; i != 16; ++i) {
6875 int EltIdx = MaskVals[i];
6876 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6877 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6879 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6880 DAG.getNode(ISD::BUILD_VECTOR, dl,
6881 MVT::v16i8, pshufbMask));
6882 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6885 // No SSSE3 - Calculate in place words and then fix all out of place words
6886 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6887 // the 16 different words that comprise the two doublequadword input vectors.
6888 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6889 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6891 for (int i = 0; i != 8; ++i) {
6892 int Elt0 = MaskVals[i*2];
6893 int Elt1 = MaskVals[i*2+1];
6895 // This word of the result is all undef, skip it.
6896 if (Elt0 < 0 && Elt1 < 0)
6899 // This word of the result is already in the correct place, skip it.
6900 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6903 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6904 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6907 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6908 // using a single extract together, load it and store it.
6909 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6910 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6911 DAG.getIntPtrConstant(Elt1 / 2));
6912 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6913 DAG.getIntPtrConstant(i));
6917 // If Elt1 is defined, extract it from the appropriate source. If the
6918 // source byte is not also odd, shift the extracted word left 8 bits
6919 // otherwise clear the bottom 8 bits if we need to do an or.
6921 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6922 DAG.getIntPtrConstant(Elt1 / 2));
6923 if ((Elt1 & 1) == 0)
6924 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6926 TLI.getShiftAmountTy(InsElt.getValueType())));
6928 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6929 DAG.getConstant(0xFF00, MVT::i16));
6931 // If Elt0 is defined, extract it from the appropriate source. If the
6932 // source byte is not also even, shift the extracted word right 8 bits. If
6933 // Elt1 was also defined, OR the extracted values together before
6934 // inserting them in the result.
6936 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6937 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6938 if ((Elt0 & 1) != 0)
6939 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6941 TLI.getShiftAmountTy(InsElt0.getValueType())));
6943 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6944 DAG.getConstant(0x00FF, MVT::i16));
6945 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6948 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6949 DAG.getIntPtrConstant(i));
6951 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6954 // v32i8 shuffles - Translate to VPSHUFB if possible.
6956 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6957 const X86Subtarget *Subtarget,
6958 SelectionDAG &DAG) {
6959 MVT VT = SVOp->getSimpleValueType(0);
6960 SDValue V1 = SVOp->getOperand(0);
6961 SDValue V2 = SVOp->getOperand(1);
6963 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6965 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6966 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6967 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6969 // VPSHUFB may be generated if
6970 // (1) one of input vector is undefined or zeroinitializer.
6971 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6972 // And (2) the mask indexes don't cross the 128-bit lane.
6973 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6974 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6977 if (V1IsAllZero && !V2IsAllZero) {
6978 CommuteVectorShuffleMask(MaskVals, 32);
6981 return getPSHUFB(MaskVals, V1, dl, DAG);
6984 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6985 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6986 /// done when every pair / quad of shuffle mask elements point to elements in
6987 /// the right sequence. e.g.
6988 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6990 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6991 SelectionDAG &DAG) {
6992 MVT VT = SVOp->getSimpleValueType(0);
6994 unsigned NumElems = VT.getVectorNumElements();
6997 switch (VT.SimpleTy) {
6998 default: llvm_unreachable("Unexpected!");
7001 return SDValue(SVOp, 0);
7002 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7003 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7004 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7005 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7006 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7007 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7010 SmallVector<int, 8> MaskVec;
7011 for (unsigned i = 0; i != NumElems; i += Scale) {
7013 for (unsigned j = 0; j != Scale; ++j) {
7014 int EltIdx = SVOp->getMaskElt(i+j);
7018 StartIdx = (EltIdx / Scale);
7019 if (EltIdx != (int)(StartIdx*Scale + j))
7022 MaskVec.push_back(StartIdx);
7025 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7026 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7027 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7030 /// getVZextMovL - Return a zero-extending vector move low node.
7032 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7033 SDValue SrcOp, SelectionDAG &DAG,
7034 const X86Subtarget *Subtarget, SDLoc dl) {
7035 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7036 LoadSDNode *LD = nullptr;
7037 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7038 LD = dyn_cast<LoadSDNode>(SrcOp);
7040 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7042 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7043 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7044 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7045 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7046 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7048 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7049 return DAG.getNode(ISD::BITCAST, dl, VT,
7050 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7051 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7059 return DAG.getNode(ISD::BITCAST, dl, VT,
7060 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7061 DAG.getNode(ISD::BITCAST, dl,
7065 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7066 /// which could not be matched by any known target speficic shuffle
7068 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7070 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7071 if (NewOp.getNode())
7074 MVT VT = SVOp->getSimpleValueType(0);
7076 unsigned NumElems = VT.getVectorNumElements();
7077 unsigned NumLaneElems = NumElems / 2;
7080 MVT EltVT = VT.getVectorElementType();
7081 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7084 SmallVector<int, 16> Mask;
7085 for (unsigned l = 0; l < 2; ++l) {
7086 // Build a shuffle mask for the output, discovering on the fly which
7087 // input vectors to use as shuffle operands (recorded in InputUsed).
7088 // If building a suitable shuffle vector proves too hard, then bail
7089 // out with UseBuildVector set.
7090 bool UseBuildVector = false;
7091 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7092 unsigned LaneStart = l * NumLaneElems;
7093 for (unsigned i = 0; i != NumLaneElems; ++i) {
7094 // The mask element. This indexes into the input.
7095 int Idx = SVOp->getMaskElt(i+LaneStart);
7097 // the mask element does not index into any input vector.
7102 // The input vector this mask element indexes into.
7103 int Input = Idx / NumLaneElems;
7105 // Turn the index into an offset from the start of the input vector.
7106 Idx -= Input * NumLaneElems;
7108 // Find or create a shuffle vector operand to hold this input.
7110 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7111 if (InputUsed[OpNo] == Input)
7112 // This input vector is already an operand.
7114 if (InputUsed[OpNo] < 0) {
7115 // Create a new operand for this input vector.
7116 InputUsed[OpNo] = Input;
7121 if (OpNo >= array_lengthof(InputUsed)) {
7122 // More than two input vectors used! Give up on trying to create a
7123 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7124 UseBuildVector = true;
7128 // Add the mask index for the new shuffle vector.
7129 Mask.push_back(Idx + OpNo * NumLaneElems);
7132 if (UseBuildVector) {
7133 SmallVector<SDValue, 16> SVOps;
7134 for (unsigned i = 0; i != NumLaneElems; ++i) {
7135 // The mask element. This indexes into the input.
7136 int Idx = SVOp->getMaskElt(i+LaneStart);
7138 SVOps.push_back(DAG.getUNDEF(EltVT));
7142 // The input vector this mask element indexes into.
7143 int Input = Idx / NumElems;
7145 // Turn the index into an offset from the start of the input vector.
7146 Idx -= Input * NumElems;
7148 // Extract the vector element by hand.
7149 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7150 SVOp->getOperand(Input),
7151 DAG.getIntPtrConstant(Idx)));
7154 // Construct the output using a BUILD_VECTOR.
7155 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7156 } else if (InputUsed[0] < 0) {
7157 // No input vectors were used! The result is undefined.
7158 Output[l] = DAG.getUNDEF(NVT);
7160 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7161 (InputUsed[0] % 2) * NumLaneElems,
7163 // If only one input was used, use an undefined vector for the other.
7164 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7165 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7166 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7167 // At least one input vector was used. Create a new shuffle vector.
7168 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7174 // Concatenate the result back
7175 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7178 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7179 /// 4 elements, and match them with several different shuffle types.
7181 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7182 SDValue V1 = SVOp->getOperand(0);
7183 SDValue V2 = SVOp->getOperand(1);
7185 MVT VT = SVOp->getSimpleValueType(0);
7187 assert(VT.is128BitVector() && "Unsupported vector size");
7189 std::pair<int, int> Locs[4];
7190 int Mask1[] = { -1, -1, -1, -1 };
7191 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7195 for (unsigned i = 0; i != 4; ++i) {
7196 int Idx = PermMask[i];
7198 Locs[i] = std::make_pair(-1, -1);
7200 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7202 Locs[i] = std::make_pair(0, NumLo);
7206 Locs[i] = std::make_pair(1, NumHi);
7208 Mask1[2+NumHi] = Idx;
7214 if (NumLo <= 2 && NumHi <= 2) {
7215 // If no more than two elements come from either vector. This can be
7216 // implemented with two shuffles. First shuffle gather the elements.
7217 // The second shuffle, which takes the first shuffle as both of its
7218 // vector operands, put the elements into the right order.
7219 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7221 int Mask2[] = { -1, -1, -1, -1 };
7223 for (unsigned i = 0; i != 4; ++i)
7224 if (Locs[i].first != -1) {
7225 unsigned Idx = (i < 2) ? 0 : 4;
7226 Idx += Locs[i].first * 2 + Locs[i].second;
7230 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7233 if (NumLo == 3 || NumHi == 3) {
7234 // Otherwise, we must have three elements from one vector, call it X, and
7235 // one element from the other, call it Y. First, use a shufps to build an
7236 // intermediate vector with the one element from Y and the element from X
7237 // that will be in the same half in the final destination (the indexes don't
7238 // matter). Then, use a shufps to build the final vector, taking the half
7239 // containing the element from Y from the intermediate, and the other half
7242 // Normalize it so the 3 elements come from V1.
7243 CommuteVectorShuffleMask(PermMask, 4);
7247 // Find the element from V2.
7249 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7250 int Val = PermMask[HiIndex];
7257 Mask1[0] = PermMask[HiIndex];
7259 Mask1[2] = PermMask[HiIndex^1];
7261 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7264 Mask1[0] = PermMask[0];
7265 Mask1[1] = PermMask[1];
7266 Mask1[2] = HiIndex & 1 ? 6 : 4;
7267 Mask1[3] = HiIndex & 1 ? 4 : 6;
7268 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7271 Mask1[0] = HiIndex & 1 ? 2 : 0;
7272 Mask1[1] = HiIndex & 1 ? 0 : 2;
7273 Mask1[2] = PermMask[2];
7274 Mask1[3] = PermMask[3];
7279 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7282 // Break it into (shuffle shuffle_hi, shuffle_lo).
7283 int LoMask[] = { -1, -1, -1, -1 };
7284 int HiMask[] = { -1, -1, -1, -1 };
7286 int *MaskPtr = LoMask;
7287 unsigned MaskIdx = 0;
7290 for (unsigned i = 0; i != 4; ++i) {
7297 int Idx = PermMask[i];
7299 Locs[i] = std::make_pair(-1, -1);
7300 } else if (Idx < 4) {
7301 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7302 MaskPtr[LoIdx] = Idx;
7305 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7306 MaskPtr[HiIdx] = Idx;
7311 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7312 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7313 int MaskOps[] = { -1, -1, -1, -1 };
7314 for (unsigned i = 0; i != 4; ++i)
7315 if (Locs[i].first != -1)
7316 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7317 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7320 static bool MayFoldVectorLoad(SDValue V) {
7321 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7322 V = V.getOperand(0);
7324 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7325 V = V.getOperand(0);
7326 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7327 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7328 // BUILD_VECTOR (load), undef
7329 V = V.getOperand(0);
7331 return MayFoldLoad(V);
7335 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7336 MVT VT = Op.getSimpleValueType();
7338 // Canonizalize to v2f64.
7339 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7340 return DAG.getNode(ISD::BITCAST, dl, VT,
7341 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7346 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7348 SDValue V1 = Op.getOperand(0);
7349 SDValue V2 = Op.getOperand(1);
7350 MVT VT = Op.getSimpleValueType();
7352 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7354 if (HasSSE2 && VT == MVT::v2f64)
7355 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7357 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7358 return DAG.getNode(ISD::BITCAST, dl, VT,
7359 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7360 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7361 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7365 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7366 SDValue V1 = Op.getOperand(0);
7367 SDValue V2 = Op.getOperand(1);
7368 MVT VT = Op.getSimpleValueType();
7370 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7371 "unsupported shuffle type");
7373 if (V2.getOpcode() == ISD::UNDEF)
7377 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7381 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7382 SDValue V1 = Op.getOperand(0);
7383 SDValue V2 = Op.getOperand(1);
7384 MVT VT = Op.getSimpleValueType();
7385 unsigned NumElems = VT.getVectorNumElements();
7387 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7388 // operand of these instructions is only memory, so check if there's a
7389 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7391 bool CanFoldLoad = false;
7393 // Trivial case, when V2 comes from a load.
7394 if (MayFoldVectorLoad(V2))
7397 // When V1 is a load, it can be folded later into a store in isel, example:
7398 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7400 // (MOVLPSmr addr:$src1, VR128:$src2)
7401 // So, recognize this potential and also use MOVLPS or MOVLPD
7402 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7405 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7407 if (HasSSE2 && NumElems == 2)
7408 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7411 // If we don't care about the second element, proceed to use movss.
7412 if (SVOp->getMaskElt(1) != -1)
7413 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7416 // movl and movlp will both match v2i64, but v2i64 is never matched by
7417 // movl earlier because we make it strict to avoid messing with the movlp load
7418 // folding logic (see the code above getMOVLP call). Match it here then,
7419 // this is horrible, but will stay like this until we move all shuffle
7420 // matching to x86 specific nodes. Note that for the 1st condition all
7421 // types are matched with movsd.
7423 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7424 // as to remove this logic from here, as much as possible
7425 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7426 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7427 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7430 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7432 // Invert the operand order and use SHUFPS to match it.
7433 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7434 getShuffleSHUFImmediate(SVOp), DAG);
7437 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7438 SelectionDAG &DAG) {
7440 MVT VT = Load->getSimpleValueType(0);
7441 MVT EVT = VT.getVectorElementType();
7442 SDValue Addr = Load->getOperand(1);
7443 SDValue NewAddr = DAG.getNode(
7444 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7445 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7448 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7449 DAG.getMachineFunction().getMachineMemOperand(
7450 Load->getMemOperand(), 0, EVT.getStoreSize()));
7454 // It is only safe to call this function if isINSERTPSMask is true for
7455 // this shufflevector mask.
7456 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7457 SelectionDAG &DAG) {
7458 // Generate an insertps instruction when inserting an f32 from memory onto a
7459 // v4f32 or when copying a member from one v4f32 to another.
7460 // We also use it for transferring i32 from one register to another,
7461 // since it simply copies the same bits.
7462 // If we're transferring an i32 from memory to a specific element in a
7463 // register, we output a generic DAG that will match the PINSRD
7465 MVT VT = SVOp->getSimpleValueType(0);
7466 MVT EVT = VT.getVectorElementType();
7467 SDValue V1 = SVOp->getOperand(0);
7468 SDValue V2 = SVOp->getOperand(1);
7469 auto Mask = SVOp->getMask();
7470 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7471 "unsupported vector type for insertps/pinsrd");
7473 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7474 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7475 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7483 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7486 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7487 "More than one element from V1 and from V2, or no elements from one "
7488 "of the vectors. This case should not have returned true from "
7493 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7496 if (MayFoldLoad(From)) {
7497 // Trivial case, when From comes from a load and is only used by the
7498 // shuffle. Make it use insertps from the vector that we need from that
7501 NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7502 if (!NewLoad.getNode())
7505 if (EVT == MVT::f32) {
7506 // Create this as a scalar to vector to match the instruction pattern.
7507 SDValue LoadScalarToVector =
7508 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7509 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7510 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7512 } else { // EVT == MVT::i32
7513 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7514 // instruction, to match the PINSRD instruction, which loads an i32 to a
7515 // certain vector element.
7516 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7517 DAG.getConstant(DestIndex, MVT::i32));
7521 // Vector-element-to-vector
7522 unsigned SrcIndex = Mask[DestIndex] % 4;
7523 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7524 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7527 // Reduce a vector shuffle to zext.
7528 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7529 SelectionDAG &DAG) {
7530 // PMOVZX is only available from SSE41.
7531 if (!Subtarget->hasSSE41())
7534 MVT VT = Op.getSimpleValueType();
7536 // Only AVX2 support 256-bit vector integer extending.
7537 if (!Subtarget->hasInt256() && VT.is256BitVector())
7540 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7542 SDValue V1 = Op.getOperand(0);
7543 SDValue V2 = Op.getOperand(1);
7544 unsigned NumElems = VT.getVectorNumElements();
7546 // Extending is an unary operation and the element type of the source vector
7547 // won't be equal to or larger than i64.
7548 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7549 VT.getVectorElementType() == MVT::i64)
7552 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7553 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7554 while ((1U << Shift) < NumElems) {
7555 if (SVOp->getMaskElt(1U << Shift) == 1)
7558 // The maximal ratio is 8, i.e. from i8 to i64.
7563 // Check the shuffle mask.
7564 unsigned Mask = (1U << Shift) - 1;
7565 for (unsigned i = 0; i != NumElems; ++i) {
7566 int EltIdx = SVOp->getMaskElt(i);
7567 if ((i & Mask) != 0 && EltIdx != -1)
7569 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7573 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7574 MVT NeVT = MVT::getIntegerVT(NBits);
7575 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7577 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7580 // Simplify the operand as it's prepared to be fed into shuffle.
7581 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7582 if (V1.getOpcode() == ISD::BITCAST &&
7583 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7584 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7585 V1.getOperand(0).getOperand(0)
7586 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7587 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7588 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7589 ConstantSDNode *CIdx =
7590 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7591 // If it's foldable, i.e. normal load with single use, we will let code
7592 // selection to fold it. Otherwise, we will short the conversion sequence.
7593 if (CIdx && CIdx->getZExtValue() == 0 &&
7594 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7595 MVT FullVT = V.getSimpleValueType();
7596 MVT V1VT = V1.getSimpleValueType();
7597 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7598 // The "ext_vec_elt" node is wider than the result node.
7599 // In this case we should extract subvector from V.
7600 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7601 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7602 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7603 FullVT.getVectorNumElements()/Ratio);
7604 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7605 DAG.getIntPtrConstant(0));
7607 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7611 return DAG.getNode(ISD::BITCAST, DL, VT,
7612 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7615 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7616 SelectionDAG &DAG) {
7617 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7618 MVT VT = Op.getSimpleValueType();
7620 SDValue V1 = Op.getOperand(0);
7621 SDValue V2 = Op.getOperand(1);
7623 if (isZeroShuffle(SVOp))
7624 return getZeroVector(VT, Subtarget, DAG, dl);
7626 // Handle splat operations
7627 if (SVOp->isSplat()) {
7628 // Use vbroadcast whenever the splat comes from a foldable load
7629 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7630 if (Broadcast.getNode())
7634 // Check integer expanding shuffles.
7635 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7636 if (NewOp.getNode())
7639 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7641 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7643 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7644 if (NewOp.getNode())
7645 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7646 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7647 // FIXME: Figure out a cleaner way to do this.
7648 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7649 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7650 if (NewOp.getNode()) {
7651 MVT NewVT = NewOp.getSimpleValueType();
7652 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7653 NewVT, true, false))
7654 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7657 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7658 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7659 if (NewOp.getNode()) {
7660 MVT NewVT = NewOp.getSimpleValueType();
7661 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7662 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7671 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7672 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7673 SDValue V1 = Op.getOperand(0);
7674 SDValue V2 = Op.getOperand(1);
7675 MVT VT = Op.getSimpleValueType();
7677 unsigned NumElems = VT.getVectorNumElements();
7678 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7679 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7680 bool V1IsSplat = false;
7681 bool V2IsSplat = false;
7682 bool HasSSE2 = Subtarget->hasSSE2();
7683 bool HasFp256 = Subtarget->hasFp256();
7684 bool HasInt256 = Subtarget->hasInt256();
7685 MachineFunction &MF = DAG.getMachineFunction();
7686 bool OptForSize = MF.getFunction()->getAttributes().
7687 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7689 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7691 if (V1IsUndef && V2IsUndef)
7692 return DAG.getUNDEF(VT);
7694 // When we create a shuffle node we put the UNDEF node to second operand,
7695 // but in some cases the first operand may be transformed to UNDEF.
7696 // In this case we should just commute the node.
7698 return CommuteVectorShuffle(SVOp, DAG);
7700 // Vector shuffle lowering takes 3 steps:
7702 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7703 // narrowing and commutation of operands should be handled.
7704 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7706 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7707 // so the shuffle can be broken into other shuffles and the legalizer can
7708 // try the lowering again.
7710 // The general idea is that no vector_shuffle operation should be left to
7711 // be matched during isel, all of them must be converted to a target specific
7714 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7715 // narrowing and commutation of operands should be handled. The actual code
7716 // doesn't include all of those, work in progress...
7717 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7718 if (NewOp.getNode())
7721 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7723 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7724 // unpckh_undef). Only use pshufd if speed is more important than size.
7725 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7726 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7727 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7728 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7730 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7731 V2IsUndef && MayFoldVectorLoad(V1))
7732 return getMOVDDup(Op, dl, V1, DAG);
7734 if (isMOVHLPS_v_undef_Mask(M, VT))
7735 return getMOVHighToLow(Op, dl, DAG);
7737 // Use to match splats
7738 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7739 (VT == MVT::v2f64 || VT == MVT::v2i64))
7740 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7742 if (isPSHUFDMask(M, VT)) {
7743 // The actual implementation will match the mask in the if above and then
7744 // during isel it can match several different instructions, not only pshufd
7745 // as its name says, sad but true, emulate the behavior for now...
7746 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7747 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7749 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7751 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7752 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7754 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7755 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7758 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7762 if (isPALIGNRMask(M, VT, Subtarget))
7763 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7764 getShufflePALIGNRImmediate(SVOp),
7767 // Check if this can be converted into a logical shift.
7768 bool isLeft = false;
7771 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7772 if (isShift && ShVal.hasOneUse()) {
7773 // If the shifted value has multiple uses, it may be cheaper to use
7774 // v_set0 + movlhps or movhlps, etc.
7775 MVT EltVT = VT.getVectorElementType();
7776 ShAmt *= EltVT.getSizeInBits();
7777 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7780 if (isMOVLMask(M, VT)) {
7781 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7782 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7783 if (!isMOVLPMask(M, VT)) {
7784 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7785 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7787 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7788 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7792 // FIXME: fold these into legal mask.
7793 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7794 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7796 if (isMOVHLPSMask(M, VT))
7797 return getMOVHighToLow(Op, dl, DAG);
7799 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7800 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7802 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7803 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7805 if (isMOVLPMask(M, VT))
7806 return getMOVLP(Op, dl, DAG, HasSSE2);
7808 if (ShouldXformToMOVHLPS(M, VT) ||
7809 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7810 return CommuteVectorShuffle(SVOp, DAG);
7813 // No better options. Use a vshldq / vsrldq.
7814 MVT EltVT = VT.getVectorElementType();
7815 ShAmt *= EltVT.getSizeInBits();
7816 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7819 bool Commuted = false;
7820 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7821 // 1,1,1,1 -> v8i16 though.
7822 V1IsSplat = isSplatVector(V1.getNode());
7823 V2IsSplat = isSplatVector(V2.getNode());
7825 // Canonicalize the splat or undef, if present, to be on the RHS.
7826 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7827 CommuteVectorShuffleMask(M, NumElems);
7829 std::swap(V1IsSplat, V2IsSplat);
7833 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7834 // Shuffling low element of v1 into undef, just return v1.
7837 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7838 // the instruction selector will not match, so get a canonical MOVL with
7839 // swapped operands to undo the commute.
7840 return getMOVL(DAG, dl, VT, V2, V1);
7843 if (isUNPCKLMask(M, VT, HasInt256))
7844 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7846 if (isUNPCKHMask(M, VT, HasInt256))
7847 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7850 // Normalize mask so all entries that point to V2 points to its first
7851 // element then try to match unpck{h|l} again. If match, return a
7852 // new vector_shuffle with the corrected mask.p
7853 SmallVector<int, 8> NewMask(M.begin(), M.end());
7854 NormalizeMask(NewMask, NumElems);
7855 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7856 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7857 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7858 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7862 // Commute is back and try unpck* again.
7863 // FIXME: this seems wrong.
7864 CommuteVectorShuffleMask(M, NumElems);
7866 std::swap(V1IsSplat, V2IsSplat);
7868 if (isUNPCKLMask(M, VT, HasInt256))
7869 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7871 if (isUNPCKHMask(M, VT, HasInt256))
7872 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7875 // Normalize the node to match x86 shuffle ops if needed
7876 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7877 return CommuteVectorShuffle(SVOp, DAG);
7879 // The checks below are all present in isShuffleMaskLegal, but they are
7880 // inlined here right now to enable us to directly emit target specific
7881 // nodes, and remove one by one until they don't return Op anymore.
7883 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7884 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7885 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7886 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7889 if (isPSHUFHWMask(M, VT, HasInt256))
7890 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7891 getShufflePSHUFHWImmediate(SVOp),
7894 if (isPSHUFLWMask(M, VT, HasInt256))
7895 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7896 getShufflePSHUFLWImmediate(SVOp),
7899 if (isSHUFPMask(M, VT))
7900 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7901 getShuffleSHUFImmediate(SVOp), DAG);
7903 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7904 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7905 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7906 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7908 //===--------------------------------------------------------------------===//
7909 // Generate target specific nodes for 128 or 256-bit shuffles only
7910 // supported in the AVX instruction set.
7913 // Handle VMOVDDUPY permutations
7914 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7915 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7917 // Handle VPERMILPS/D* permutations
7918 if (isVPERMILPMask(M, VT)) {
7919 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7920 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7921 getShuffleSHUFImmediate(SVOp), DAG);
7922 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7923 getShuffleSHUFImmediate(SVOp), DAG);
7927 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7928 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7929 Idx*(NumElems/2), DAG, dl);
7931 // Handle VPERM2F128/VPERM2I128 permutations
7932 if (isVPERM2X128Mask(M, VT, HasFp256))
7933 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7934 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7937 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
7939 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
7941 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7942 return getINSERTPS(SVOp, dl, DAG);
7945 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7946 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7948 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7949 VT.is512BitVector()) {
7950 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7951 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7952 SmallVector<SDValue, 16> permclMask;
7953 for (unsigned i = 0; i != NumElems; ++i) {
7954 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7957 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7959 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7960 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7961 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7962 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7963 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7966 //===--------------------------------------------------------------------===//
7967 // Since no target specific shuffle was selected for this generic one,
7968 // lower it into other known shuffles. FIXME: this isn't true yet, but
7969 // this is the plan.
7972 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7973 if (VT == MVT::v8i16) {
7974 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7975 if (NewOp.getNode())
7979 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7980 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7981 if (NewOp.getNode())
7985 if (VT == MVT::v16i8) {
7986 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7987 if (NewOp.getNode())
7991 if (VT == MVT::v32i8) {
7992 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7993 if (NewOp.getNode())
7997 // Handle all 128-bit wide vectors with 4 elements, and match them with
7998 // several different shuffle types.
7999 if (NumElems == 4 && VT.is128BitVector())
8000 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8002 // Handle general 256-bit shuffles
8003 if (VT.is256BitVector())
8004 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8009 // This function assumes its argument is a BUILD_VECTOR of constants or
8010 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8012 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8013 unsigned &MaskValue) {
8015 unsigned NumElems = BuildVector->getNumOperands();
8016 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8017 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8018 unsigned NumElemsInLane = NumElems / NumLanes;
8020 // Blend for v16i16 should be symetric for the both lanes.
8021 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8022 SDValue EltCond = BuildVector->getOperand(i);
8023 SDValue SndLaneEltCond =
8024 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8026 int Lane1Cond = -1, Lane2Cond = -1;
8027 if (isa<ConstantSDNode>(EltCond))
8028 Lane1Cond = !isZero(EltCond);
8029 if (isa<ConstantSDNode>(SndLaneEltCond))
8030 Lane2Cond = !isZero(SndLaneEltCond);
8032 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8033 // Lane1Cond != 0, means we want the first argument.
8034 // Lane1Cond == 0, means we want the second argument.
8035 // The encoding of this argument is 0 for the first argument, 1
8036 // for the second. Therefore, invert the condition.
8037 MaskValue |= !Lane1Cond << i;
8038 else if (Lane1Cond < 0)
8039 MaskValue |= !Lane2Cond << i;
8046 // Try to lower a vselect node into a simple blend instruction.
8047 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8048 SelectionDAG &DAG) {
8049 SDValue Cond = Op.getOperand(0);
8050 SDValue LHS = Op.getOperand(1);
8051 SDValue RHS = Op.getOperand(2);
8053 MVT VT = Op.getSimpleValueType();
8054 MVT EltVT = VT.getVectorElementType();
8055 unsigned NumElems = VT.getVectorNumElements();
8057 // There is no blend with immediate in AVX-512.
8058 if (VT.is512BitVector())
8061 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8063 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8066 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8069 // Check the mask for BLEND and build the value.
8070 unsigned MaskValue = 0;
8071 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8074 // Convert i32 vectors to floating point if it is not AVX2.
8075 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8077 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8078 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8080 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8081 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8084 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8085 DAG.getConstant(MaskValue, MVT::i32));
8086 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8089 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8090 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8091 if (BlendOp.getNode())
8094 // Some types for vselect were previously set to Expand, not Legal or
8095 // Custom. Return an empty SDValue so we fall-through to Expand, after
8096 // the Custom lowering phase.
8097 MVT VT = Op.getSimpleValueType();
8098 switch (VT.SimpleTy) {
8106 // We couldn't create a "Blend with immediate" node.
8107 // This node should still be legal, but we'll have to emit a blendv*
8112 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8113 MVT VT = Op.getSimpleValueType();
8116 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8119 if (VT.getSizeInBits() == 8) {
8120 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8121 Op.getOperand(0), Op.getOperand(1));
8122 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8123 DAG.getValueType(VT));
8124 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8127 if (VT.getSizeInBits() == 16) {
8128 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8129 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8131 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8132 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8133 DAG.getNode(ISD::BITCAST, dl,
8137 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8138 Op.getOperand(0), Op.getOperand(1));
8139 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8140 DAG.getValueType(VT));
8141 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8144 if (VT == MVT::f32) {
8145 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8146 // the result back to FR32 register. It's only worth matching if the
8147 // result has a single use which is a store or a bitcast to i32. And in
8148 // the case of a store, it's not worth it if the index is a constant 0,
8149 // because a MOVSSmr can be used instead, which is smaller and faster.
8150 if (!Op.hasOneUse())
8152 SDNode *User = *Op.getNode()->use_begin();
8153 if ((User->getOpcode() != ISD::STORE ||
8154 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8155 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8156 (User->getOpcode() != ISD::BITCAST ||
8157 User->getValueType(0) != MVT::i32))
8159 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8160 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8163 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8166 if (VT == MVT::i32 || VT == MVT::i64) {
8167 // ExtractPS/pextrq works with constant index.
8168 if (isa<ConstantSDNode>(Op.getOperand(1)))
8174 /// Extract one bit from mask vector, like v16i1 or v8i1.
8175 /// AVX-512 feature.
8177 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8178 SDValue Vec = Op.getOperand(0);
8180 MVT VecVT = Vec.getSimpleValueType();
8181 SDValue Idx = Op.getOperand(1);
8182 MVT EltVT = Op.getSimpleValueType();
8184 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8186 // variable index can't be handled in mask registers,
8187 // extend vector to VR512
8188 if (!isa<ConstantSDNode>(Idx)) {
8189 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8190 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8191 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8192 ExtVT.getVectorElementType(), Ext, Idx);
8193 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8196 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8197 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8198 unsigned MaxSift = rc->getSize()*8 - 1;
8199 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8200 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8201 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8202 DAG.getConstant(MaxSift, MVT::i8));
8203 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8204 DAG.getIntPtrConstant(0));
8208 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8209 SelectionDAG &DAG) const {
8211 SDValue Vec = Op.getOperand(0);
8212 MVT VecVT = Vec.getSimpleValueType();
8213 SDValue Idx = Op.getOperand(1);
8215 if (Op.getSimpleValueType() == MVT::i1)
8216 return ExtractBitFromMaskVector(Op, DAG);
8218 if (!isa<ConstantSDNode>(Idx)) {
8219 if (VecVT.is512BitVector() ||
8220 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8221 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8224 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8225 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8226 MaskEltVT.getSizeInBits());
8228 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8229 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8230 getZeroVector(MaskVT, Subtarget, DAG, dl),
8231 Idx, DAG.getConstant(0, getPointerTy()));
8232 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8233 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8234 Perm, DAG.getConstant(0, getPointerTy()));
8239 // If this is a 256-bit vector result, first extract the 128-bit vector and
8240 // then extract the element from the 128-bit vector.
8241 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8243 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8244 // Get the 128-bit vector.
8245 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8246 MVT EltVT = VecVT.getVectorElementType();
8248 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8250 //if (IdxVal >= NumElems/2)
8251 // IdxVal -= NumElems/2;
8252 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8253 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8254 DAG.getConstant(IdxVal, MVT::i32));
8257 assert(VecVT.is128BitVector() && "Unexpected vector length");
8259 if (Subtarget->hasSSE41()) {
8260 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8265 MVT VT = Op.getSimpleValueType();
8266 // TODO: handle v16i8.
8267 if (VT.getSizeInBits() == 16) {
8268 SDValue Vec = Op.getOperand(0);
8269 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8271 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8272 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8273 DAG.getNode(ISD::BITCAST, dl,
8276 // Transform it so it match pextrw which produces a 32-bit result.
8277 MVT EltVT = MVT::i32;
8278 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8279 Op.getOperand(0), Op.getOperand(1));
8280 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8281 DAG.getValueType(VT));
8282 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8285 if (VT.getSizeInBits() == 32) {
8286 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8290 // SHUFPS the element to the lowest double word, then movss.
8291 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8292 MVT VVT = Op.getOperand(0).getSimpleValueType();
8293 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8294 DAG.getUNDEF(VVT), Mask);
8295 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8296 DAG.getIntPtrConstant(0));
8299 if (VT.getSizeInBits() == 64) {
8300 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8301 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8302 // to match extract_elt for f64.
8303 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8307 // UNPCKHPD the element to the lowest double word, then movsd.
8308 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8309 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8310 int Mask[2] = { 1, -1 };
8311 MVT VVT = Op.getOperand(0).getSimpleValueType();
8312 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8313 DAG.getUNDEF(VVT), Mask);
8314 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8315 DAG.getIntPtrConstant(0));
8321 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8322 MVT VT = Op.getSimpleValueType();
8323 MVT EltVT = VT.getVectorElementType();
8326 SDValue N0 = Op.getOperand(0);
8327 SDValue N1 = Op.getOperand(1);
8328 SDValue N2 = Op.getOperand(2);
8330 if (!VT.is128BitVector())
8333 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8334 isa<ConstantSDNode>(N2)) {
8336 if (VT == MVT::v8i16)
8337 Opc = X86ISD::PINSRW;
8338 else if (VT == MVT::v16i8)
8339 Opc = X86ISD::PINSRB;
8341 Opc = X86ISD::PINSRB;
8343 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8345 if (N1.getValueType() != MVT::i32)
8346 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8347 if (N2.getValueType() != MVT::i32)
8348 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8349 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8352 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8353 // Bits [7:6] of the constant are the source select. This will always be
8354 // zero here. The DAG Combiner may combine an extract_elt index into these
8355 // bits. For example (insert (extract, 3), 2) could be matched by putting
8356 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8357 // Bits [5:4] of the constant are the destination select. This is the
8358 // value of the incoming immediate.
8359 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8360 // combine either bitwise AND or insert of float 0.0 to set these bits.
8361 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8362 // Create this as a scalar to vector..
8363 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8364 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8367 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8368 // PINSR* works with constant index.
8374 /// Insert one bit to mask vector, like v16i1 or v8i1.
8375 /// AVX-512 feature.
8377 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8379 SDValue Vec = Op.getOperand(0);
8380 SDValue Elt = Op.getOperand(1);
8381 SDValue Idx = Op.getOperand(2);
8382 MVT VecVT = Vec.getSimpleValueType();
8384 if (!isa<ConstantSDNode>(Idx)) {
8385 // Non constant index. Extend source and destination,
8386 // insert element and then truncate the result.
8387 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8388 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8389 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8390 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8391 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8392 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8395 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8396 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8397 if (Vec.getOpcode() == ISD::UNDEF)
8398 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8399 DAG.getConstant(IdxVal, MVT::i8));
8400 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8401 unsigned MaxSift = rc->getSize()*8 - 1;
8402 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8403 DAG.getConstant(MaxSift, MVT::i8));
8404 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8405 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8406 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8409 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8410 MVT VT = Op.getSimpleValueType();
8411 MVT EltVT = VT.getVectorElementType();
8413 if (EltVT == MVT::i1)
8414 return InsertBitToMaskVector(Op, DAG);
8417 SDValue N0 = Op.getOperand(0);
8418 SDValue N1 = Op.getOperand(1);
8419 SDValue N2 = Op.getOperand(2);
8421 // If this is a 256-bit vector result, first extract the 128-bit vector,
8422 // insert the element into the extracted half and then place it back.
8423 if (VT.is256BitVector() || VT.is512BitVector()) {
8424 if (!isa<ConstantSDNode>(N2))
8427 // Get the desired 128-bit vector half.
8428 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8429 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8431 // Insert the element into the desired half.
8432 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8433 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8435 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8436 DAG.getConstant(IdxIn128, MVT::i32));
8438 // Insert the changed part back to the 256-bit vector
8439 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8442 if (Subtarget->hasSSE41())
8443 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8445 if (EltVT == MVT::i8)
8448 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8449 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8450 // as its second argument.
8451 if (N1.getValueType() != MVT::i32)
8452 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8453 if (N2.getValueType() != MVT::i32)
8454 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8455 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8460 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8462 MVT OpVT = Op.getSimpleValueType();
8464 // If this is a 256-bit vector result, first insert into a 128-bit
8465 // vector and then insert into the 256-bit vector.
8466 if (!OpVT.is128BitVector()) {
8467 // Insert into a 128-bit vector.
8468 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8469 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8470 OpVT.getVectorNumElements() / SizeFactor);
8472 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8474 // Insert the 128-bit vector.
8475 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8478 if (OpVT == MVT::v1i64 &&
8479 Op.getOperand(0).getValueType() == MVT::i64)
8480 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8482 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8483 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8484 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8485 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8488 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8489 // a simple subregister reference or explicit instructions to grab
8490 // upper bits of a vector.
8491 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8492 SelectionDAG &DAG) {
8494 SDValue In = Op.getOperand(0);
8495 SDValue Idx = Op.getOperand(1);
8496 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8497 MVT ResVT = Op.getSimpleValueType();
8498 MVT InVT = In.getSimpleValueType();
8500 if (Subtarget->hasFp256()) {
8501 if (ResVT.is128BitVector() &&
8502 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8503 isa<ConstantSDNode>(Idx)) {
8504 return Extract128BitVector(In, IdxVal, DAG, dl);
8506 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8507 isa<ConstantSDNode>(Idx)) {
8508 return Extract256BitVector(In, IdxVal, DAG, dl);
8514 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8515 // simple superregister reference or explicit instructions to insert
8516 // the upper bits of a vector.
8517 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8518 SelectionDAG &DAG) {
8519 if (Subtarget->hasFp256()) {
8520 SDLoc dl(Op.getNode());
8521 SDValue Vec = Op.getNode()->getOperand(0);
8522 SDValue SubVec = Op.getNode()->getOperand(1);
8523 SDValue Idx = Op.getNode()->getOperand(2);
8525 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8526 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8527 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8528 isa<ConstantSDNode>(Idx)) {
8529 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8530 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8533 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8534 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8535 isa<ConstantSDNode>(Idx)) {
8536 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8537 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8543 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8544 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8545 // one of the above mentioned nodes. It has to be wrapped because otherwise
8546 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8547 // be used to form addressing mode. These wrapped nodes will be selected
8550 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8551 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8553 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8555 unsigned char OpFlag = 0;
8556 unsigned WrapperKind = X86ISD::Wrapper;
8557 CodeModel::Model M = getTargetMachine().getCodeModel();
8559 if (Subtarget->isPICStyleRIPRel() &&
8560 (M == CodeModel::Small || M == CodeModel::Kernel))
8561 WrapperKind = X86ISD::WrapperRIP;
8562 else if (Subtarget->isPICStyleGOT())
8563 OpFlag = X86II::MO_GOTOFF;
8564 else if (Subtarget->isPICStyleStubPIC())
8565 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8567 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8569 CP->getOffset(), OpFlag);
8571 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8572 // With PIC, the address is actually $g + Offset.
8574 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8575 DAG.getNode(X86ISD::GlobalBaseReg,
8576 SDLoc(), getPointerTy()),
8583 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8584 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8586 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8588 unsigned char OpFlag = 0;
8589 unsigned WrapperKind = X86ISD::Wrapper;
8590 CodeModel::Model M = getTargetMachine().getCodeModel();
8592 if (Subtarget->isPICStyleRIPRel() &&
8593 (M == CodeModel::Small || M == CodeModel::Kernel))
8594 WrapperKind = X86ISD::WrapperRIP;
8595 else if (Subtarget->isPICStyleGOT())
8596 OpFlag = X86II::MO_GOTOFF;
8597 else if (Subtarget->isPICStyleStubPIC())
8598 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8600 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8603 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8605 // With PIC, the address is actually $g + Offset.
8607 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8608 DAG.getNode(X86ISD::GlobalBaseReg,
8609 SDLoc(), getPointerTy()),
8616 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8617 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8619 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8621 unsigned char OpFlag = 0;
8622 unsigned WrapperKind = X86ISD::Wrapper;
8623 CodeModel::Model M = getTargetMachine().getCodeModel();
8625 if (Subtarget->isPICStyleRIPRel() &&
8626 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8627 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8628 OpFlag = X86II::MO_GOTPCREL;
8629 WrapperKind = X86ISD::WrapperRIP;
8630 } else if (Subtarget->isPICStyleGOT()) {
8631 OpFlag = X86II::MO_GOT;
8632 } else if (Subtarget->isPICStyleStubPIC()) {
8633 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8634 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8635 OpFlag = X86II::MO_DARWIN_NONLAZY;
8638 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8641 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8643 // With PIC, the address is actually $g + Offset.
8644 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8645 !Subtarget->is64Bit()) {
8646 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8647 DAG.getNode(X86ISD::GlobalBaseReg,
8648 SDLoc(), getPointerTy()),
8652 // For symbols that require a load from a stub to get the address, emit the
8654 if (isGlobalStubReference(OpFlag))
8655 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8656 MachinePointerInfo::getGOT(), false, false, false, 0);
8662 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8663 // Create the TargetBlockAddressAddress node.
8664 unsigned char OpFlags =
8665 Subtarget->ClassifyBlockAddressReference();
8666 CodeModel::Model M = getTargetMachine().getCodeModel();
8667 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8668 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8670 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8673 if (Subtarget->isPICStyleRIPRel() &&
8674 (M == CodeModel::Small || M == CodeModel::Kernel))
8675 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8677 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8679 // With PIC, the address is actually $g + Offset.
8680 if (isGlobalRelativeToPICBase(OpFlags)) {
8681 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8682 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8690 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8691 int64_t Offset, SelectionDAG &DAG) const {
8692 // Create the TargetGlobalAddress node, folding in the constant
8693 // offset if it is legal.
8694 unsigned char OpFlags =
8695 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8696 CodeModel::Model M = getTargetMachine().getCodeModel();
8698 if (OpFlags == X86II::MO_NO_FLAG &&
8699 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8700 // A direct static reference to a global.
8701 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8704 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8707 if (Subtarget->isPICStyleRIPRel() &&
8708 (M == CodeModel::Small || M == CodeModel::Kernel))
8709 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8711 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8713 // With PIC, the address is actually $g + Offset.
8714 if (isGlobalRelativeToPICBase(OpFlags)) {
8715 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8716 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8720 // For globals that require a load from a stub to get the address, emit the
8722 if (isGlobalStubReference(OpFlags))
8723 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8724 MachinePointerInfo::getGOT(), false, false, false, 0);
8726 // If there was a non-zero offset that we didn't fold, create an explicit
8729 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8730 DAG.getConstant(Offset, getPointerTy()));
8736 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8737 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8738 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8739 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8743 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8744 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8745 unsigned char OperandFlags, bool LocalDynamic = false) {
8746 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8747 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8749 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8750 GA->getValueType(0),
8754 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8758 SDValue Ops[] = { Chain, TGA, *InFlag };
8759 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8761 SDValue Ops[] = { Chain, TGA };
8762 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8765 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8766 MFI->setAdjustsStack(true);
8768 SDValue Flag = Chain.getValue(1);
8769 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8772 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8774 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8777 SDLoc dl(GA); // ? function entry point might be better
8778 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8779 DAG.getNode(X86ISD::GlobalBaseReg,
8780 SDLoc(), PtrVT), InFlag);
8781 InFlag = Chain.getValue(1);
8783 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8786 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8788 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8790 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8791 X86::RAX, X86II::MO_TLSGD);
8794 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8800 // Get the start address of the TLS block for this module.
8801 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8802 .getInfo<X86MachineFunctionInfo>();
8803 MFI->incNumLocalDynamicTLSAccesses();
8807 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8808 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8811 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8812 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8813 InFlag = Chain.getValue(1);
8814 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8815 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8818 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8822 unsigned char OperandFlags = X86II::MO_DTPOFF;
8823 unsigned WrapperKind = X86ISD::Wrapper;
8824 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8825 GA->getValueType(0),
8826 GA->getOffset(), OperandFlags);
8827 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8829 // Add x@dtpoff with the base.
8830 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8833 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8834 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8835 const EVT PtrVT, TLSModel::Model model,
8836 bool is64Bit, bool isPIC) {
8839 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8840 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8841 is64Bit ? 257 : 256));
8843 SDValue ThreadPointer =
8844 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8845 MachinePointerInfo(Ptr), false, false, false, 0);
8847 unsigned char OperandFlags = 0;
8848 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8850 unsigned WrapperKind = X86ISD::Wrapper;
8851 if (model == TLSModel::LocalExec) {
8852 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8853 } else if (model == TLSModel::InitialExec) {
8855 OperandFlags = X86II::MO_GOTTPOFF;
8856 WrapperKind = X86ISD::WrapperRIP;
8858 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8861 llvm_unreachable("Unexpected model");
8864 // emit "addl x@ntpoff,%eax" (local exec)
8865 // or "addl x@indntpoff,%eax" (initial exec)
8866 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8868 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8869 GA->getOffset(), OperandFlags);
8870 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8872 if (model == TLSModel::InitialExec) {
8873 if (isPIC && !is64Bit) {
8874 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8875 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8879 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8880 MachinePointerInfo::getGOT(), false, false, false, 0);
8883 // The address of the thread local variable is the add of the thread
8884 // pointer with the offset of the variable.
8885 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8889 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8891 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8892 const GlobalValue *GV = GA->getGlobal();
8894 if (Subtarget->isTargetELF()) {
8895 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8898 case TLSModel::GeneralDynamic:
8899 if (Subtarget->is64Bit())
8900 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8901 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8902 case TLSModel::LocalDynamic:
8903 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8904 Subtarget->is64Bit());
8905 case TLSModel::InitialExec:
8906 case TLSModel::LocalExec:
8907 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8908 Subtarget->is64Bit(),
8909 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8911 llvm_unreachable("Unknown TLS model.");
8914 if (Subtarget->isTargetDarwin()) {
8915 // Darwin only has one model of TLS. Lower to that.
8916 unsigned char OpFlag = 0;
8917 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8918 X86ISD::WrapperRIP : X86ISD::Wrapper;
8920 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8922 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8923 !Subtarget->is64Bit();
8925 OpFlag = X86II::MO_TLVP_PIC_BASE;
8927 OpFlag = X86II::MO_TLVP;
8929 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8930 GA->getValueType(0),
8931 GA->getOffset(), OpFlag);
8932 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8934 // With PIC32, the address is actually $g + Offset.
8936 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8937 DAG.getNode(X86ISD::GlobalBaseReg,
8938 SDLoc(), getPointerTy()),
8941 // Lowering the machine isd will make sure everything is in the right
8943 SDValue Chain = DAG.getEntryNode();
8944 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8945 SDValue Args[] = { Chain, Offset };
8946 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8948 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8949 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8950 MFI->setAdjustsStack(true);
8952 // And our return value (tls address) is in the standard call return value
8954 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8955 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8959 if (Subtarget->isTargetKnownWindowsMSVC() ||
8960 Subtarget->isTargetWindowsGNU()) {
8961 // Just use the implicit TLS architecture
8962 // Need to generate someting similar to:
8963 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8965 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8966 // mov rcx, qword [rdx+rcx*8]
8967 // mov eax, .tls$:tlsvar
8968 // [rax+rcx] contains the address
8969 // Windows 64bit: gs:0x58
8970 // Windows 32bit: fs:__tls_array
8973 SDValue Chain = DAG.getEntryNode();
8975 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8976 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8977 // use its literal value of 0x2C.
8978 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8979 ? Type::getInt8PtrTy(*DAG.getContext(),
8981 : Type::getInt32PtrTy(*DAG.getContext(),
8985 Subtarget->is64Bit()
8986 ? DAG.getIntPtrConstant(0x58)
8987 : (Subtarget->isTargetWindowsGNU()
8988 ? DAG.getIntPtrConstant(0x2C)
8989 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8991 SDValue ThreadPointer =
8992 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8993 MachinePointerInfo(Ptr), false, false, false, 0);
8995 // Load the _tls_index variable
8996 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8997 if (Subtarget->is64Bit())
8998 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8999 IDX, MachinePointerInfo(), MVT::i32,
9002 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9003 false, false, false, 0);
9005 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9007 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9009 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9010 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9011 false, false, false, 0);
9013 // Get the offset of start of .tls section
9014 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9015 GA->getValueType(0),
9016 GA->getOffset(), X86II::MO_SECREL);
9017 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9019 // The address of the thread local variable is the add of the thread
9020 // pointer with the offset of the variable.
9021 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9024 llvm_unreachable("TLS not implemented for this target.");
9027 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9028 /// and take a 2 x i32 value to shift plus a shift amount.
9029 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9030 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9031 MVT VT = Op.getSimpleValueType();
9032 unsigned VTBits = VT.getSizeInBits();
9034 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9035 SDValue ShOpLo = Op.getOperand(0);
9036 SDValue ShOpHi = Op.getOperand(1);
9037 SDValue ShAmt = Op.getOperand(2);
9038 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9039 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9041 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9042 DAG.getConstant(VTBits - 1, MVT::i8));
9043 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9044 DAG.getConstant(VTBits - 1, MVT::i8))
9045 : DAG.getConstant(0, VT);
9048 if (Op.getOpcode() == ISD::SHL_PARTS) {
9049 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9050 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9052 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9053 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9056 // If the shift amount is larger or equal than the width of a part we can't
9057 // rely on the results of shld/shrd. Insert a test and select the appropriate
9058 // values for large shift amounts.
9059 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9060 DAG.getConstant(VTBits, MVT::i8));
9061 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9062 AndNode, DAG.getConstant(0, MVT::i8));
9065 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9066 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9067 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9069 if (Op.getOpcode() == ISD::SHL_PARTS) {
9070 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9071 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9073 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9074 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9077 SDValue Ops[2] = { Lo, Hi };
9078 return DAG.getMergeValues(Ops, dl);
9081 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9082 SelectionDAG &DAG) const {
9083 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9085 if (SrcVT.isVector())
9088 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9089 "Unknown SINT_TO_FP to lower!");
9091 // These are really Legal; return the operand so the caller accepts it as
9093 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9095 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9096 Subtarget->is64Bit()) {
9101 unsigned Size = SrcVT.getSizeInBits()/8;
9102 MachineFunction &MF = DAG.getMachineFunction();
9103 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9104 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9105 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9107 MachinePointerInfo::getFixedStack(SSFI),
9109 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9112 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9114 SelectionDAG &DAG) const {
9118 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9120 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9122 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9124 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9126 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9127 MachineMemOperand *MMO;
9129 int SSFI = FI->getIndex();
9131 DAG.getMachineFunction()
9132 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9133 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9135 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9136 StackSlot = StackSlot.getOperand(1);
9138 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9139 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9141 Tys, Ops, SrcVT, MMO);
9144 Chain = Result.getValue(1);
9145 SDValue InFlag = Result.getValue(2);
9147 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9148 // shouldn't be necessary except that RFP cannot be live across
9149 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9150 MachineFunction &MF = DAG.getMachineFunction();
9151 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9152 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9153 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9154 Tys = DAG.getVTList(MVT::Other);
9156 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9158 MachineMemOperand *MMO =
9159 DAG.getMachineFunction()
9160 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9161 MachineMemOperand::MOStore, SSFISize, SSFISize);
9163 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9164 Ops, Op.getValueType(), MMO);
9165 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9166 MachinePointerInfo::getFixedStack(SSFI),
9167 false, false, false, 0);
9173 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9174 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9175 SelectionDAG &DAG) const {
9176 // This algorithm is not obvious. Here it is what we're trying to output:
9179 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9180 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9184 pshufd $0x4e, %xmm0, %xmm1
9190 LLVMContext *Context = DAG.getContext();
9192 // Build some magic constants.
9193 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9194 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9195 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9197 SmallVector<Constant*,2> CV1;
9199 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9200 APInt(64, 0x4330000000000000ULL))));
9202 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9203 APInt(64, 0x4530000000000000ULL))));
9204 Constant *C1 = ConstantVector::get(CV1);
9205 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9207 // Load the 64-bit value into an XMM register.
9208 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9210 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9211 MachinePointerInfo::getConstantPool(),
9212 false, false, false, 16);
9213 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9214 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9217 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9218 MachinePointerInfo::getConstantPool(),
9219 false, false, false, 16);
9220 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9221 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9224 if (Subtarget->hasSSE3()) {
9225 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9226 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9228 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9229 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9231 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9232 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9236 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9237 DAG.getIntPtrConstant(0));
9240 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9241 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9242 SelectionDAG &DAG) const {
9244 // FP constant to bias correct the final result.
9245 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9248 // Load the 32-bit value into an XMM register.
9249 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9252 // Zero out the upper parts of the register.
9253 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9255 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9256 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9257 DAG.getIntPtrConstant(0));
9259 // Or the load with the bias.
9260 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9261 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9262 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9264 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9265 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9266 MVT::v2f64, Bias)));
9267 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9268 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9269 DAG.getIntPtrConstant(0));
9271 // Subtract the bias.
9272 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9274 // Handle final rounding.
9275 EVT DestVT = Op.getValueType();
9277 if (DestVT.bitsLT(MVT::f64))
9278 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9279 DAG.getIntPtrConstant(0));
9280 if (DestVT.bitsGT(MVT::f64))
9281 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9283 // Handle final rounding.
9287 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9288 SelectionDAG &DAG) const {
9289 SDValue N0 = Op.getOperand(0);
9290 MVT SVT = N0.getSimpleValueType();
9293 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9294 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9295 "Custom UINT_TO_FP is not supported!");
9297 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9298 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9299 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9302 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9303 SelectionDAG &DAG) const {
9304 SDValue N0 = Op.getOperand(0);
9307 if (Op.getValueType().isVector())
9308 return lowerUINT_TO_FP_vec(Op, DAG);
9310 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9311 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9312 // the optimization here.
9313 if (DAG.SignBitIsZero(N0))
9314 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9316 MVT SrcVT = N0.getSimpleValueType();
9317 MVT DstVT = Op.getSimpleValueType();
9318 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9319 return LowerUINT_TO_FP_i64(Op, DAG);
9320 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9321 return LowerUINT_TO_FP_i32(Op, DAG);
9322 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9325 // Make a 64-bit buffer, and use it to build an FILD.
9326 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9327 if (SrcVT == MVT::i32) {
9328 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9329 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9330 getPointerTy(), StackSlot, WordOff);
9331 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9332 StackSlot, MachinePointerInfo(),
9334 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9335 OffsetSlot, MachinePointerInfo(),
9337 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9341 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9342 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9343 StackSlot, MachinePointerInfo(),
9345 // For i64 source, we need to add the appropriate power of 2 if the input
9346 // was negative. This is the same as the optimization in
9347 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9348 // we must be careful to do the computation in x87 extended precision, not
9349 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9350 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9351 MachineMemOperand *MMO =
9352 DAG.getMachineFunction()
9353 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9354 MachineMemOperand::MOLoad, 8, 8);
9356 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9357 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9358 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9361 APInt FF(32, 0x5F800000ULL);
9363 // Check whether the sign bit is set.
9364 SDValue SignSet = DAG.getSetCC(dl,
9365 getSetCCResultType(*DAG.getContext(), MVT::i64),
9366 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9369 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9370 SDValue FudgePtr = DAG.getConstantPool(
9371 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9374 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9375 SDValue Zero = DAG.getIntPtrConstant(0);
9376 SDValue Four = DAG.getIntPtrConstant(4);
9377 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9379 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9381 // Load the value out, extending it from f32 to f80.
9382 // FIXME: Avoid the extend by constructing the right constant pool?
9383 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9384 FudgePtr, MachinePointerInfo::getConstantPool(),
9385 MVT::f32, false, false, 4);
9386 // Extend everything to 80 bits to force it to be done on x87.
9387 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9388 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9391 std::pair<SDValue,SDValue>
9392 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9393 bool IsSigned, bool IsReplace) const {
9396 EVT DstTy = Op.getValueType();
9398 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9399 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9403 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9404 DstTy.getSimpleVT() >= MVT::i16 &&
9405 "Unknown FP_TO_INT to lower!");
9407 // These are really Legal.
9408 if (DstTy == MVT::i32 &&
9409 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9410 return std::make_pair(SDValue(), SDValue());
9411 if (Subtarget->is64Bit() &&
9412 DstTy == MVT::i64 &&
9413 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9414 return std::make_pair(SDValue(), SDValue());
9416 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9417 // stack slot, or into the FTOL runtime function.
9418 MachineFunction &MF = DAG.getMachineFunction();
9419 unsigned MemSize = DstTy.getSizeInBits()/8;
9420 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9421 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9424 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9425 Opc = X86ISD::WIN_FTOL;
9427 switch (DstTy.getSimpleVT().SimpleTy) {
9428 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9429 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9430 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9431 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9434 SDValue Chain = DAG.getEntryNode();
9435 SDValue Value = Op.getOperand(0);
9436 EVT TheVT = Op.getOperand(0).getValueType();
9437 // FIXME This causes a redundant load/store if the SSE-class value is already
9438 // in memory, such as if it is on the callstack.
9439 if (isScalarFPTypeInSSEReg(TheVT)) {
9440 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9441 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9442 MachinePointerInfo::getFixedStack(SSFI),
9444 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9446 Chain, StackSlot, DAG.getValueType(TheVT)
9449 MachineMemOperand *MMO =
9450 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9451 MachineMemOperand::MOLoad, MemSize, MemSize);
9452 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9453 Chain = Value.getValue(1);
9454 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9455 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9458 MachineMemOperand *MMO =
9459 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9460 MachineMemOperand::MOStore, MemSize, MemSize);
9462 if (Opc != X86ISD::WIN_FTOL) {
9463 // Build the FP_TO_INT*_IN_MEM
9464 SDValue Ops[] = { Chain, Value, StackSlot };
9465 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9467 return std::make_pair(FIST, StackSlot);
9469 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9470 DAG.getVTList(MVT::Other, MVT::Glue),
9472 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9473 MVT::i32, ftol.getValue(1));
9474 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9475 MVT::i32, eax.getValue(2));
9476 SDValue Ops[] = { eax, edx };
9477 SDValue pair = IsReplace
9478 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9479 : DAG.getMergeValues(Ops, DL);
9480 return std::make_pair(pair, SDValue());
9484 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9485 const X86Subtarget *Subtarget) {
9486 MVT VT = Op->getSimpleValueType(0);
9487 SDValue In = Op->getOperand(0);
9488 MVT InVT = In.getSimpleValueType();
9491 // Optimize vectors in AVX mode:
9494 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9495 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9496 // Concat upper and lower parts.
9499 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9500 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9501 // Concat upper and lower parts.
9504 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9505 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9506 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9509 if (Subtarget->hasInt256())
9510 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9512 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9513 SDValue Undef = DAG.getUNDEF(InVT);
9514 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9515 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9516 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9518 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9519 VT.getVectorNumElements()/2);
9521 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9522 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9524 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9527 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9528 SelectionDAG &DAG) {
9529 MVT VT = Op->getSimpleValueType(0);
9530 SDValue In = Op->getOperand(0);
9531 MVT InVT = In.getSimpleValueType();
9533 unsigned int NumElts = VT.getVectorNumElements();
9534 if (NumElts != 8 && NumElts != 16)
9537 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9538 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9540 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9541 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9542 // Now we have only mask extension
9543 assert(InVT.getVectorElementType() == MVT::i1);
9544 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9545 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9546 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9547 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9548 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9549 MachinePointerInfo::getConstantPool(),
9550 false, false, false, Alignment);
9552 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9553 if (VT.is512BitVector())
9555 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9558 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9559 SelectionDAG &DAG) {
9560 if (Subtarget->hasFp256()) {
9561 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9569 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9570 SelectionDAG &DAG) {
9572 MVT VT = Op.getSimpleValueType();
9573 SDValue In = Op.getOperand(0);
9574 MVT SVT = In.getSimpleValueType();
9576 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9577 return LowerZERO_EXTEND_AVX512(Op, DAG);
9579 if (Subtarget->hasFp256()) {
9580 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9585 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9586 VT.getVectorNumElements() != SVT.getVectorNumElements());
9590 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9592 MVT VT = Op.getSimpleValueType();
9593 SDValue In = Op.getOperand(0);
9594 MVT InVT = In.getSimpleValueType();
9596 if (VT == MVT::i1) {
9597 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9598 "Invalid scalar TRUNCATE operation");
9599 if (InVT == MVT::i32)
9601 if (InVT.getSizeInBits() == 64)
9602 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9603 else if (InVT.getSizeInBits() < 32)
9604 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9605 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9607 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9608 "Invalid TRUNCATE operation");
9610 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9611 if (VT.getVectorElementType().getSizeInBits() >=8)
9612 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9614 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9615 unsigned NumElts = InVT.getVectorNumElements();
9616 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9617 if (InVT.getSizeInBits() < 512) {
9618 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9619 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9623 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9624 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9625 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9626 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9627 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9628 MachinePointerInfo::getConstantPool(),
9629 false, false, false, Alignment);
9630 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9631 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9632 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9635 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9636 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9637 if (Subtarget->hasInt256()) {
9638 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9639 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9640 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9642 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9643 DAG.getIntPtrConstant(0));
9646 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9647 DAG.getIntPtrConstant(0));
9648 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9649 DAG.getIntPtrConstant(2));
9650 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9651 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9652 static const int ShufMask[] = {0, 2, 4, 6};
9653 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9656 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9657 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9658 if (Subtarget->hasInt256()) {
9659 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9661 SmallVector<SDValue,32> pshufbMask;
9662 for (unsigned i = 0; i < 2; ++i) {
9663 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9664 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9665 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9666 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9667 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9668 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9669 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9670 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9671 for (unsigned j = 0; j < 8; ++j)
9672 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9674 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9675 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9676 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9678 static const int ShufMask[] = {0, 2, -1, -1};
9679 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9681 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9682 DAG.getIntPtrConstant(0));
9683 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9686 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9687 DAG.getIntPtrConstant(0));
9689 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9690 DAG.getIntPtrConstant(4));
9692 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9693 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9696 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9697 -1, -1, -1, -1, -1, -1, -1, -1};
9699 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9700 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9701 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9703 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9704 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9706 // The MOVLHPS Mask:
9707 static const int ShufMask2[] = {0, 1, 4, 5};
9708 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9709 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9712 // Handle truncation of V256 to V128 using shuffles.
9713 if (!VT.is128BitVector() || !InVT.is256BitVector())
9716 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9718 unsigned NumElems = VT.getVectorNumElements();
9719 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9721 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9722 // Prepare truncation shuffle mask
9723 for (unsigned i = 0; i != NumElems; ++i)
9725 SDValue V = DAG.getVectorShuffle(NVT, DL,
9726 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9727 DAG.getUNDEF(NVT), &MaskVec[0]);
9728 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9729 DAG.getIntPtrConstant(0));
9732 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9733 SelectionDAG &DAG) const {
9734 assert(!Op.getSimpleValueType().isVector());
9736 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9737 /*IsSigned=*/ true, /*IsReplace=*/ false);
9738 SDValue FIST = Vals.first, StackSlot = Vals.second;
9739 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9740 if (!FIST.getNode()) return Op;
9742 if (StackSlot.getNode())
9744 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9745 FIST, StackSlot, MachinePointerInfo(),
9746 false, false, false, 0);
9748 // The node is the result.
9752 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9753 SelectionDAG &DAG) const {
9754 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9755 /*IsSigned=*/ false, /*IsReplace=*/ false);
9756 SDValue FIST = Vals.first, StackSlot = Vals.second;
9757 assert(FIST.getNode() && "Unexpected failure");
9759 if (StackSlot.getNode())
9761 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9762 FIST, StackSlot, MachinePointerInfo(),
9763 false, false, false, 0);
9765 // The node is the result.
9769 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9771 MVT VT = Op.getSimpleValueType();
9772 SDValue In = Op.getOperand(0);
9773 MVT SVT = In.getSimpleValueType();
9775 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9777 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9778 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9779 In, DAG.getUNDEF(SVT)));
9782 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9783 LLVMContext *Context = DAG.getContext();
9785 MVT VT = Op.getSimpleValueType();
9787 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9788 if (VT.isVector()) {
9789 EltVT = VT.getVectorElementType();
9790 NumElts = VT.getVectorNumElements();
9793 if (EltVT == MVT::f64)
9794 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9795 APInt(64, ~(1ULL << 63))));
9797 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9798 APInt(32, ~(1U << 31))));
9799 C = ConstantVector::getSplat(NumElts, C);
9800 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9801 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9802 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9803 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9804 MachinePointerInfo::getConstantPool(),
9805 false, false, false, Alignment);
9806 if (VT.isVector()) {
9807 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9808 return DAG.getNode(ISD::BITCAST, dl, VT,
9809 DAG.getNode(ISD::AND, dl, ANDVT,
9810 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9812 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9814 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9817 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9818 LLVMContext *Context = DAG.getContext();
9820 MVT VT = Op.getSimpleValueType();
9822 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9823 if (VT.isVector()) {
9824 EltVT = VT.getVectorElementType();
9825 NumElts = VT.getVectorNumElements();
9828 if (EltVT == MVT::f64)
9829 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9830 APInt(64, 1ULL << 63)));
9832 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9833 APInt(32, 1U << 31)));
9834 C = ConstantVector::getSplat(NumElts, C);
9835 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9836 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9837 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9838 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9839 MachinePointerInfo::getConstantPool(),
9840 false, false, false, Alignment);
9841 if (VT.isVector()) {
9842 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9843 return DAG.getNode(ISD::BITCAST, dl, VT,
9844 DAG.getNode(ISD::XOR, dl, XORVT,
9845 DAG.getNode(ISD::BITCAST, dl, XORVT,
9847 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9850 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9853 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9854 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9855 LLVMContext *Context = DAG.getContext();
9856 SDValue Op0 = Op.getOperand(0);
9857 SDValue Op1 = Op.getOperand(1);
9859 MVT VT = Op.getSimpleValueType();
9860 MVT SrcVT = Op1.getSimpleValueType();
9862 // If second operand is smaller, extend it first.
9863 if (SrcVT.bitsLT(VT)) {
9864 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9867 // And if it is bigger, shrink it first.
9868 if (SrcVT.bitsGT(VT)) {
9869 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9873 // At this point the operands and the result should have the same
9874 // type, and that won't be f80 since that is not custom lowered.
9876 // First get the sign bit of second operand.
9877 SmallVector<Constant*,4> CV;
9878 if (SrcVT == MVT::f64) {
9879 const fltSemantics &Sem = APFloat::IEEEdouble;
9880 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9881 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9883 const fltSemantics &Sem = APFloat::IEEEsingle;
9884 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9885 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9886 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9887 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9889 Constant *C = ConstantVector::get(CV);
9890 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9891 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9892 MachinePointerInfo::getConstantPool(),
9893 false, false, false, 16);
9894 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9896 // Shift sign bit right or left if the two operands have different types.
9897 if (SrcVT.bitsGT(VT)) {
9898 // Op0 is MVT::f32, Op1 is MVT::f64.
9899 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9900 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9901 DAG.getConstant(32, MVT::i32));
9902 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9903 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9904 DAG.getIntPtrConstant(0));
9907 // Clear first operand sign bit.
9909 if (VT == MVT::f64) {
9910 const fltSemantics &Sem = APFloat::IEEEdouble;
9911 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9912 APInt(64, ~(1ULL << 63)))));
9913 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9915 const fltSemantics &Sem = APFloat::IEEEsingle;
9916 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9917 APInt(32, ~(1U << 31)))));
9918 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9919 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9920 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9922 C = ConstantVector::get(CV);
9923 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9924 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9925 MachinePointerInfo::getConstantPool(),
9926 false, false, false, 16);
9927 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9929 // Or the value with the sign bit.
9930 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9933 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9934 SDValue N0 = Op.getOperand(0);
9936 MVT VT = Op.getSimpleValueType();
9938 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9939 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9940 DAG.getConstant(1, VT));
9941 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9944 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9946 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9947 SelectionDAG &DAG) {
9948 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9950 if (!Subtarget->hasSSE41())
9953 if (!Op->hasOneUse())
9956 SDNode *N = Op.getNode();
9959 SmallVector<SDValue, 8> Opnds;
9960 DenseMap<SDValue, unsigned> VecInMap;
9961 SmallVector<SDValue, 8> VecIns;
9962 EVT VT = MVT::Other;
9964 // Recognize a special case where a vector is casted into wide integer to
9966 Opnds.push_back(N->getOperand(0));
9967 Opnds.push_back(N->getOperand(1));
9969 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9970 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9971 // BFS traverse all OR'd operands.
9972 if (I->getOpcode() == ISD::OR) {
9973 Opnds.push_back(I->getOperand(0));
9974 Opnds.push_back(I->getOperand(1));
9975 // Re-evaluate the number of nodes to be traversed.
9976 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9980 // Quit if a non-EXTRACT_VECTOR_ELT
9981 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9984 // Quit if without a constant index.
9985 SDValue Idx = I->getOperand(1);
9986 if (!isa<ConstantSDNode>(Idx))
9989 SDValue ExtractedFromVec = I->getOperand(0);
9990 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9991 if (M == VecInMap.end()) {
9992 VT = ExtractedFromVec.getValueType();
9993 // Quit if not 128/256-bit vector.
9994 if (!VT.is128BitVector() && !VT.is256BitVector())
9996 // Quit if not the same type.
9997 if (VecInMap.begin() != VecInMap.end() &&
9998 VT != VecInMap.begin()->first.getValueType())
10000 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10001 VecIns.push_back(ExtractedFromVec);
10003 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10006 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10007 "Not extracted from 128-/256-bit vector.");
10009 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10011 for (DenseMap<SDValue, unsigned>::const_iterator
10012 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10013 // Quit if not all elements are used.
10014 if (I->second != FullMask)
10018 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10020 // Cast all vectors into TestVT for PTEST.
10021 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10022 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10024 // If more than one full vectors are evaluated, OR them first before PTEST.
10025 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10026 // Each iteration will OR 2 nodes and append the result until there is only
10027 // 1 node left, i.e. the final OR'd value of all vectors.
10028 SDValue LHS = VecIns[Slot];
10029 SDValue RHS = VecIns[Slot + 1];
10030 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10033 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10034 VecIns.back(), VecIns.back());
10037 /// \brief return true if \c Op has a use that doesn't just read flags.
10038 static bool hasNonFlagsUse(SDValue Op) {
10039 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10041 SDNode *User = *UI;
10042 unsigned UOpNo = UI.getOperandNo();
10043 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10044 // Look pass truncate.
10045 UOpNo = User->use_begin().getOperandNo();
10046 User = *User->use_begin();
10049 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10050 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10056 /// Emit nodes that will be selected as "test Op0,Op0", or something
10058 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10059 SelectionDAG &DAG) const {
10060 if (Op.getValueType() == MVT::i1)
10061 // KORTEST instruction should be selected
10062 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10063 DAG.getConstant(0, Op.getValueType()));
10065 // CF and OF aren't always set the way we want. Determine which
10066 // of these we need.
10067 bool NeedCF = false;
10068 bool NeedOF = false;
10071 case X86::COND_A: case X86::COND_AE:
10072 case X86::COND_B: case X86::COND_BE:
10075 case X86::COND_G: case X86::COND_GE:
10076 case X86::COND_L: case X86::COND_LE:
10077 case X86::COND_O: case X86::COND_NO:
10081 // See if we can use the EFLAGS value from the operand instead of
10082 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10083 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10084 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10085 // Emit a CMP with 0, which is the TEST pattern.
10086 //if (Op.getValueType() == MVT::i1)
10087 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10088 // DAG.getConstant(0, MVT::i1));
10089 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10090 DAG.getConstant(0, Op.getValueType()));
10092 unsigned Opcode = 0;
10093 unsigned NumOperands = 0;
10095 // Truncate operations may prevent the merge of the SETCC instruction
10096 // and the arithmetic instruction before it. Attempt to truncate the operands
10097 // of the arithmetic instruction and use a reduced bit-width instruction.
10098 bool NeedTruncation = false;
10099 SDValue ArithOp = Op;
10100 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10101 SDValue Arith = Op->getOperand(0);
10102 // Both the trunc and the arithmetic op need to have one user each.
10103 if (Arith->hasOneUse())
10104 switch (Arith.getOpcode()) {
10111 NeedTruncation = true;
10117 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10118 // which may be the result of a CAST. We use the variable 'Op', which is the
10119 // non-casted variable when we check for possible users.
10120 switch (ArithOp.getOpcode()) {
10122 // Due to an isel shortcoming, be conservative if this add is likely to be
10123 // selected as part of a load-modify-store instruction. When the root node
10124 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10125 // uses of other nodes in the match, such as the ADD in this case. This
10126 // leads to the ADD being left around and reselected, with the result being
10127 // two adds in the output. Alas, even if none our users are stores, that
10128 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10129 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10130 // climbing the DAG back to the root, and it doesn't seem to be worth the
10132 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10133 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10134 if (UI->getOpcode() != ISD::CopyToReg &&
10135 UI->getOpcode() != ISD::SETCC &&
10136 UI->getOpcode() != ISD::STORE)
10139 if (ConstantSDNode *C =
10140 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10141 // An add of one will be selected as an INC.
10142 if (C->getAPIntValue() == 1) {
10143 Opcode = X86ISD::INC;
10148 // An add of negative one (subtract of one) will be selected as a DEC.
10149 if (C->getAPIntValue().isAllOnesValue()) {
10150 Opcode = X86ISD::DEC;
10156 // Otherwise use a regular EFLAGS-setting add.
10157 Opcode = X86ISD::ADD;
10162 // If we have a constant logical shift that's only used in a comparison
10163 // against zero turn it into an equivalent AND. This allows turning it into
10164 // a TEST instruction later.
10165 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10166 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10167 EVT VT = Op.getValueType();
10168 unsigned BitWidth = VT.getSizeInBits();
10169 unsigned ShAmt = Op->getConstantOperandVal(1);
10170 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10172 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10173 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10174 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10175 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10177 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10178 DAG.getConstant(Mask, VT));
10179 DAG.ReplaceAllUsesWith(Op, New);
10185 // If the primary and result isn't used, don't bother using X86ISD::AND,
10186 // because a TEST instruction will be better.
10187 if (!hasNonFlagsUse(Op))
10193 // Due to the ISEL shortcoming noted above, be conservative if this op is
10194 // likely to be selected as part of a load-modify-store instruction.
10195 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10196 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10197 if (UI->getOpcode() == ISD::STORE)
10200 // Otherwise use a regular EFLAGS-setting instruction.
10201 switch (ArithOp.getOpcode()) {
10202 default: llvm_unreachable("unexpected operator!");
10203 case ISD::SUB: Opcode = X86ISD::SUB; break;
10204 case ISD::XOR: Opcode = X86ISD::XOR; break;
10205 case ISD::AND: Opcode = X86ISD::AND; break;
10207 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10208 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10209 if (EFLAGS.getNode())
10212 Opcode = X86ISD::OR;
10226 return SDValue(Op.getNode(), 1);
10232 // If we found that truncation is beneficial, perform the truncation and
10234 if (NeedTruncation) {
10235 EVT VT = Op.getValueType();
10236 SDValue WideVal = Op->getOperand(0);
10237 EVT WideVT = WideVal.getValueType();
10238 unsigned ConvertedOp = 0;
10239 // Use a target machine opcode to prevent further DAGCombine
10240 // optimizations that may separate the arithmetic operations
10241 // from the setcc node.
10242 switch (WideVal.getOpcode()) {
10244 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10245 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10246 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10247 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10248 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10252 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10253 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10254 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10255 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10256 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10262 // Emit a CMP with 0, which is the TEST pattern.
10263 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10264 DAG.getConstant(0, Op.getValueType()));
10266 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10267 SmallVector<SDValue, 4> Ops;
10268 for (unsigned i = 0; i != NumOperands; ++i)
10269 Ops.push_back(Op.getOperand(i));
10271 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10272 DAG.ReplaceAllUsesWith(Op, New);
10273 return SDValue(New.getNode(), 1);
10276 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10278 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10279 SDLoc dl, SelectionDAG &DAG) const {
10280 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10281 if (C->getAPIntValue() == 0)
10282 return EmitTest(Op0, X86CC, dl, DAG);
10284 if (Op0.getValueType() == MVT::i1)
10285 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10288 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10289 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10290 // Do the comparison at i32 if it's smaller, besides the Atom case.
10291 // This avoids subregister aliasing issues. Keep the smaller reference
10292 // if we're optimizing for size, however, as that'll allow better folding
10293 // of memory operations.
10294 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10295 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10296 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10297 !Subtarget->isAtom()) {
10298 unsigned ExtendOp =
10299 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10300 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10301 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10303 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10304 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10305 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10307 return SDValue(Sub.getNode(), 1);
10309 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10312 /// Convert a comparison if required by the subtarget.
10313 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10314 SelectionDAG &DAG) const {
10315 // If the subtarget does not support the FUCOMI instruction, floating-point
10316 // comparisons have to be converted.
10317 if (Subtarget->hasCMov() ||
10318 Cmp.getOpcode() != X86ISD::CMP ||
10319 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10320 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10323 // The instruction selector will select an FUCOM instruction instead of
10324 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10325 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10326 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10328 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10329 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10330 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10331 DAG.getConstant(8, MVT::i8));
10332 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10333 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10336 static bool isAllOnes(SDValue V) {
10337 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10338 return C && C->isAllOnesValue();
10341 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10342 /// if it's possible.
10343 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10344 SDLoc dl, SelectionDAG &DAG) const {
10345 SDValue Op0 = And.getOperand(0);
10346 SDValue Op1 = And.getOperand(1);
10347 if (Op0.getOpcode() == ISD::TRUNCATE)
10348 Op0 = Op0.getOperand(0);
10349 if (Op1.getOpcode() == ISD::TRUNCATE)
10350 Op1 = Op1.getOperand(0);
10353 if (Op1.getOpcode() == ISD::SHL)
10354 std::swap(Op0, Op1);
10355 if (Op0.getOpcode() == ISD::SHL) {
10356 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10357 if (And00C->getZExtValue() == 1) {
10358 // If we looked past a truncate, check that it's only truncating away
10360 unsigned BitWidth = Op0.getValueSizeInBits();
10361 unsigned AndBitWidth = And.getValueSizeInBits();
10362 if (BitWidth > AndBitWidth) {
10364 DAG.computeKnownBits(Op0, Zeros, Ones);
10365 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10369 RHS = Op0.getOperand(1);
10371 } else if (Op1.getOpcode() == ISD::Constant) {
10372 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10373 uint64_t AndRHSVal = AndRHS->getZExtValue();
10374 SDValue AndLHS = Op0;
10376 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10377 LHS = AndLHS.getOperand(0);
10378 RHS = AndLHS.getOperand(1);
10381 // Use BT if the immediate can't be encoded in a TEST instruction.
10382 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10384 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10388 if (LHS.getNode()) {
10389 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10390 // instruction. Since the shift amount is in-range-or-undefined, we know
10391 // that doing a bittest on the i32 value is ok. We extend to i32 because
10392 // the encoding for the i16 version is larger than the i32 version.
10393 // Also promote i16 to i32 for performance / code size reason.
10394 if (LHS.getValueType() == MVT::i8 ||
10395 LHS.getValueType() == MVT::i16)
10396 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10398 // If the operand types disagree, extend the shift amount to match. Since
10399 // BT ignores high bits (like shifts) we can use anyextend.
10400 if (LHS.getValueType() != RHS.getValueType())
10401 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10403 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10404 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10405 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10406 DAG.getConstant(Cond, MVT::i8), BT);
10412 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10414 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10419 // SSE Condition code mapping:
10428 switch (SetCCOpcode) {
10429 default: llvm_unreachable("Unexpected SETCC condition");
10431 case ISD::SETEQ: SSECC = 0; break;
10433 case ISD::SETGT: Swap = true; // Fallthrough
10435 case ISD::SETOLT: SSECC = 1; break;
10437 case ISD::SETGE: Swap = true; // Fallthrough
10439 case ISD::SETOLE: SSECC = 2; break;
10440 case ISD::SETUO: SSECC = 3; break;
10442 case ISD::SETNE: SSECC = 4; break;
10443 case ISD::SETULE: Swap = true; // Fallthrough
10444 case ISD::SETUGE: SSECC = 5; break;
10445 case ISD::SETULT: Swap = true; // Fallthrough
10446 case ISD::SETUGT: SSECC = 6; break;
10447 case ISD::SETO: SSECC = 7; break;
10449 case ISD::SETONE: SSECC = 8; break;
10452 std::swap(Op0, Op1);
10457 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10458 // ones, and then concatenate the result back.
10459 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10460 MVT VT = Op.getSimpleValueType();
10462 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10463 "Unsupported value type for operation");
10465 unsigned NumElems = VT.getVectorNumElements();
10467 SDValue CC = Op.getOperand(2);
10469 // Extract the LHS vectors
10470 SDValue LHS = Op.getOperand(0);
10471 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10472 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10474 // Extract the RHS vectors
10475 SDValue RHS = Op.getOperand(1);
10476 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10477 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10479 // Issue the operation on the smaller types and concatenate the result back
10480 MVT EltVT = VT.getVectorElementType();
10481 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10482 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10483 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10484 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10487 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10488 const X86Subtarget *Subtarget) {
10489 SDValue Op0 = Op.getOperand(0);
10490 SDValue Op1 = Op.getOperand(1);
10491 SDValue CC = Op.getOperand(2);
10492 MVT VT = Op.getSimpleValueType();
10495 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10496 Op.getValueType().getScalarType() == MVT::i1 &&
10497 "Cannot set masked compare for this operation");
10499 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10501 bool Unsigned = false;
10504 switch (SetCCOpcode) {
10505 default: llvm_unreachable("Unexpected SETCC condition");
10506 case ISD::SETNE: SSECC = 4; break;
10507 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10508 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10509 case ISD::SETLT: Swap = true; //fall-through
10510 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10511 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10512 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10513 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10514 case ISD::SETULE: Unsigned = true; //fall-through
10515 case ISD::SETLE: SSECC = 2; break;
10519 std::swap(Op0, Op1);
10521 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10522 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10523 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10524 DAG.getConstant(SSECC, MVT::i8));
10527 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10528 /// operand \p Op1. If non-trivial (for example because it's not constant)
10529 /// return an empty value.
10530 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10532 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10536 MVT VT = Op1.getSimpleValueType();
10537 MVT EVT = VT.getVectorElementType();
10538 unsigned n = VT.getVectorNumElements();
10539 SmallVector<SDValue, 8> ULTOp1;
10541 for (unsigned i = 0; i < n; ++i) {
10542 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10543 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10546 // Avoid underflow.
10547 APInt Val = Elt->getAPIntValue();
10551 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10554 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10557 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10558 SelectionDAG &DAG) {
10559 SDValue Op0 = Op.getOperand(0);
10560 SDValue Op1 = Op.getOperand(1);
10561 SDValue CC = Op.getOperand(2);
10562 MVT VT = Op.getSimpleValueType();
10563 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10564 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10569 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10570 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10573 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10574 unsigned Opc = X86ISD::CMPP;
10575 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10576 assert(VT.getVectorNumElements() <= 16);
10577 Opc = X86ISD::CMPM;
10579 // In the two special cases we can't handle, emit two comparisons.
10582 unsigned CombineOpc;
10583 if (SetCCOpcode == ISD::SETUEQ) {
10584 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10586 assert(SetCCOpcode == ISD::SETONE);
10587 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10590 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10591 DAG.getConstant(CC0, MVT::i8));
10592 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10593 DAG.getConstant(CC1, MVT::i8));
10594 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10596 // Handle all other FP comparisons here.
10597 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10598 DAG.getConstant(SSECC, MVT::i8));
10601 // Break 256-bit integer vector compare into smaller ones.
10602 if (VT.is256BitVector() && !Subtarget->hasInt256())
10603 return Lower256IntVSETCC(Op, DAG);
10605 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10606 EVT OpVT = Op1.getValueType();
10607 if (Subtarget->hasAVX512()) {
10608 if (Op1.getValueType().is512BitVector() ||
10609 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10610 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10612 // In AVX-512 architecture setcc returns mask with i1 elements,
10613 // But there is no compare instruction for i8 and i16 elements.
10614 // We are not talking about 512-bit operands in this case, these
10615 // types are illegal.
10617 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10618 OpVT.getVectorElementType().getSizeInBits() >= 8))
10619 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10620 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10623 // We are handling one of the integer comparisons here. Since SSE only has
10624 // GT and EQ comparisons for integer, swapping operands and multiple
10625 // operations may be required for some comparisons.
10627 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10628 bool Subus = false;
10630 switch (SetCCOpcode) {
10631 default: llvm_unreachable("Unexpected SETCC condition");
10632 case ISD::SETNE: Invert = true;
10633 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10634 case ISD::SETLT: Swap = true;
10635 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10636 case ISD::SETGE: Swap = true;
10637 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10638 Invert = true; break;
10639 case ISD::SETULT: Swap = true;
10640 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10641 FlipSigns = true; break;
10642 case ISD::SETUGE: Swap = true;
10643 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10644 FlipSigns = true; Invert = true; break;
10647 // Special case: Use min/max operations for SETULE/SETUGE
10648 MVT VET = VT.getVectorElementType();
10650 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10651 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10654 switch (SetCCOpcode) {
10656 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10657 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10660 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10663 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10664 if (!MinMax && hasSubus) {
10665 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10667 // t = psubus Op0, Op1
10668 // pcmpeq t, <0..0>
10669 switch (SetCCOpcode) {
10671 case ISD::SETULT: {
10672 // If the comparison is against a constant we can turn this into a
10673 // setule. With psubus, setule does not require a swap. This is
10674 // beneficial because the constant in the register is no longer
10675 // destructed as the destination so it can be hoisted out of a loop.
10676 // Only do this pre-AVX since vpcmp* is no longer destructive.
10677 if (Subtarget->hasAVX())
10679 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10680 if (ULEOp1.getNode()) {
10682 Subus = true; Invert = false; Swap = false;
10686 // Psubus is better than flip-sign because it requires no inversion.
10687 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10688 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10692 Opc = X86ISD::SUBUS;
10698 std::swap(Op0, Op1);
10700 // Check that the operation in question is available (most are plain SSE2,
10701 // but PCMPGTQ and PCMPEQQ have different requirements).
10702 if (VT == MVT::v2i64) {
10703 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10704 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10706 // First cast everything to the right type.
10707 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10708 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10710 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10711 // bits of the inputs before performing those operations. The lower
10712 // compare is always unsigned.
10715 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10717 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10718 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10719 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10720 Sign, Zero, Sign, Zero);
10722 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10723 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10725 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10726 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10727 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10729 // Create masks for only the low parts/high parts of the 64 bit integers.
10730 static const int MaskHi[] = { 1, 1, 3, 3 };
10731 static const int MaskLo[] = { 0, 0, 2, 2 };
10732 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10733 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10734 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10736 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10737 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10740 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10742 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10745 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10746 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10747 // pcmpeqd + pshufd + pand.
10748 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10750 // First cast everything to the right type.
10751 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10752 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10755 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10757 // Make sure the lower and upper halves are both all-ones.
10758 static const int Mask[] = { 1, 0, 3, 2 };
10759 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10760 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10763 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10765 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10769 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10770 // bits of the inputs before performing those operations.
10772 EVT EltVT = VT.getVectorElementType();
10773 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10774 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10775 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10778 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10780 // If the logical-not of the result is required, perform that now.
10782 Result = DAG.getNOT(dl, Result, VT);
10785 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10788 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10789 getZeroVector(VT, Subtarget, DAG, dl));
10794 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10796 MVT VT = Op.getSimpleValueType();
10798 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10800 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10801 && "SetCC type must be 8-bit or 1-bit integer");
10802 SDValue Op0 = Op.getOperand(0);
10803 SDValue Op1 = Op.getOperand(1);
10805 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10807 // Optimize to BT if possible.
10808 // Lower (X & (1 << N)) == 0 to BT(X, N).
10809 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10810 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10811 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10812 Op1.getOpcode() == ISD::Constant &&
10813 cast<ConstantSDNode>(Op1)->isNullValue() &&
10814 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10815 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10816 if (NewSetCC.getNode())
10820 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10822 if (Op1.getOpcode() == ISD::Constant &&
10823 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10824 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10825 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10827 // If the input is a setcc, then reuse the input setcc or use a new one with
10828 // the inverted condition.
10829 if (Op0.getOpcode() == X86ISD::SETCC) {
10830 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10831 bool Invert = (CC == ISD::SETNE) ^
10832 cast<ConstantSDNode>(Op1)->isNullValue();
10836 CCode = X86::GetOppositeBranchCondition(CCode);
10837 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10838 DAG.getConstant(CCode, MVT::i8),
10839 Op0.getOperand(1));
10841 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10845 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10846 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10847 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10849 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10850 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10853 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10854 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10855 if (X86CC == X86::COND_INVALID)
10858 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10859 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10860 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10861 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10863 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10867 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10868 static bool isX86LogicalCmp(SDValue Op) {
10869 unsigned Opc = Op.getNode()->getOpcode();
10870 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10871 Opc == X86ISD::SAHF)
10873 if (Op.getResNo() == 1 &&
10874 (Opc == X86ISD::ADD ||
10875 Opc == X86ISD::SUB ||
10876 Opc == X86ISD::ADC ||
10877 Opc == X86ISD::SBB ||
10878 Opc == X86ISD::SMUL ||
10879 Opc == X86ISD::UMUL ||
10880 Opc == X86ISD::INC ||
10881 Opc == X86ISD::DEC ||
10882 Opc == X86ISD::OR ||
10883 Opc == X86ISD::XOR ||
10884 Opc == X86ISD::AND))
10887 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10893 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10894 if (V.getOpcode() != ISD::TRUNCATE)
10897 SDValue VOp0 = V.getOperand(0);
10898 unsigned InBits = VOp0.getValueSizeInBits();
10899 unsigned Bits = V.getValueSizeInBits();
10900 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10903 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10904 bool addTest = true;
10905 SDValue Cond = Op.getOperand(0);
10906 SDValue Op1 = Op.getOperand(1);
10907 SDValue Op2 = Op.getOperand(2);
10909 EVT VT = Op1.getValueType();
10912 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10913 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10914 // sequence later on.
10915 if (Cond.getOpcode() == ISD::SETCC &&
10916 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10917 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10918 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10919 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10920 int SSECC = translateX86FSETCC(
10921 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10924 if (Subtarget->hasAVX512()) {
10925 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10926 DAG.getConstant(SSECC, MVT::i8));
10927 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10929 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10930 DAG.getConstant(SSECC, MVT::i8));
10931 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10932 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10933 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10937 if (Cond.getOpcode() == ISD::SETCC) {
10938 SDValue NewCond = LowerSETCC(Cond, DAG);
10939 if (NewCond.getNode())
10943 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10944 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10945 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10946 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10947 if (Cond.getOpcode() == X86ISD::SETCC &&
10948 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10949 isZero(Cond.getOperand(1).getOperand(1))) {
10950 SDValue Cmp = Cond.getOperand(1);
10952 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10954 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10955 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10956 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10958 SDValue CmpOp0 = Cmp.getOperand(0);
10959 // Apply further optimizations for special cases
10960 // (select (x != 0), -1, 0) -> neg & sbb
10961 // (select (x == 0), 0, -1) -> neg & sbb
10962 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10963 if (YC->isNullValue() &&
10964 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10965 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10966 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10967 DAG.getConstant(0, CmpOp0.getValueType()),
10969 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10970 DAG.getConstant(X86::COND_B, MVT::i8),
10971 SDValue(Neg.getNode(), 1));
10975 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10976 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10977 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10979 SDValue Res = // Res = 0 or -1.
10980 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10981 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10983 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10984 Res = DAG.getNOT(DL, Res, Res.getValueType());
10986 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10987 if (!N2C || !N2C->isNullValue())
10988 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10993 // Look past (and (setcc_carry (cmp ...)), 1).
10994 if (Cond.getOpcode() == ISD::AND &&
10995 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10996 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10997 if (C && C->getAPIntValue() == 1)
10998 Cond = Cond.getOperand(0);
11001 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11002 // setting operand in place of the X86ISD::SETCC.
11003 unsigned CondOpcode = Cond.getOpcode();
11004 if (CondOpcode == X86ISD::SETCC ||
11005 CondOpcode == X86ISD::SETCC_CARRY) {
11006 CC = Cond.getOperand(0);
11008 SDValue Cmp = Cond.getOperand(1);
11009 unsigned Opc = Cmp.getOpcode();
11010 MVT VT = Op.getSimpleValueType();
11012 bool IllegalFPCMov = false;
11013 if (VT.isFloatingPoint() && !VT.isVector() &&
11014 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11015 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11017 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11018 Opc == X86ISD::BT) { // FIXME
11022 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11023 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11024 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11025 Cond.getOperand(0).getValueType() != MVT::i8)) {
11026 SDValue LHS = Cond.getOperand(0);
11027 SDValue RHS = Cond.getOperand(1);
11028 unsigned X86Opcode;
11031 switch (CondOpcode) {
11032 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11033 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11034 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11035 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11036 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11037 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11038 default: llvm_unreachable("unexpected overflowing operator");
11040 if (CondOpcode == ISD::UMULO)
11041 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11044 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11046 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11048 if (CondOpcode == ISD::UMULO)
11049 Cond = X86Op.getValue(2);
11051 Cond = X86Op.getValue(1);
11053 CC = DAG.getConstant(X86Cond, MVT::i8);
11058 // Look pass the truncate if the high bits are known zero.
11059 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11060 Cond = Cond.getOperand(0);
11062 // We know the result of AND is compared against zero. Try to match
11064 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11065 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11066 if (NewSetCC.getNode()) {
11067 CC = NewSetCC.getOperand(0);
11068 Cond = NewSetCC.getOperand(1);
11075 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11076 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11079 // a < b ? -1 : 0 -> RES = ~setcc_carry
11080 // a < b ? 0 : -1 -> RES = setcc_carry
11081 // a >= b ? -1 : 0 -> RES = setcc_carry
11082 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11083 if (Cond.getOpcode() == X86ISD::SUB) {
11084 Cond = ConvertCmpIfNecessary(Cond, DAG);
11085 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11087 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11088 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11089 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11090 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11091 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11092 return DAG.getNOT(DL, Res, Res.getValueType());
11097 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11098 // widen the cmov and push the truncate through. This avoids introducing a new
11099 // branch during isel and doesn't add any extensions.
11100 if (Op.getValueType() == MVT::i8 &&
11101 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11102 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11103 if (T1.getValueType() == T2.getValueType() &&
11104 // Blacklist CopyFromReg to avoid partial register stalls.
11105 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11106 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11107 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11108 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11112 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11113 // condition is true.
11114 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11115 SDValue Ops[] = { Op2, Op1, CC, Cond };
11116 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11119 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11120 MVT VT = Op->getSimpleValueType(0);
11121 SDValue In = Op->getOperand(0);
11122 MVT InVT = In.getSimpleValueType();
11125 unsigned int NumElts = VT.getVectorNumElements();
11126 if (NumElts != 8 && NumElts != 16)
11129 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11130 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11132 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11133 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11135 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11136 Constant *C = ConstantInt::get(*DAG.getContext(),
11137 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11139 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11140 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11141 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11142 MachinePointerInfo::getConstantPool(),
11143 false, false, false, Alignment);
11144 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11145 if (VT.is512BitVector())
11147 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11150 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11151 SelectionDAG &DAG) {
11152 MVT VT = Op->getSimpleValueType(0);
11153 SDValue In = Op->getOperand(0);
11154 MVT InVT = In.getSimpleValueType();
11157 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11158 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11160 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11161 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11162 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11165 if (Subtarget->hasInt256())
11166 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11168 // Optimize vectors in AVX mode
11169 // Sign extend v8i16 to v8i32 and
11172 // Divide input vector into two parts
11173 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11174 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11175 // concat the vectors to original VT
11177 unsigned NumElems = InVT.getVectorNumElements();
11178 SDValue Undef = DAG.getUNDEF(InVT);
11180 SmallVector<int,8> ShufMask1(NumElems, -1);
11181 for (unsigned i = 0; i != NumElems/2; ++i)
11184 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11186 SmallVector<int,8> ShufMask2(NumElems, -1);
11187 for (unsigned i = 0; i != NumElems/2; ++i)
11188 ShufMask2[i] = i + NumElems/2;
11190 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11192 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11193 VT.getVectorNumElements()/2);
11195 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11196 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11198 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11201 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11202 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11203 // from the AND / OR.
11204 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11205 Opc = Op.getOpcode();
11206 if (Opc != ISD::OR && Opc != ISD::AND)
11208 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11209 Op.getOperand(0).hasOneUse() &&
11210 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11211 Op.getOperand(1).hasOneUse());
11214 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11215 // 1 and that the SETCC node has a single use.
11216 static bool isXor1OfSetCC(SDValue Op) {
11217 if (Op.getOpcode() != ISD::XOR)
11219 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11220 if (N1C && N1C->getAPIntValue() == 1) {
11221 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11222 Op.getOperand(0).hasOneUse();
11227 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11228 bool addTest = true;
11229 SDValue Chain = Op.getOperand(0);
11230 SDValue Cond = Op.getOperand(1);
11231 SDValue Dest = Op.getOperand(2);
11234 bool Inverted = false;
11236 if (Cond.getOpcode() == ISD::SETCC) {
11237 // Check for setcc([su]{add,sub,mul}o == 0).
11238 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11239 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11240 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11241 Cond.getOperand(0).getResNo() == 1 &&
11242 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11243 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11244 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11245 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11246 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11247 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11249 Cond = Cond.getOperand(0);
11251 SDValue NewCond = LowerSETCC(Cond, DAG);
11252 if (NewCond.getNode())
11257 // FIXME: LowerXALUO doesn't handle these!!
11258 else if (Cond.getOpcode() == X86ISD::ADD ||
11259 Cond.getOpcode() == X86ISD::SUB ||
11260 Cond.getOpcode() == X86ISD::SMUL ||
11261 Cond.getOpcode() == X86ISD::UMUL)
11262 Cond = LowerXALUO(Cond, DAG);
11265 // Look pass (and (setcc_carry (cmp ...)), 1).
11266 if (Cond.getOpcode() == ISD::AND &&
11267 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11268 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11269 if (C && C->getAPIntValue() == 1)
11270 Cond = Cond.getOperand(0);
11273 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11274 // setting operand in place of the X86ISD::SETCC.
11275 unsigned CondOpcode = Cond.getOpcode();
11276 if (CondOpcode == X86ISD::SETCC ||
11277 CondOpcode == X86ISD::SETCC_CARRY) {
11278 CC = Cond.getOperand(0);
11280 SDValue Cmp = Cond.getOperand(1);
11281 unsigned Opc = Cmp.getOpcode();
11282 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11283 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11287 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11291 // These can only come from an arithmetic instruction with overflow,
11292 // e.g. SADDO, UADDO.
11293 Cond = Cond.getNode()->getOperand(1);
11299 CondOpcode = Cond.getOpcode();
11300 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11301 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11302 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11303 Cond.getOperand(0).getValueType() != MVT::i8)) {
11304 SDValue LHS = Cond.getOperand(0);
11305 SDValue RHS = Cond.getOperand(1);
11306 unsigned X86Opcode;
11309 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11310 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11312 switch (CondOpcode) {
11313 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11315 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11317 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11320 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11321 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11323 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11325 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11328 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11329 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11330 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11331 default: llvm_unreachable("unexpected overflowing operator");
11334 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11335 if (CondOpcode == ISD::UMULO)
11336 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11339 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11341 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11343 if (CondOpcode == ISD::UMULO)
11344 Cond = X86Op.getValue(2);
11346 Cond = X86Op.getValue(1);
11348 CC = DAG.getConstant(X86Cond, MVT::i8);
11352 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11353 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11354 if (CondOpc == ISD::OR) {
11355 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11356 // two branches instead of an explicit OR instruction with a
11358 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11359 isX86LogicalCmp(Cmp)) {
11360 CC = Cond.getOperand(0).getOperand(0);
11361 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11362 Chain, Dest, CC, Cmp);
11363 CC = Cond.getOperand(1).getOperand(0);
11367 } else { // ISD::AND
11368 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11369 // two branches instead of an explicit AND instruction with a
11370 // separate test. However, we only do this if this block doesn't
11371 // have a fall-through edge, because this requires an explicit
11372 // jmp when the condition is false.
11373 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11374 isX86LogicalCmp(Cmp) &&
11375 Op.getNode()->hasOneUse()) {
11376 X86::CondCode CCode =
11377 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11378 CCode = X86::GetOppositeBranchCondition(CCode);
11379 CC = DAG.getConstant(CCode, MVT::i8);
11380 SDNode *User = *Op.getNode()->use_begin();
11381 // Look for an unconditional branch following this conditional branch.
11382 // We need this because we need to reverse the successors in order
11383 // to implement FCMP_OEQ.
11384 if (User->getOpcode() == ISD::BR) {
11385 SDValue FalseBB = User->getOperand(1);
11387 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11388 assert(NewBR == User);
11392 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11393 Chain, Dest, CC, Cmp);
11394 X86::CondCode CCode =
11395 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11396 CCode = X86::GetOppositeBranchCondition(CCode);
11397 CC = DAG.getConstant(CCode, MVT::i8);
11403 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11404 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11405 // It should be transformed during dag combiner except when the condition
11406 // is set by a arithmetics with overflow node.
11407 X86::CondCode CCode =
11408 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11409 CCode = X86::GetOppositeBranchCondition(CCode);
11410 CC = DAG.getConstant(CCode, MVT::i8);
11411 Cond = Cond.getOperand(0).getOperand(1);
11413 } else if (Cond.getOpcode() == ISD::SETCC &&
11414 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11415 // For FCMP_OEQ, we can emit
11416 // two branches instead of an explicit AND instruction with a
11417 // separate test. However, we only do this if this block doesn't
11418 // have a fall-through edge, because this requires an explicit
11419 // jmp when the condition is false.
11420 if (Op.getNode()->hasOneUse()) {
11421 SDNode *User = *Op.getNode()->use_begin();
11422 // Look for an unconditional branch following this conditional branch.
11423 // We need this because we need to reverse the successors in order
11424 // to implement FCMP_OEQ.
11425 if (User->getOpcode() == ISD::BR) {
11426 SDValue FalseBB = User->getOperand(1);
11428 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11429 assert(NewBR == User);
11433 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11434 Cond.getOperand(0), Cond.getOperand(1));
11435 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11436 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11437 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11438 Chain, Dest, CC, Cmp);
11439 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11444 } else if (Cond.getOpcode() == ISD::SETCC &&
11445 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11446 // For FCMP_UNE, we can emit
11447 // two branches instead of an explicit AND instruction with a
11448 // separate test. However, we only do this if this block doesn't
11449 // have a fall-through edge, because this requires an explicit
11450 // jmp when the condition is false.
11451 if (Op.getNode()->hasOneUse()) {
11452 SDNode *User = *Op.getNode()->use_begin();
11453 // Look for an unconditional branch following this conditional branch.
11454 // We need this because we need to reverse the successors in order
11455 // to implement FCMP_UNE.
11456 if (User->getOpcode() == ISD::BR) {
11457 SDValue FalseBB = User->getOperand(1);
11459 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11460 assert(NewBR == User);
11463 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11464 Cond.getOperand(0), Cond.getOperand(1));
11465 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11466 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11467 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11468 Chain, Dest, CC, Cmp);
11469 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11479 // Look pass the truncate if the high bits are known zero.
11480 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11481 Cond = Cond.getOperand(0);
11483 // We know the result of AND is compared against zero. Try to match
11485 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11486 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11487 if (NewSetCC.getNode()) {
11488 CC = NewSetCC.getOperand(0);
11489 Cond = NewSetCC.getOperand(1);
11496 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11497 CC = DAG.getConstant(X86Cond, MVT::i8);
11498 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11500 Cond = ConvertCmpIfNecessary(Cond, DAG);
11501 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11502 Chain, Dest, CC, Cond);
11505 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11506 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11507 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11508 // that the guard pages used by the OS virtual memory manager are allocated in
11509 // correct sequence.
11511 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11512 SelectionDAG &DAG) const {
11513 MachineFunction &MF = DAG.getMachineFunction();
11514 bool SplitStack = MF.shouldSplitStack();
11515 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11520 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11521 SDNode* Node = Op.getNode();
11523 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11524 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11525 " not tell us which reg is the stack pointer!");
11526 EVT VT = Node->getValueType(0);
11527 SDValue Tmp1 = SDValue(Node, 0);
11528 SDValue Tmp2 = SDValue(Node, 1);
11529 SDValue Tmp3 = Node->getOperand(2);
11530 SDValue Chain = Tmp1.getOperand(0);
11532 // Chain the dynamic stack allocation so that it doesn't modify the stack
11533 // pointer when other instructions are using the stack.
11534 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11537 SDValue Size = Tmp2.getOperand(1);
11538 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11539 Chain = SP.getValue(1);
11540 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11541 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11542 unsigned StackAlign = TFI.getStackAlignment();
11543 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11544 if (Align > StackAlign)
11545 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11546 DAG.getConstant(-(uint64_t)Align, VT));
11547 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11549 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11550 DAG.getIntPtrConstant(0, true), SDValue(),
11553 SDValue Ops[2] = { Tmp1, Tmp2 };
11554 return DAG.getMergeValues(Ops, dl);
11558 SDValue Chain = Op.getOperand(0);
11559 SDValue Size = Op.getOperand(1);
11560 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11561 EVT VT = Op.getNode()->getValueType(0);
11563 bool Is64Bit = Subtarget->is64Bit();
11564 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11567 MachineRegisterInfo &MRI = MF.getRegInfo();
11570 // The 64 bit implementation of segmented stacks needs to clobber both r10
11571 // r11. This makes it impossible to use it along with nested parameters.
11572 const Function *F = MF.getFunction();
11574 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11576 if (I->hasNestAttr())
11577 report_fatal_error("Cannot use segmented stacks with functions that "
11578 "have nested arguments.");
11581 const TargetRegisterClass *AddrRegClass =
11582 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11583 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11584 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11585 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11586 DAG.getRegister(Vreg, SPTy));
11587 SDValue Ops1[2] = { Value, Chain };
11588 return DAG.getMergeValues(Ops1, dl);
11591 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11593 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11594 Flag = Chain.getValue(1);
11595 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11597 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11599 const X86RegisterInfo *RegInfo =
11600 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11601 unsigned SPReg = RegInfo->getStackRegister();
11602 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11603 Chain = SP.getValue(1);
11606 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11607 DAG.getConstant(-(uint64_t)Align, VT));
11608 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11611 SDValue Ops1[2] = { SP, Chain };
11612 return DAG.getMergeValues(Ops1, dl);
11616 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11617 MachineFunction &MF = DAG.getMachineFunction();
11618 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11620 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11623 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11624 // vastart just stores the address of the VarArgsFrameIndex slot into the
11625 // memory location argument.
11626 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11628 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11629 MachinePointerInfo(SV), false, false, 0);
11633 // gp_offset (0 - 6 * 8)
11634 // fp_offset (48 - 48 + 8 * 16)
11635 // overflow_arg_area (point to parameters coming in memory).
11637 SmallVector<SDValue, 8> MemOps;
11638 SDValue FIN = Op.getOperand(1);
11640 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11641 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11643 FIN, MachinePointerInfo(SV), false, false, 0);
11644 MemOps.push_back(Store);
11647 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11648 FIN, DAG.getIntPtrConstant(4));
11649 Store = DAG.getStore(Op.getOperand(0), DL,
11650 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11652 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11653 MemOps.push_back(Store);
11655 // Store ptr to overflow_arg_area
11656 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11657 FIN, DAG.getIntPtrConstant(4));
11658 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11660 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11661 MachinePointerInfo(SV, 8),
11663 MemOps.push_back(Store);
11665 // Store ptr to reg_save_area.
11666 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11667 FIN, DAG.getIntPtrConstant(8));
11668 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11670 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11671 MachinePointerInfo(SV, 16), false, false, 0);
11672 MemOps.push_back(Store);
11673 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11676 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11677 assert(Subtarget->is64Bit() &&
11678 "LowerVAARG only handles 64-bit va_arg!");
11679 assert((Subtarget->isTargetLinux() ||
11680 Subtarget->isTargetDarwin()) &&
11681 "Unhandled target in LowerVAARG");
11682 assert(Op.getNode()->getNumOperands() == 4);
11683 SDValue Chain = Op.getOperand(0);
11684 SDValue SrcPtr = Op.getOperand(1);
11685 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11686 unsigned Align = Op.getConstantOperandVal(3);
11689 EVT ArgVT = Op.getNode()->getValueType(0);
11690 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11691 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11694 // Decide which area this value should be read from.
11695 // TODO: Implement the AMD64 ABI in its entirety. This simple
11696 // selection mechanism works only for the basic types.
11697 if (ArgVT == MVT::f80) {
11698 llvm_unreachable("va_arg for f80 not yet implemented");
11699 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11700 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11701 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11702 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11704 llvm_unreachable("Unhandled argument type in LowerVAARG");
11707 if (ArgMode == 2) {
11708 // Sanity Check: Make sure using fp_offset makes sense.
11709 assert(!getTargetMachine().Options.UseSoftFloat &&
11710 !(DAG.getMachineFunction()
11711 .getFunction()->getAttributes()
11712 .hasAttribute(AttributeSet::FunctionIndex,
11713 Attribute::NoImplicitFloat)) &&
11714 Subtarget->hasSSE1());
11717 // Insert VAARG_64 node into the DAG
11718 // VAARG_64 returns two values: Variable Argument Address, Chain
11719 SmallVector<SDValue, 11> InstOps;
11720 InstOps.push_back(Chain);
11721 InstOps.push_back(SrcPtr);
11722 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11723 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11724 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11725 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11726 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11727 VTs, InstOps, MVT::i64,
11728 MachinePointerInfo(SV),
11730 /*Volatile=*/false,
11732 /*WriteMem=*/true);
11733 Chain = VAARG.getValue(1);
11735 // Load the next argument and return it
11736 return DAG.getLoad(ArgVT, dl,
11739 MachinePointerInfo(),
11740 false, false, false, 0);
11743 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11744 SelectionDAG &DAG) {
11745 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11746 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11747 SDValue Chain = Op.getOperand(0);
11748 SDValue DstPtr = Op.getOperand(1);
11749 SDValue SrcPtr = Op.getOperand(2);
11750 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11751 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11754 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11755 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11757 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11760 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11761 // amount is a constant. Takes immediate version of shift as input.
11762 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11763 SDValue SrcOp, uint64_t ShiftAmt,
11764 SelectionDAG &DAG) {
11765 MVT ElementType = VT.getVectorElementType();
11767 // Fold this packed shift into its first operand if ShiftAmt is 0.
11771 // Check for ShiftAmt >= element width
11772 if (ShiftAmt >= ElementType.getSizeInBits()) {
11773 if (Opc == X86ISD::VSRAI)
11774 ShiftAmt = ElementType.getSizeInBits() - 1;
11776 return DAG.getConstant(0, VT);
11779 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11780 && "Unknown target vector shift-by-constant node");
11782 // Fold this packed vector shift into a build vector if SrcOp is a
11783 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11784 if (VT == SrcOp.getSimpleValueType() &&
11785 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11786 SmallVector<SDValue, 8> Elts;
11787 unsigned NumElts = SrcOp->getNumOperands();
11788 ConstantSDNode *ND;
11791 default: llvm_unreachable(nullptr);
11792 case X86ISD::VSHLI:
11793 for (unsigned i=0; i!=NumElts; ++i) {
11794 SDValue CurrentOp = SrcOp->getOperand(i);
11795 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11796 Elts.push_back(CurrentOp);
11799 ND = cast<ConstantSDNode>(CurrentOp);
11800 const APInt &C = ND->getAPIntValue();
11801 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11804 case X86ISD::VSRLI:
11805 for (unsigned i=0; i!=NumElts; ++i) {
11806 SDValue CurrentOp = SrcOp->getOperand(i);
11807 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11808 Elts.push_back(CurrentOp);
11811 ND = cast<ConstantSDNode>(CurrentOp);
11812 const APInt &C = ND->getAPIntValue();
11813 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11816 case X86ISD::VSRAI:
11817 for (unsigned i=0; i!=NumElts; ++i) {
11818 SDValue CurrentOp = SrcOp->getOperand(i);
11819 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11820 Elts.push_back(CurrentOp);
11823 ND = cast<ConstantSDNode>(CurrentOp);
11824 const APInt &C = ND->getAPIntValue();
11825 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11830 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11833 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11836 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11837 // may or may not be a constant. Takes immediate version of shift as input.
11838 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11839 SDValue SrcOp, SDValue ShAmt,
11840 SelectionDAG &DAG) {
11841 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11843 // Catch shift-by-constant.
11844 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11845 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11846 CShAmt->getZExtValue(), DAG);
11848 // Change opcode to non-immediate version
11850 default: llvm_unreachable("Unknown target vector shift node");
11851 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11852 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11853 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11856 // Need to build a vector containing shift amount
11857 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11860 ShOps[1] = DAG.getConstant(0, MVT::i32);
11861 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11862 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11864 // The return type has to be a 128-bit type with the same element
11865 // type as the input type.
11866 MVT EltVT = VT.getVectorElementType();
11867 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11869 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11870 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11873 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11875 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11877 default: return SDValue(); // Don't custom lower most intrinsics.
11878 // Comparison intrinsics.
11879 case Intrinsic::x86_sse_comieq_ss:
11880 case Intrinsic::x86_sse_comilt_ss:
11881 case Intrinsic::x86_sse_comile_ss:
11882 case Intrinsic::x86_sse_comigt_ss:
11883 case Intrinsic::x86_sse_comige_ss:
11884 case Intrinsic::x86_sse_comineq_ss:
11885 case Intrinsic::x86_sse_ucomieq_ss:
11886 case Intrinsic::x86_sse_ucomilt_ss:
11887 case Intrinsic::x86_sse_ucomile_ss:
11888 case Intrinsic::x86_sse_ucomigt_ss:
11889 case Intrinsic::x86_sse_ucomige_ss:
11890 case Intrinsic::x86_sse_ucomineq_ss:
11891 case Intrinsic::x86_sse2_comieq_sd:
11892 case Intrinsic::x86_sse2_comilt_sd:
11893 case Intrinsic::x86_sse2_comile_sd:
11894 case Intrinsic::x86_sse2_comigt_sd:
11895 case Intrinsic::x86_sse2_comige_sd:
11896 case Intrinsic::x86_sse2_comineq_sd:
11897 case Intrinsic::x86_sse2_ucomieq_sd:
11898 case Intrinsic::x86_sse2_ucomilt_sd:
11899 case Intrinsic::x86_sse2_ucomile_sd:
11900 case Intrinsic::x86_sse2_ucomigt_sd:
11901 case Intrinsic::x86_sse2_ucomige_sd:
11902 case Intrinsic::x86_sse2_ucomineq_sd: {
11906 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11907 case Intrinsic::x86_sse_comieq_ss:
11908 case Intrinsic::x86_sse2_comieq_sd:
11909 Opc = X86ISD::COMI;
11912 case Intrinsic::x86_sse_comilt_ss:
11913 case Intrinsic::x86_sse2_comilt_sd:
11914 Opc = X86ISD::COMI;
11917 case Intrinsic::x86_sse_comile_ss:
11918 case Intrinsic::x86_sse2_comile_sd:
11919 Opc = X86ISD::COMI;
11922 case Intrinsic::x86_sse_comigt_ss:
11923 case Intrinsic::x86_sse2_comigt_sd:
11924 Opc = X86ISD::COMI;
11927 case Intrinsic::x86_sse_comige_ss:
11928 case Intrinsic::x86_sse2_comige_sd:
11929 Opc = X86ISD::COMI;
11932 case Intrinsic::x86_sse_comineq_ss:
11933 case Intrinsic::x86_sse2_comineq_sd:
11934 Opc = X86ISD::COMI;
11937 case Intrinsic::x86_sse_ucomieq_ss:
11938 case Intrinsic::x86_sse2_ucomieq_sd:
11939 Opc = X86ISD::UCOMI;
11942 case Intrinsic::x86_sse_ucomilt_ss:
11943 case Intrinsic::x86_sse2_ucomilt_sd:
11944 Opc = X86ISD::UCOMI;
11947 case Intrinsic::x86_sse_ucomile_ss:
11948 case Intrinsic::x86_sse2_ucomile_sd:
11949 Opc = X86ISD::UCOMI;
11952 case Intrinsic::x86_sse_ucomigt_ss:
11953 case Intrinsic::x86_sse2_ucomigt_sd:
11954 Opc = X86ISD::UCOMI;
11957 case Intrinsic::x86_sse_ucomige_ss:
11958 case Intrinsic::x86_sse2_ucomige_sd:
11959 Opc = X86ISD::UCOMI;
11962 case Intrinsic::x86_sse_ucomineq_ss:
11963 case Intrinsic::x86_sse2_ucomineq_sd:
11964 Opc = X86ISD::UCOMI;
11969 SDValue LHS = Op.getOperand(1);
11970 SDValue RHS = Op.getOperand(2);
11971 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11972 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11973 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11974 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11975 DAG.getConstant(X86CC, MVT::i8), Cond);
11976 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11979 // Arithmetic intrinsics.
11980 case Intrinsic::x86_sse2_pmulu_dq:
11981 case Intrinsic::x86_avx2_pmulu_dq:
11982 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11983 Op.getOperand(1), Op.getOperand(2));
11985 case Intrinsic::x86_sse41_pmuldq:
11986 case Intrinsic::x86_avx2_pmul_dq:
11987 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11988 Op.getOperand(1), Op.getOperand(2));
11990 case Intrinsic::x86_sse2_pmulhu_w:
11991 case Intrinsic::x86_avx2_pmulhu_w:
11992 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11993 Op.getOperand(1), Op.getOperand(2));
11995 case Intrinsic::x86_sse2_pmulh_w:
11996 case Intrinsic::x86_avx2_pmulh_w:
11997 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11998 Op.getOperand(1), Op.getOperand(2));
12000 // SSE2/AVX2 sub with unsigned saturation intrinsics
12001 case Intrinsic::x86_sse2_psubus_b:
12002 case Intrinsic::x86_sse2_psubus_w:
12003 case Intrinsic::x86_avx2_psubus_b:
12004 case Intrinsic::x86_avx2_psubus_w:
12005 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12006 Op.getOperand(1), Op.getOperand(2));
12008 // SSE3/AVX horizontal add/sub intrinsics
12009 case Intrinsic::x86_sse3_hadd_ps:
12010 case Intrinsic::x86_sse3_hadd_pd:
12011 case Intrinsic::x86_avx_hadd_ps_256:
12012 case Intrinsic::x86_avx_hadd_pd_256:
12013 case Intrinsic::x86_sse3_hsub_ps:
12014 case Intrinsic::x86_sse3_hsub_pd:
12015 case Intrinsic::x86_avx_hsub_ps_256:
12016 case Intrinsic::x86_avx_hsub_pd_256:
12017 case Intrinsic::x86_ssse3_phadd_w_128:
12018 case Intrinsic::x86_ssse3_phadd_d_128:
12019 case Intrinsic::x86_avx2_phadd_w:
12020 case Intrinsic::x86_avx2_phadd_d:
12021 case Intrinsic::x86_ssse3_phsub_w_128:
12022 case Intrinsic::x86_ssse3_phsub_d_128:
12023 case Intrinsic::x86_avx2_phsub_w:
12024 case Intrinsic::x86_avx2_phsub_d: {
12027 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12028 case Intrinsic::x86_sse3_hadd_ps:
12029 case Intrinsic::x86_sse3_hadd_pd:
12030 case Intrinsic::x86_avx_hadd_ps_256:
12031 case Intrinsic::x86_avx_hadd_pd_256:
12032 Opcode = X86ISD::FHADD;
12034 case Intrinsic::x86_sse3_hsub_ps:
12035 case Intrinsic::x86_sse3_hsub_pd:
12036 case Intrinsic::x86_avx_hsub_ps_256:
12037 case Intrinsic::x86_avx_hsub_pd_256:
12038 Opcode = X86ISD::FHSUB;
12040 case Intrinsic::x86_ssse3_phadd_w_128:
12041 case Intrinsic::x86_ssse3_phadd_d_128:
12042 case Intrinsic::x86_avx2_phadd_w:
12043 case Intrinsic::x86_avx2_phadd_d:
12044 Opcode = X86ISD::HADD;
12046 case Intrinsic::x86_ssse3_phsub_w_128:
12047 case Intrinsic::x86_ssse3_phsub_d_128:
12048 case Intrinsic::x86_avx2_phsub_w:
12049 case Intrinsic::x86_avx2_phsub_d:
12050 Opcode = X86ISD::HSUB;
12053 return DAG.getNode(Opcode, dl, Op.getValueType(),
12054 Op.getOperand(1), Op.getOperand(2));
12057 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12058 case Intrinsic::x86_sse2_pmaxu_b:
12059 case Intrinsic::x86_sse41_pmaxuw:
12060 case Intrinsic::x86_sse41_pmaxud:
12061 case Intrinsic::x86_avx2_pmaxu_b:
12062 case Intrinsic::x86_avx2_pmaxu_w:
12063 case Intrinsic::x86_avx2_pmaxu_d:
12064 case Intrinsic::x86_sse2_pminu_b:
12065 case Intrinsic::x86_sse41_pminuw:
12066 case Intrinsic::x86_sse41_pminud:
12067 case Intrinsic::x86_avx2_pminu_b:
12068 case Intrinsic::x86_avx2_pminu_w:
12069 case Intrinsic::x86_avx2_pminu_d:
12070 case Intrinsic::x86_sse41_pmaxsb:
12071 case Intrinsic::x86_sse2_pmaxs_w:
12072 case Intrinsic::x86_sse41_pmaxsd:
12073 case Intrinsic::x86_avx2_pmaxs_b:
12074 case Intrinsic::x86_avx2_pmaxs_w:
12075 case Intrinsic::x86_avx2_pmaxs_d:
12076 case Intrinsic::x86_sse41_pminsb:
12077 case Intrinsic::x86_sse2_pmins_w:
12078 case Intrinsic::x86_sse41_pminsd:
12079 case Intrinsic::x86_avx2_pmins_b:
12080 case Intrinsic::x86_avx2_pmins_w:
12081 case Intrinsic::x86_avx2_pmins_d: {
12084 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12085 case Intrinsic::x86_sse2_pmaxu_b:
12086 case Intrinsic::x86_sse41_pmaxuw:
12087 case Intrinsic::x86_sse41_pmaxud:
12088 case Intrinsic::x86_avx2_pmaxu_b:
12089 case Intrinsic::x86_avx2_pmaxu_w:
12090 case Intrinsic::x86_avx2_pmaxu_d:
12091 Opcode = X86ISD::UMAX;
12093 case Intrinsic::x86_sse2_pminu_b:
12094 case Intrinsic::x86_sse41_pminuw:
12095 case Intrinsic::x86_sse41_pminud:
12096 case Intrinsic::x86_avx2_pminu_b:
12097 case Intrinsic::x86_avx2_pminu_w:
12098 case Intrinsic::x86_avx2_pminu_d:
12099 Opcode = X86ISD::UMIN;
12101 case Intrinsic::x86_sse41_pmaxsb:
12102 case Intrinsic::x86_sse2_pmaxs_w:
12103 case Intrinsic::x86_sse41_pmaxsd:
12104 case Intrinsic::x86_avx2_pmaxs_b:
12105 case Intrinsic::x86_avx2_pmaxs_w:
12106 case Intrinsic::x86_avx2_pmaxs_d:
12107 Opcode = X86ISD::SMAX;
12109 case Intrinsic::x86_sse41_pminsb:
12110 case Intrinsic::x86_sse2_pmins_w:
12111 case Intrinsic::x86_sse41_pminsd:
12112 case Intrinsic::x86_avx2_pmins_b:
12113 case Intrinsic::x86_avx2_pmins_w:
12114 case Intrinsic::x86_avx2_pmins_d:
12115 Opcode = X86ISD::SMIN;
12118 return DAG.getNode(Opcode, dl, Op.getValueType(),
12119 Op.getOperand(1), Op.getOperand(2));
12122 // SSE/SSE2/AVX floating point max/min intrinsics.
12123 case Intrinsic::x86_sse_max_ps:
12124 case Intrinsic::x86_sse2_max_pd:
12125 case Intrinsic::x86_avx_max_ps_256:
12126 case Intrinsic::x86_avx_max_pd_256:
12127 case Intrinsic::x86_sse_min_ps:
12128 case Intrinsic::x86_sse2_min_pd:
12129 case Intrinsic::x86_avx_min_ps_256:
12130 case Intrinsic::x86_avx_min_pd_256: {
12133 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12134 case Intrinsic::x86_sse_max_ps:
12135 case Intrinsic::x86_sse2_max_pd:
12136 case Intrinsic::x86_avx_max_ps_256:
12137 case Intrinsic::x86_avx_max_pd_256:
12138 Opcode = X86ISD::FMAX;
12140 case Intrinsic::x86_sse_min_ps:
12141 case Intrinsic::x86_sse2_min_pd:
12142 case Intrinsic::x86_avx_min_ps_256:
12143 case Intrinsic::x86_avx_min_pd_256:
12144 Opcode = X86ISD::FMIN;
12147 return DAG.getNode(Opcode, dl, Op.getValueType(),
12148 Op.getOperand(1), Op.getOperand(2));
12151 // AVX2 variable shift intrinsics
12152 case Intrinsic::x86_avx2_psllv_d:
12153 case Intrinsic::x86_avx2_psllv_q:
12154 case Intrinsic::x86_avx2_psllv_d_256:
12155 case Intrinsic::x86_avx2_psllv_q_256:
12156 case Intrinsic::x86_avx2_psrlv_d:
12157 case Intrinsic::x86_avx2_psrlv_q:
12158 case Intrinsic::x86_avx2_psrlv_d_256:
12159 case Intrinsic::x86_avx2_psrlv_q_256:
12160 case Intrinsic::x86_avx2_psrav_d:
12161 case Intrinsic::x86_avx2_psrav_d_256: {
12164 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12165 case Intrinsic::x86_avx2_psllv_d:
12166 case Intrinsic::x86_avx2_psllv_q:
12167 case Intrinsic::x86_avx2_psllv_d_256:
12168 case Intrinsic::x86_avx2_psllv_q_256:
12171 case Intrinsic::x86_avx2_psrlv_d:
12172 case Intrinsic::x86_avx2_psrlv_q:
12173 case Intrinsic::x86_avx2_psrlv_d_256:
12174 case Intrinsic::x86_avx2_psrlv_q_256:
12177 case Intrinsic::x86_avx2_psrav_d:
12178 case Intrinsic::x86_avx2_psrav_d_256:
12182 return DAG.getNode(Opcode, dl, Op.getValueType(),
12183 Op.getOperand(1), Op.getOperand(2));
12186 case Intrinsic::x86_ssse3_pshuf_b_128:
12187 case Intrinsic::x86_avx2_pshuf_b:
12188 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12189 Op.getOperand(1), Op.getOperand(2));
12191 case Intrinsic::x86_ssse3_psign_b_128:
12192 case Intrinsic::x86_ssse3_psign_w_128:
12193 case Intrinsic::x86_ssse3_psign_d_128:
12194 case Intrinsic::x86_avx2_psign_b:
12195 case Intrinsic::x86_avx2_psign_w:
12196 case Intrinsic::x86_avx2_psign_d:
12197 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12198 Op.getOperand(1), Op.getOperand(2));
12200 case Intrinsic::x86_sse41_insertps:
12201 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12202 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12204 case Intrinsic::x86_avx_vperm2f128_ps_256:
12205 case Intrinsic::x86_avx_vperm2f128_pd_256:
12206 case Intrinsic::x86_avx_vperm2f128_si_256:
12207 case Intrinsic::x86_avx2_vperm2i128:
12208 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12209 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12211 case Intrinsic::x86_avx2_permd:
12212 case Intrinsic::x86_avx2_permps:
12213 // Operands intentionally swapped. Mask is last operand to intrinsic,
12214 // but second operand for node/instruction.
12215 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12216 Op.getOperand(2), Op.getOperand(1));
12218 case Intrinsic::x86_sse_sqrt_ps:
12219 case Intrinsic::x86_sse2_sqrt_pd:
12220 case Intrinsic::x86_avx_sqrt_ps_256:
12221 case Intrinsic::x86_avx_sqrt_pd_256:
12222 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12224 // ptest and testp intrinsics. The intrinsic these come from are designed to
12225 // return an integer value, not just an instruction so lower it to the ptest
12226 // or testp pattern and a setcc for the result.
12227 case Intrinsic::x86_sse41_ptestz:
12228 case Intrinsic::x86_sse41_ptestc:
12229 case Intrinsic::x86_sse41_ptestnzc:
12230 case Intrinsic::x86_avx_ptestz_256:
12231 case Intrinsic::x86_avx_ptestc_256:
12232 case Intrinsic::x86_avx_ptestnzc_256:
12233 case Intrinsic::x86_avx_vtestz_ps:
12234 case Intrinsic::x86_avx_vtestc_ps:
12235 case Intrinsic::x86_avx_vtestnzc_ps:
12236 case Intrinsic::x86_avx_vtestz_pd:
12237 case Intrinsic::x86_avx_vtestc_pd:
12238 case Intrinsic::x86_avx_vtestnzc_pd:
12239 case Intrinsic::x86_avx_vtestz_ps_256:
12240 case Intrinsic::x86_avx_vtestc_ps_256:
12241 case Intrinsic::x86_avx_vtestnzc_ps_256:
12242 case Intrinsic::x86_avx_vtestz_pd_256:
12243 case Intrinsic::x86_avx_vtestc_pd_256:
12244 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12245 bool IsTestPacked = false;
12248 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12249 case Intrinsic::x86_avx_vtestz_ps:
12250 case Intrinsic::x86_avx_vtestz_pd:
12251 case Intrinsic::x86_avx_vtestz_ps_256:
12252 case Intrinsic::x86_avx_vtestz_pd_256:
12253 IsTestPacked = true; // Fallthrough
12254 case Intrinsic::x86_sse41_ptestz:
12255 case Intrinsic::x86_avx_ptestz_256:
12257 X86CC = X86::COND_E;
12259 case Intrinsic::x86_avx_vtestc_ps:
12260 case Intrinsic::x86_avx_vtestc_pd:
12261 case Intrinsic::x86_avx_vtestc_ps_256:
12262 case Intrinsic::x86_avx_vtestc_pd_256:
12263 IsTestPacked = true; // Fallthrough
12264 case Intrinsic::x86_sse41_ptestc:
12265 case Intrinsic::x86_avx_ptestc_256:
12267 X86CC = X86::COND_B;
12269 case Intrinsic::x86_avx_vtestnzc_ps:
12270 case Intrinsic::x86_avx_vtestnzc_pd:
12271 case Intrinsic::x86_avx_vtestnzc_ps_256:
12272 case Intrinsic::x86_avx_vtestnzc_pd_256:
12273 IsTestPacked = true; // Fallthrough
12274 case Intrinsic::x86_sse41_ptestnzc:
12275 case Intrinsic::x86_avx_ptestnzc_256:
12277 X86CC = X86::COND_A;
12281 SDValue LHS = Op.getOperand(1);
12282 SDValue RHS = Op.getOperand(2);
12283 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12284 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12285 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12286 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12287 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12289 case Intrinsic::x86_avx512_kortestz_w:
12290 case Intrinsic::x86_avx512_kortestc_w: {
12291 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12292 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12293 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12294 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12295 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12296 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12297 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12300 // SSE/AVX shift intrinsics
12301 case Intrinsic::x86_sse2_psll_w:
12302 case Intrinsic::x86_sse2_psll_d:
12303 case Intrinsic::x86_sse2_psll_q:
12304 case Intrinsic::x86_avx2_psll_w:
12305 case Intrinsic::x86_avx2_psll_d:
12306 case Intrinsic::x86_avx2_psll_q:
12307 case Intrinsic::x86_sse2_psrl_w:
12308 case Intrinsic::x86_sse2_psrl_d:
12309 case Intrinsic::x86_sse2_psrl_q:
12310 case Intrinsic::x86_avx2_psrl_w:
12311 case Intrinsic::x86_avx2_psrl_d:
12312 case Intrinsic::x86_avx2_psrl_q:
12313 case Intrinsic::x86_sse2_psra_w:
12314 case Intrinsic::x86_sse2_psra_d:
12315 case Intrinsic::x86_avx2_psra_w:
12316 case Intrinsic::x86_avx2_psra_d: {
12319 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12320 case Intrinsic::x86_sse2_psll_w:
12321 case Intrinsic::x86_sse2_psll_d:
12322 case Intrinsic::x86_sse2_psll_q:
12323 case Intrinsic::x86_avx2_psll_w:
12324 case Intrinsic::x86_avx2_psll_d:
12325 case Intrinsic::x86_avx2_psll_q:
12326 Opcode = X86ISD::VSHL;
12328 case Intrinsic::x86_sse2_psrl_w:
12329 case Intrinsic::x86_sse2_psrl_d:
12330 case Intrinsic::x86_sse2_psrl_q:
12331 case Intrinsic::x86_avx2_psrl_w:
12332 case Intrinsic::x86_avx2_psrl_d:
12333 case Intrinsic::x86_avx2_psrl_q:
12334 Opcode = X86ISD::VSRL;
12336 case Intrinsic::x86_sse2_psra_w:
12337 case Intrinsic::x86_sse2_psra_d:
12338 case Intrinsic::x86_avx2_psra_w:
12339 case Intrinsic::x86_avx2_psra_d:
12340 Opcode = X86ISD::VSRA;
12343 return DAG.getNode(Opcode, dl, Op.getValueType(),
12344 Op.getOperand(1), Op.getOperand(2));
12347 // SSE/AVX immediate shift intrinsics
12348 case Intrinsic::x86_sse2_pslli_w:
12349 case Intrinsic::x86_sse2_pslli_d:
12350 case Intrinsic::x86_sse2_pslli_q:
12351 case Intrinsic::x86_avx2_pslli_w:
12352 case Intrinsic::x86_avx2_pslli_d:
12353 case Intrinsic::x86_avx2_pslli_q:
12354 case Intrinsic::x86_sse2_psrli_w:
12355 case Intrinsic::x86_sse2_psrli_d:
12356 case Intrinsic::x86_sse2_psrli_q:
12357 case Intrinsic::x86_avx2_psrli_w:
12358 case Intrinsic::x86_avx2_psrli_d:
12359 case Intrinsic::x86_avx2_psrli_q:
12360 case Intrinsic::x86_sse2_psrai_w:
12361 case Intrinsic::x86_sse2_psrai_d:
12362 case Intrinsic::x86_avx2_psrai_w:
12363 case Intrinsic::x86_avx2_psrai_d: {
12366 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12367 case Intrinsic::x86_sse2_pslli_w:
12368 case Intrinsic::x86_sse2_pslli_d:
12369 case Intrinsic::x86_sse2_pslli_q:
12370 case Intrinsic::x86_avx2_pslli_w:
12371 case Intrinsic::x86_avx2_pslli_d:
12372 case Intrinsic::x86_avx2_pslli_q:
12373 Opcode = X86ISD::VSHLI;
12375 case Intrinsic::x86_sse2_psrli_w:
12376 case Intrinsic::x86_sse2_psrli_d:
12377 case Intrinsic::x86_sse2_psrli_q:
12378 case Intrinsic::x86_avx2_psrli_w:
12379 case Intrinsic::x86_avx2_psrli_d:
12380 case Intrinsic::x86_avx2_psrli_q:
12381 Opcode = X86ISD::VSRLI;
12383 case Intrinsic::x86_sse2_psrai_w:
12384 case Intrinsic::x86_sse2_psrai_d:
12385 case Intrinsic::x86_avx2_psrai_w:
12386 case Intrinsic::x86_avx2_psrai_d:
12387 Opcode = X86ISD::VSRAI;
12390 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12391 Op.getOperand(1), Op.getOperand(2), DAG);
12394 case Intrinsic::x86_sse42_pcmpistria128:
12395 case Intrinsic::x86_sse42_pcmpestria128:
12396 case Intrinsic::x86_sse42_pcmpistric128:
12397 case Intrinsic::x86_sse42_pcmpestric128:
12398 case Intrinsic::x86_sse42_pcmpistrio128:
12399 case Intrinsic::x86_sse42_pcmpestrio128:
12400 case Intrinsic::x86_sse42_pcmpistris128:
12401 case Intrinsic::x86_sse42_pcmpestris128:
12402 case Intrinsic::x86_sse42_pcmpistriz128:
12403 case Intrinsic::x86_sse42_pcmpestriz128: {
12407 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12408 case Intrinsic::x86_sse42_pcmpistria128:
12409 Opcode = X86ISD::PCMPISTRI;
12410 X86CC = X86::COND_A;
12412 case Intrinsic::x86_sse42_pcmpestria128:
12413 Opcode = X86ISD::PCMPESTRI;
12414 X86CC = X86::COND_A;
12416 case Intrinsic::x86_sse42_pcmpistric128:
12417 Opcode = X86ISD::PCMPISTRI;
12418 X86CC = X86::COND_B;
12420 case Intrinsic::x86_sse42_pcmpestric128:
12421 Opcode = X86ISD::PCMPESTRI;
12422 X86CC = X86::COND_B;
12424 case Intrinsic::x86_sse42_pcmpistrio128:
12425 Opcode = X86ISD::PCMPISTRI;
12426 X86CC = X86::COND_O;
12428 case Intrinsic::x86_sse42_pcmpestrio128:
12429 Opcode = X86ISD::PCMPESTRI;
12430 X86CC = X86::COND_O;
12432 case Intrinsic::x86_sse42_pcmpistris128:
12433 Opcode = X86ISD::PCMPISTRI;
12434 X86CC = X86::COND_S;
12436 case Intrinsic::x86_sse42_pcmpestris128:
12437 Opcode = X86ISD::PCMPESTRI;
12438 X86CC = X86::COND_S;
12440 case Intrinsic::x86_sse42_pcmpistriz128:
12441 Opcode = X86ISD::PCMPISTRI;
12442 X86CC = X86::COND_E;
12444 case Intrinsic::x86_sse42_pcmpestriz128:
12445 Opcode = X86ISD::PCMPESTRI;
12446 X86CC = X86::COND_E;
12449 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12450 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12451 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12452 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12453 DAG.getConstant(X86CC, MVT::i8),
12454 SDValue(PCMP.getNode(), 1));
12455 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12458 case Intrinsic::x86_sse42_pcmpistri128:
12459 case Intrinsic::x86_sse42_pcmpestri128: {
12461 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12462 Opcode = X86ISD::PCMPISTRI;
12464 Opcode = X86ISD::PCMPESTRI;
12466 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12467 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12468 return DAG.getNode(Opcode, dl, VTs, NewOps);
12470 case Intrinsic::x86_fma_vfmadd_ps:
12471 case Intrinsic::x86_fma_vfmadd_pd:
12472 case Intrinsic::x86_fma_vfmsub_ps:
12473 case Intrinsic::x86_fma_vfmsub_pd:
12474 case Intrinsic::x86_fma_vfnmadd_ps:
12475 case Intrinsic::x86_fma_vfnmadd_pd:
12476 case Intrinsic::x86_fma_vfnmsub_ps:
12477 case Intrinsic::x86_fma_vfnmsub_pd:
12478 case Intrinsic::x86_fma_vfmaddsub_ps:
12479 case Intrinsic::x86_fma_vfmaddsub_pd:
12480 case Intrinsic::x86_fma_vfmsubadd_ps:
12481 case Intrinsic::x86_fma_vfmsubadd_pd:
12482 case Intrinsic::x86_fma_vfmadd_ps_256:
12483 case Intrinsic::x86_fma_vfmadd_pd_256:
12484 case Intrinsic::x86_fma_vfmsub_ps_256:
12485 case Intrinsic::x86_fma_vfmsub_pd_256:
12486 case Intrinsic::x86_fma_vfnmadd_ps_256:
12487 case Intrinsic::x86_fma_vfnmadd_pd_256:
12488 case Intrinsic::x86_fma_vfnmsub_ps_256:
12489 case Intrinsic::x86_fma_vfnmsub_pd_256:
12490 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12491 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12492 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12493 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12494 case Intrinsic::x86_fma_vfmadd_ps_512:
12495 case Intrinsic::x86_fma_vfmadd_pd_512:
12496 case Intrinsic::x86_fma_vfmsub_ps_512:
12497 case Intrinsic::x86_fma_vfmsub_pd_512:
12498 case Intrinsic::x86_fma_vfnmadd_ps_512:
12499 case Intrinsic::x86_fma_vfnmadd_pd_512:
12500 case Intrinsic::x86_fma_vfnmsub_ps_512:
12501 case Intrinsic::x86_fma_vfnmsub_pd_512:
12502 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12503 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12504 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12505 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12508 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12509 case Intrinsic::x86_fma_vfmadd_ps:
12510 case Intrinsic::x86_fma_vfmadd_pd:
12511 case Intrinsic::x86_fma_vfmadd_ps_256:
12512 case Intrinsic::x86_fma_vfmadd_pd_256:
12513 case Intrinsic::x86_fma_vfmadd_ps_512:
12514 case Intrinsic::x86_fma_vfmadd_pd_512:
12515 Opc = X86ISD::FMADD;
12517 case Intrinsic::x86_fma_vfmsub_ps:
12518 case Intrinsic::x86_fma_vfmsub_pd:
12519 case Intrinsic::x86_fma_vfmsub_ps_256:
12520 case Intrinsic::x86_fma_vfmsub_pd_256:
12521 case Intrinsic::x86_fma_vfmsub_ps_512:
12522 case Intrinsic::x86_fma_vfmsub_pd_512:
12523 Opc = X86ISD::FMSUB;
12525 case Intrinsic::x86_fma_vfnmadd_ps:
12526 case Intrinsic::x86_fma_vfnmadd_pd:
12527 case Intrinsic::x86_fma_vfnmadd_ps_256:
12528 case Intrinsic::x86_fma_vfnmadd_pd_256:
12529 case Intrinsic::x86_fma_vfnmadd_ps_512:
12530 case Intrinsic::x86_fma_vfnmadd_pd_512:
12531 Opc = X86ISD::FNMADD;
12533 case Intrinsic::x86_fma_vfnmsub_ps:
12534 case Intrinsic::x86_fma_vfnmsub_pd:
12535 case Intrinsic::x86_fma_vfnmsub_ps_256:
12536 case Intrinsic::x86_fma_vfnmsub_pd_256:
12537 case Intrinsic::x86_fma_vfnmsub_ps_512:
12538 case Intrinsic::x86_fma_vfnmsub_pd_512:
12539 Opc = X86ISD::FNMSUB;
12541 case Intrinsic::x86_fma_vfmaddsub_ps:
12542 case Intrinsic::x86_fma_vfmaddsub_pd:
12543 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12544 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12545 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12546 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12547 Opc = X86ISD::FMADDSUB;
12549 case Intrinsic::x86_fma_vfmsubadd_ps:
12550 case Intrinsic::x86_fma_vfmsubadd_pd:
12551 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12552 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12553 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12554 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12555 Opc = X86ISD::FMSUBADD;
12559 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12560 Op.getOperand(2), Op.getOperand(3));
12565 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12566 SDValue Src, SDValue Mask, SDValue Base,
12567 SDValue Index, SDValue ScaleOp, SDValue Chain,
12568 const X86Subtarget * Subtarget) {
12570 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12571 assert(C && "Invalid scale type");
12572 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12573 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12574 Index.getSimpleValueType().getVectorNumElements());
12576 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12578 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12580 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12581 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12582 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12583 SDValue Segment = DAG.getRegister(0, MVT::i32);
12584 if (Src.getOpcode() == ISD::UNDEF)
12585 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12586 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12587 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12588 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12589 return DAG.getMergeValues(RetOps, dl);
12592 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12593 SDValue Src, SDValue Mask, SDValue Base,
12594 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12596 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12597 assert(C && "Invalid scale type");
12598 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12599 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12600 SDValue Segment = DAG.getRegister(0, MVT::i32);
12601 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12602 Index.getSimpleValueType().getVectorNumElements());
12604 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12606 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12608 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12609 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12610 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12611 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12612 return SDValue(Res, 1);
12615 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12616 SDValue Mask, SDValue Base, SDValue Index,
12617 SDValue ScaleOp, SDValue Chain) {
12619 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12620 assert(C && "Invalid scale type");
12621 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12622 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12623 SDValue Segment = DAG.getRegister(0, MVT::i32);
12625 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12627 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12629 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12631 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12632 //SDVTList VTs = DAG.getVTList(MVT::Other);
12633 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12634 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12635 return SDValue(Res, 0);
12638 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12639 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12640 // also used to custom lower READCYCLECOUNTER nodes.
12641 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12642 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12643 SmallVectorImpl<SDValue> &Results) {
12644 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12645 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12648 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12649 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12650 // and the EAX register is loaded with the low-order 32 bits.
12651 if (Subtarget->is64Bit()) {
12652 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12653 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12656 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12657 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12660 SDValue Chain = HI.getValue(1);
12662 if (Opcode == X86ISD::RDTSCP_DAG) {
12663 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12665 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12666 // the ECX register. Add 'ecx' explicitly to the chain.
12667 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12669 // Explicitly store the content of ECX at the location passed in input
12670 // to the 'rdtscp' intrinsic.
12671 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12672 MachinePointerInfo(), false, false, 0);
12675 if (Subtarget->is64Bit()) {
12676 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12677 // the EAX register is loaded with the low-order 32 bits.
12678 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12679 DAG.getConstant(32, MVT::i8));
12680 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12681 Results.push_back(Chain);
12685 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12686 SDValue Ops[] = { LO, HI };
12687 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12688 Results.push_back(Pair);
12689 Results.push_back(Chain);
12692 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12693 SelectionDAG &DAG) {
12694 SmallVector<SDValue, 2> Results;
12696 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12698 return DAG.getMergeValues(Results, DL);
12701 enum IntrinsicType {
12702 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12705 struct IntrinsicData {
12706 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12707 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12708 IntrinsicType Type;
12713 std::map < unsigned, IntrinsicData> IntrMap;
12714 static void InitIntinsicsMap() {
12715 static bool Initialized = false;
12718 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12719 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12720 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12721 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12722 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12723 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12724 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12725 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12726 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12727 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12728 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
12729 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12730 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
12731 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12732 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
12733 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12734 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
12735 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12737 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12738 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12739 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
12740 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12741 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
12742 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12743 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
12744 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12745 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
12746 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12747 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
12748 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12749 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
12750 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12751 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
12752 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12754 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
12755 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12756 X86::VGATHERPF1QPSm)));
12757 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
12758 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12759 X86::VGATHERPF1QPDm)));
12760 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
12761 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12762 X86::VGATHERPF1DPDm)));
12763 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
12764 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12765 X86::VGATHERPF1DPSm)));
12766 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
12767 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12768 X86::VSCATTERPF1QPSm)));
12769 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
12770 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12771 X86::VSCATTERPF1QPDm)));
12772 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
12773 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12774 X86::VSCATTERPF1DPDm)));
12775 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
12776 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12777 X86::VSCATTERPF1DPSm)));
12778 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12779 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12780 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12781 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12782 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12783 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12784 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12785 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12786 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12787 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12788 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12789 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12790 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12791 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
12792 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12793 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
12794 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12795 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
12796 Initialized = true;
12799 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12800 SelectionDAG &DAG) {
12801 InitIntinsicsMap();
12802 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12803 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12804 if (itr == IntrMap.end())
12808 IntrinsicData Intr = itr->second;
12809 switch(Intr.Type) {
12812 // Emit the node with the right value type.
12813 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12814 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12816 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12817 // Otherwise return the value from Rand, which is always 0, casted to i32.
12818 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12819 DAG.getConstant(1, Op->getValueType(1)),
12820 DAG.getConstant(X86::COND_B, MVT::i32),
12821 SDValue(Result.getNode(), 1) };
12822 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12823 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12826 // Return { result, isValid, chain }.
12827 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12828 SDValue(Result.getNode(), 2));
12831 //gather(v1, mask, index, base, scale);
12832 SDValue Chain = Op.getOperand(0);
12833 SDValue Src = Op.getOperand(2);
12834 SDValue Base = Op.getOperand(3);
12835 SDValue Index = Op.getOperand(4);
12836 SDValue Mask = Op.getOperand(5);
12837 SDValue Scale = Op.getOperand(6);
12838 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12842 //scatter(base, mask, index, v1, scale);
12843 SDValue Chain = Op.getOperand(0);
12844 SDValue Base = Op.getOperand(2);
12845 SDValue Mask = Op.getOperand(3);
12846 SDValue Index = Op.getOperand(4);
12847 SDValue Src = Op.getOperand(5);
12848 SDValue Scale = Op.getOperand(6);
12849 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12852 SDValue Hint = Op.getOperand(6);
12854 if (dyn_cast<ConstantSDNode> (Hint) == 0 ||
12855 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12856 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12857 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12858 SDValue Chain = Op.getOperand(0);
12859 SDValue Mask = Op.getOperand(2);
12860 SDValue Index = Op.getOperand(3);
12861 SDValue Base = Op.getOperand(4);
12862 SDValue Scale = Op.getOperand(5);
12863 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12865 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12867 SmallVector<SDValue, 2> Results;
12868 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12869 return DAG.getMergeValues(Results, dl);
12871 // XTEST intrinsics.
12873 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12874 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12875 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12876 DAG.getConstant(X86::COND_NE, MVT::i8),
12878 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12879 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12880 Ret, SDValue(InTrans.getNode(), 1));
12883 llvm_unreachable("Unknown Intrinsic Type");
12886 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12887 SelectionDAG &DAG) const {
12888 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12889 MFI->setReturnAddressIsTaken(true);
12891 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12894 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12896 EVT PtrVT = getPointerTy();
12899 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12900 const X86RegisterInfo *RegInfo =
12901 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12902 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12903 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12904 DAG.getNode(ISD::ADD, dl, PtrVT,
12905 FrameAddr, Offset),
12906 MachinePointerInfo(), false, false, false, 0);
12909 // Just load the return address.
12910 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12911 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12912 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12915 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12916 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12917 MFI->setFrameAddressIsTaken(true);
12919 EVT VT = Op.getValueType();
12920 SDLoc dl(Op); // FIXME probably not meaningful
12921 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12922 const X86RegisterInfo *RegInfo =
12923 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12924 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12925 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12926 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12927 "Invalid Frame Register!");
12928 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12930 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12931 MachinePointerInfo(),
12932 false, false, false, 0);
12936 // FIXME? Maybe this could be a TableGen attribute on some registers and
12937 // this table could be generated automatically from RegInfo.
12938 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12940 unsigned Reg = StringSwitch<unsigned>(RegName)
12941 .Case("esp", X86::ESP)
12942 .Case("rsp", X86::RSP)
12946 report_fatal_error("Invalid register name global variable");
12949 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12950 SelectionDAG &DAG) const {
12951 const X86RegisterInfo *RegInfo =
12952 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12953 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12956 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12957 SDValue Chain = Op.getOperand(0);
12958 SDValue Offset = Op.getOperand(1);
12959 SDValue Handler = Op.getOperand(2);
12962 EVT PtrVT = getPointerTy();
12963 const X86RegisterInfo *RegInfo =
12964 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12965 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12966 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12967 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12968 "Invalid Frame Register!");
12969 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12970 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12972 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12973 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12974 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12975 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12977 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12979 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12980 DAG.getRegister(StoreAddrReg, PtrVT));
12983 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12984 SelectionDAG &DAG) const {
12986 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12987 DAG.getVTList(MVT::i32, MVT::Other),
12988 Op.getOperand(0), Op.getOperand(1));
12991 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12992 SelectionDAG &DAG) const {
12994 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12995 Op.getOperand(0), Op.getOperand(1));
12998 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12999 return Op.getOperand(0);
13002 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13003 SelectionDAG &DAG) const {
13004 SDValue Root = Op.getOperand(0);
13005 SDValue Trmp = Op.getOperand(1); // trampoline
13006 SDValue FPtr = Op.getOperand(2); // nested function
13007 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13010 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13011 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13013 if (Subtarget->is64Bit()) {
13014 SDValue OutChains[6];
13016 // Large code-model.
13017 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13018 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13020 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13021 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13023 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13025 // Load the pointer to the nested function into R11.
13026 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13027 SDValue Addr = Trmp;
13028 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13029 Addr, MachinePointerInfo(TrmpAddr),
13032 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13033 DAG.getConstant(2, MVT::i64));
13034 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13035 MachinePointerInfo(TrmpAddr, 2),
13038 // Load the 'nest' parameter value into R10.
13039 // R10 is specified in X86CallingConv.td
13040 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13041 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13042 DAG.getConstant(10, MVT::i64));
13043 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13044 Addr, MachinePointerInfo(TrmpAddr, 10),
13047 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13048 DAG.getConstant(12, MVT::i64));
13049 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13050 MachinePointerInfo(TrmpAddr, 12),
13053 // Jump to the nested function.
13054 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13055 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13056 DAG.getConstant(20, MVT::i64));
13057 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13058 Addr, MachinePointerInfo(TrmpAddr, 20),
13061 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13062 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13063 DAG.getConstant(22, MVT::i64));
13064 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13065 MachinePointerInfo(TrmpAddr, 22),
13068 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13070 const Function *Func =
13071 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13072 CallingConv::ID CC = Func->getCallingConv();
13077 llvm_unreachable("Unsupported calling convention");
13078 case CallingConv::C:
13079 case CallingConv::X86_StdCall: {
13080 // Pass 'nest' parameter in ECX.
13081 // Must be kept in sync with X86CallingConv.td
13082 NestReg = X86::ECX;
13084 // Check that ECX wasn't needed by an 'inreg' parameter.
13085 FunctionType *FTy = Func->getFunctionType();
13086 const AttributeSet &Attrs = Func->getAttributes();
13088 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13089 unsigned InRegCount = 0;
13092 for (FunctionType::param_iterator I = FTy->param_begin(),
13093 E = FTy->param_end(); I != E; ++I, ++Idx)
13094 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13095 // FIXME: should only count parameters that are lowered to integers.
13096 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13098 if (InRegCount > 2) {
13099 report_fatal_error("Nest register in use - reduce number of inreg"
13105 case CallingConv::X86_FastCall:
13106 case CallingConv::X86_ThisCall:
13107 case CallingConv::Fast:
13108 // Pass 'nest' parameter in EAX.
13109 // Must be kept in sync with X86CallingConv.td
13110 NestReg = X86::EAX;
13114 SDValue OutChains[4];
13115 SDValue Addr, Disp;
13117 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13118 DAG.getConstant(10, MVT::i32));
13119 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13121 // This is storing the opcode for MOV32ri.
13122 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13123 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13124 OutChains[0] = DAG.getStore(Root, dl,
13125 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13126 Trmp, MachinePointerInfo(TrmpAddr),
13129 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13130 DAG.getConstant(1, MVT::i32));
13131 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13132 MachinePointerInfo(TrmpAddr, 1),
13135 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13136 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13137 DAG.getConstant(5, MVT::i32));
13138 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13139 MachinePointerInfo(TrmpAddr, 5),
13142 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13143 DAG.getConstant(6, MVT::i32));
13144 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13145 MachinePointerInfo(TrmpAddr, 6),
13148 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13152 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13153 SelectionDAG &DAG) const {
13155 The rounding mode is in bits 11:10 of FPSR, and has the following
13157 00 Round to nearest
13162 FLT_ROUNDS, on the other hand, expects the following:
13169 To perform the conversion, we do:
13170 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13173 MachineFunction &MF = DAG.getMachineFunction();
13174 const TargetMachine &TM = MF.getTarget();
13175 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13176 unsigned StackAlignment = TFI.getStackAlignment();
13177 MVT VT = Op.getSimpleValueType();
13180 // Save FP Control Word to stack slot
13181 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13182 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13184 MachineMemOperand *MMO =
13185 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13186 MachineMemOperand::MOStore, 2, 2);
13188 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13189 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13190 DAG.getVTList(MVT::Other),
13191 Ops, MVT::i16, MMO);
13193 // Load FP Control Word from stack slot
13194 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13195 MachinePointerInfo(), false, false, false, 0);
13197 // Transform as necessary
13199 DAG.getNode(ISD::SRL, DL, MVT::i16,
13200 DAG.getNode(ISD::AND, DL, MVT::i16,
13201 CWD, DAG.getConstant(0x800, MVT::i16)),
13202 DAG.getConstant(11, MVT::i8));
13204 DAG.getNode(ISD::SRL, DL, MVT::i16,
13205 DAG.getNode(ISD::AND, DL, MVT::i16,
13206 CWD, DAG.getConstant(0x400, MVT::i16)),
13207 DAG.getConstant(9, MVT::i8));
13210 DAG.getNode(ISD::AND, DL, MVT::i16,
13211 DAG.getNode(ISD::ADD, DL, MVT::i16,
13212 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13213 DAG.getConstant(1, MVT::i16)),
13214 DAG.getConstant(3, MVT::i16));
13216 return DAG.getNode((VT.getSizeInBits() < 16 ?
13217 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13220 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13221 MVT VT = Op.getSimpleValueType();
13223 unsigned NumBits = VT.getSizeInBits();
13226 Op = Op.getOperand(0);
13227 if (VT == MVT::i8) {
13228 // Zero extend to i32 since there is not an i8 bsr.
13230 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13233 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13234 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13235 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13237 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13240 DAG.getConstant(NumBits+NumBits-1, OpVT),
13241 DAG.getConstant(X86::COND_E, MVT::i8),
13244 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13246 // Finally xor with NumBits-1.
13247 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13250 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13254 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13255 MVT VT = Op.getSimpleValueType();
13257 unsigned NumBits = VT.getSizeInBits();
13260 Op = Op.getOperand(0);
13261 if (VT == MVT::i8) {
13262 // Zero extend to i32 since there is not an i8 bsr.
13264 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13267 // Issue a bsr (scan bits in reverse).
13268 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13269 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13271 // And xor with NumBits-1.
13272 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13275 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13279 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13280 MVT VT = Op.getSimpleValueType();
13281 unsigned NumBits = VT.getSizeInBits();
13283 Op = Op.getOperand(0);
13285 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13286 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13287 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13289 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13292 DAG.getConstant(NumBits, VT),
13293 DAG.getConstant(X86::COND_E, MVT::i8),
13296 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13299 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13300 // ones, and then concatenate the result back.
13301 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13302 MVT VT = Op.getSimpleValueType();
13304 assert(VT.is256BitVector() && VT.isInteger() &&
13305 "Unsupported value type for operation");
13307 unsigned NumElems = VT.getVectorNumElements();
13310 // Extract the LHS vectors
13311 SDValue LHS = Op.getOperand(0);
13312 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13313 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13315 // Extract the RHS vectors
13316 SDValue RHS = Op.getOperand(1);
13317 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13318 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13320 MVT EltVT = VT.getVectorElementType();
13321 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13323 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13324 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13325 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13328 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13329 assert(Op.getSimpleValueType().is256BitVector() &&
13330 Op.getSimpleValueType().isInteger() &&
13331 "Only handle AVX 256-bit vector integer operation");
13332 return Lower256IntArith(Op, DAG);
13335 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13336 assert(Op.getSimpleValueType().is256BitVector() &&
13337 Op.getSimpleValueType().isInteger() &&
13338 "Only handle AVX 256-bit vector integer operation");
13339 return Lower256IntArith(Op, DAG);
13342 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13343 SelectionDAG &DAG) {
13345 MVT VT = Op.getSimpleValueType();
13347 // Decompose 256-bit ops into smaller 128-bit ops.
13348 if (VT.is256BitVector() && !Subtarget->hasInt256())
13349 return Lower256IntArith(Op, DAG);
13351 SDValue A = Op.getOperand(0);
13352 SDValue B = Op.getOperand(1);
13354 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13355 if (VT == MVT::v4i32) {
13356 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13357 "Should not custom lower when pmuldq is available!");
13359 // Extract the odd parts.
13360 static const int UnpackMask[] = { 1, -1, 3, -1 };
13361 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13362 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13364 // Multiply the even parts.
13365 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13366 // Now multiply odd parts.
13367 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13369 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13370 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13372 // Merge the two vectors back together with a shuffle. This expands into 2
13374 static const int ShufMask[] = { 0, 4, 2, 6 };
13375 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13378 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13379 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13381 // Ahi = psrlqi(a, 32);
13382 // Bhi = psrlqi(b, 32);
13384 // AloBlo = pmuludq(a, b);
13385 // AloBhi = pmuludq(a, Bhi);
13386 // AhiBlo = pmuludq(Ahi, b);
13388 // AloBhi = psllqi(AloBhi, 32);
13389 // AhiBlo = psllqi(AhiBlo, 32);
13390 // return AloBlo + AloBhi + AhiBlo;
13392 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13393 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13395 // Bit cast to 32-bit vectors for MULUDQ
13396 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13397 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13398 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13399 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13400 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13401 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13403 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13404 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13405 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13407 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13408 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13410 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13411 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13414 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13415 assert(Subtarget->isTargetWin64() && "Unexpected target");
13416 EVT VT = Op.getValueType();
13417 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13418 "Unexpected return type for lowering");
13422 switch (Op->getOpcode()) {
13423 default: llvm_unreachable("Unexpected request for libcall!");
13424 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13425 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13426 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13427 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13428 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13429 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13433 SDValue InChain = DAG.getEntryNode();
13435 TargetLowering::ArgListTy Args;
13436 TargetLowering::ArgListEntry Entry;
13437 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13438 EVT ArgVT = Op->getOperand(i).getValueType();
13439 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13440 "Unexpected argument type for lowering");
13441 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13442 Entry.Node = StackPtr;
13443 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13445 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13446 Entry.Ty = PointerType::get(ArgTy,0);
13447 Entry.isSExt = false;
13448 Entry.isZExt = false;
13449 Args.push_back(Entry);
13452 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13455 TargetLowering::CallLoweringInfo CLI(DAG);
13456 CLI.setDebugLoc(dl).setChain(InChain)
13457 .setCallee(getLibcallCallingConv(LC),
13458 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13460 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13462 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13463 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13466 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13467 SelectionDAG &DAG) {
13468 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13469 EVT VT = Op0.getValueType();
13472 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13473 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13475 // Get the high parts.
13476 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13477 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13478 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13480 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13482 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13483 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13485 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13486 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13487 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13488 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13489 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13491 // Shuffle it back into the right order.
13492 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13493 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13494 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13495 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13497 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13498 // unsigned multiply.
13499 if (IsSigned && !Subtarget->hasSSE41()) {
13501 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13502 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13503 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13504 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13505 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13507 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13508 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13511 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13514 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13515 const X86Subtarget *Subtarget) {
13516 MVT VT = Op.getSimpleValueType();
13518 SDValue R = Op.getOperand(0);
13519 SDValue Amt = Op.getOperand(1);
13521 // Optimize shl/srl/sra with constant shift amount.
13522 if (isSplatVector(Amt.getNode())) {
13523 SDValue SclrAmt = Amt->getOperand(0);
13524 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13525 uint64_t ShiftAmt = C->getZExtValue();
13527 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13528 (Subtarget->hasInt256() &&
13529 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13530 (Subtarget->hasAVX512() &&
13531 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13532 if (Op.getOpcode() == ISD::SHL)
13533 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13535 if (Op.getOpcode() == ISD::SRL)
13536 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13538 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13539 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13543 if (VT == MVT::v16i8) {
13544 if (Op.getOpcode() == ISD::SHL) {
13545 // Make a large shift.
13546 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13547 MVT::v8i16, R, ShiftAmt,
13549 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13550 // Zero out the rightmost bits.
13551 SmallVector<SDValue, 16> V(16,
13552 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13554 return DAG.getNode(ISD::AND, dl, VT, SHL,
13555 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13557 if (Op.getOpcode() == ISD::SRL) {
13558 // Make a large shift.
13559 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13560 MVT::v8i16, R, ShiftAmt,
13562 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13563 // Zero out the leftmost bits.
13564 SmallVector<SDValue, 16> V(16,
13565 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13567 return DAG.getNode(ISD::AND, dl, VT, SRL,
13568 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13570 if (Op.getOpcode() == ISD::SRA) {
13571 if (ShiftAmt == 7) {
13572 // R s>> 7 === R s< 0
13573 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13574 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13577 // R s>> a === ((R u>> a) ^ m) - m
13578 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13579 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13581 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13582 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13583 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13586 llvm_unreachable("Unknown shift opcode.");
13589 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13590 if (Op.getOpcode() == ISD::SHL) {
13591 // Make a large shift.
13592 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13593 MVT::v16i16, R, ShiftAmt,
13595 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13596 // Zero out the rightmost bits.
13597 SmallVector<SDValue, 32> V(32,
13598 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13600 return DAG.getNode(ISD::AND, dl, VT, SHL,
13601 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13603 if (Op.getOpcode() == ISD::SRL) {
13604 // Make a large shift.
13605 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13606 MVT::v16i16, R, ShiftAmt,
13608 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13609 // Zero out the leftmost bits.
13610 SmallVector<SDValue, 32> V(32,
13611 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13613 return DAG.getNode(ISD::AND, dl, VT, SRL,
13614 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13616 if (Op.getOpcode() == ISD::SRA) {
13617 if (ShiftAmt == 7) {
13618 // R s>> 7 === R s< 0
13619 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13620 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13623 // R s>> a === ((R u>> a) ^ m) - m
13624 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13625 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13627 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13628 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13629 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13632 llvm_unreachable("Unknown shift opcode.");
13637 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13638 if (!Subtarget->is64Bit() &&
13639 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13640 Amt.getOpcode() == ISD::BITCAST &&
13641 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13642 Amt = Amt.getOperand(0);
13643 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13644 VT.getVectorNumElements();
13645 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13646 uint64_t ShiftAmt = 0;
13647 for (unsigned i = 0; i != Ratio; ++i) {
13648 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13652 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13654 // Check remaining shift amounts.
13655 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13656 uint64_t ShAmt = 0;
13657 for (unsigned j = 0; j != Ratio; ++j) {
13658 ConstantSDNode *C =
13659 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13663 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13665 if (ShAmt != ShiftAmt)
13668 switch (Op.getOpcode()) {
13670 llvm_unreachable("Unknown shift opcode!");
13672 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13675 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13678 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13686 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13687 const X86Subtarget* Subtarget) {
13688 MVT VT = Op.getSimpleValueType();
13690 SDValue R = Op.getOperand(0);
13691 SDValue Amt = Op.getOperand(1);
13693 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13694 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13695 (Subtarget->hasInt256() &&
13696 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13697 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13698 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13700 EVT EltVT = VT.getVectorElementType();
13702 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13703 unsigned NumElts = VT.getVectorNumElements();
13705 for (i = 0; i != NumElts; ++i) {
13706 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13710 for (j = i; j != NumElts; ++j) {
13711 SDValue Arg = Amt.getOperand(j);
13712 if (Arg.getOpcode() == ISD::UNDEF) continue;
13713 if (Arg != Amt.getOperand(i))
13716 if (i != NumElts && j == NumElts)
13717 BaseShAmt = Amt.getOperand(i);
13719 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13720 Amt = Amt.getOperand(0);
13721 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13722 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13723 SDValue InVec = Amt.getOperand(0);
13724 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13725 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13727 for (; i != NumElts; ++i) {
13728 SDValue Arg = InVec.getOperand(i);
13729 if (Arg.getOpcode() == ISD::UNDEF) continue;
13733 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13734 if (ConstantSDNode *C =
13735 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13736 unsigned SplatIdx =
13737 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13738 if (C->getZExtValue() == SplatIdx)
13739 BaseShAmt = InVec.getOperand(1);
13742 if (!BaseShAmt.getNode())
13743 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13744 DAG.getIntPtrConstant(0));
13748 if (BaseShAmt.getNode()) {
13749 if (EltVT.bitsGT(MVT::i32))
13750 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13751 else if (EltVT.bitsLT(MVT::i32))
13752 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13754 switch (Op.getOpcode()) {
13756 llvm_unreachable("Unknown shift opcode!");
13758 switch (VT.SimpleTy) {
13759 default: return SDValue();
13768 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13771 switch (VT.SimpleTy) {
13772 default: return SDValue();
13779 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13782 switch (VT.SimpleTy) {
13783 default: return SDValue();
13792 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13798 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13799 if (!Subtarget->is64Bit() &&
13800 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13801 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13802 Amt.getOpcode() == ISD::BITCAST &&
13803 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13804 Amt = Amt.getOperand(0);
13805 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13806 VT.getVectorNumElements();
13807 std::vector<SDValue> Vals(Ratio);
13808 for (unsigned i = 0; i != Ratio; ++i)
13809 Vals[i] = Amt.getOperand(i);
13810 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13811 for (unsigned j = 0; j != Ratio; ++j)
13812 if (Vals[j] != Amt.getOperand(i + j))
13815 switch (Op.getOpcode()) {
13817 llvm_unreachable("Unknown shift opcode!");
13819 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13821 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13823 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13830 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13831 SelectionDAG &DAG) {
13833 MVT VT = Op.getSimpleValueType();
13835 SDValue R = Op.getOperand(0);
13836 SDValue Amt = Op.getOperand(1);
13839 if (!Subtarget->hasSSE2())
13842 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13846 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13850 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13852 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13853 if (Subtarget->hasInt256()) {
13854 if (Op.getOpcode() == ISD::SRL &&
13855 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13856 VT == MVT::v4i64 || VT == MVT::v8i32))
13858 if (Op.getOpcode() == ISD::SHL &&
13859 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13860 VT == MVT::v4i64 || VT == MVT::v8i32))
13862 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13866 // If possible, lower this packed shift into a vector multiply instead of
13867 // expanding it into a sequence of scalar shifts.
13868 // Do this only if the vector shift count is a constant build_vector.
13869 if (Op.getOpcode() == ISD::SHL &&
13870 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13871 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13872 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13873 SmallVector<SDValue, 8> Elts;
13874 EVT SVT = VT.getScalarType();
13875 unsigned SVTBits = SVT.getSizeInBits();
13876 const APInt &One = APInt(SVTBits, 1);
13877 unsigned NumElems = VT.getVectorNumElements();
13879 for (unsigned i=0; i !=NumElems; ++i) {
13880 SDValue Op = Amt->getOperand(i);
13881 if (Op->getOpcode() == ISD::UNDEF) {
13882 Elts.push_back(Op);
13886 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13887 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13888 uint64_t ShAmt = C.getZExtValue();
13889 if (ShAmt >= SVTBits) {
13890 Elts.push_back(DAG.getUNDEF(SVT));
13893 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13895 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13896 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13899 // Lower SHL with variable shift amount.
13900 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13901 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13903 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13904 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13905 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13906 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13909 // If possible, lower this shift as a sequence of two shifts by
13910 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13912 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13914 // Could be rewritten as:
13915 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13917 // The advantage is that the two shifts from the example would be
13918 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13919 // the vector shift into four scalar shifts plus four pairs of vector
13921 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13922 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13923 unsigned TargetOpcode = X86ISD::MOVSS;
13924 bool CanBeSimplified;
13925 // The splat value for the first packed shift (the 'X' from the example).
13926 SDValue Amt1 = Amt->getOperand(0);
13927 // The splat value for the second packed shift (the 'Y' from the example).
13928 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13929 Amt->getOperand(2);
13931 // See if it is possible to replace this node with a sequence of
13932 // two shifts followed by a MOVSS/MOVSD
13933 if (VT == MVT::v4i32) {
13934 // Check if it is legal to use a MOVSS.
13935 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13936 Amt2 == Amt->getOperand(3);
13937 if (!CanBeSimplified) {
13938 // Otherwise, check if we can still simplify this node using a MOVSD.
13939 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13940 Amt->getOperand(2) == Amt->getOperand(3);
13941 TargetOpcode = X86ISD::MOVSD;
13942 Amt2 = Amt->getOperand(2);
13945 // Do similar checks for the case where the machine value type
13947 CanBeSimplified = Amt1 == Amt->getOperand(1);
13948 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13949 CanBeSimplified = Amt2 == Amt->getOperand(i);
13951 if (!CanBeSimplified) {
13952 TargetOpcode = X86ISD::MOVSD;
13953 CanBeSimplified = true;
13954 Amt2 = Amt->getOperand(4);
13955 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13956 CanBeSimplified = Amt1 == Amt->getOperand(i);
13957 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13958 CanBeSimplified = Amt2 == Amt->getOperand(j);
13962 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13963 isa<ConstantSDNode>(Amt2)) {
13964 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13965 EVT CastVT = MVT::v4i32;
13967 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13968 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13970 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13971 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13972 if (TargetOpcode == X86ISD::MOVSD)
13973 CastVT = MVT::v2i64;
13974 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13975 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13976 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13978 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13982 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13983 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13986 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13987 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13989 // Turn 'a' into a mask suitable for VSELECT
13990 SDValue VSelM = DAG.getConstant(0x80, VT);
13991 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13992 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13994 SDValue CM1 = DAG.getConstant(0x0f, VT);
13995 SDValue CM2 = DAG.getConstant(0x3f, VT);
13997 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13998 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13999 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14000 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14001 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14004 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14005 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14006 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14008 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14009 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14010 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14011 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14012 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14015 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14016 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14017 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14019 // return VSELECT(r, r+r, a);
14020 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14021 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14025 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14026 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14027 // solution better.
14028 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14029 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14031 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14032 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14033 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14034 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14035 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14038 // Decompose 256-bit shifts into smaller 128-bit shifts.
14039 if (VT.is256BitVector()) {
14040 unsigned NumElems = VT.getVectorNumElements();
14041 MVT EltVT = VT.getVectorElementType();
14042 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14044 // Extract the two vectors
14045 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14046 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14048 // Recreate the shift amount vectors
14049 SDValue Amt1, Amt2;
14050 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14051 // Constant shift amount
14052 SmallVector<SDValue, 4> Amt1Csts;
14053 SmallVector<SDValue, 4> Amt2Csts;
14054 for (unsigned i = 0; i != NumElems/2; ++i)
14055 Amt1Csts.push_back(Amt->getOperand(i));
14056 for (unsigned i = NumElems/2; i != NumElems; ++i)
14057 Amt2Csts.push_back(Amt->getOperand(i));
14059 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14060 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14062 // Variable shift amount
14063 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14064 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14067 // Issue new vector shifts for the smaller types
14068 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14069 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14071 // Concatenate the result back
14072 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14078 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14079 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14080 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14081 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14082 // has only one use.
14083 SDNode *N = Op.getNode();
14084 SDValue LHS = N->getOperand(0);
14085 SDValue RHS = N->getOperand(1);
14086 unsigned BaseOp = 0;
14089 switch (Op.getOpcode()) {
14090 default: llvm_unreachable("Unknown ovf instruction!");
14092 // A subtract of one will be selected as a INC. Note that INC doesn't
14093 // set CF, so we can't do this for UADDO.
14094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14096 BaseOp = X86ISD::INC;
14097 Cond = X86::COND_O;
14100 BaseOp = X86ISD::ADD;
14101 Cond = X86::COND_O;
14104 BaseOp = X86ISD::ADD;
14105 Cond = X86::COND_B;
14108 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14109 // set CF, so we can't do this for USUBO.
14110 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14112 BaseOp = X86ISD::DEC;
14113 Cond = X86::COND_O;
14116 BaseOp = X86ISD::SUB;
14117 Cond = X86::COND_O;
14120 BaseOp = X86ISD::SUB;
14121 Cond = X86::COND_B;
14124 BaseOp = X86ISD::SMUL;
14125 Cond = X86::COND_O;
14127 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14128 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14130 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14133 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14134 DAG.getConstant(X86::COND_O, MVT::i32),
14135 SDValue(Sum.getNode(), 2));
14137 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14141 // Also sets EFLAGS.
14142 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14143 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14146 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14147 DAG.getConstant(Cond, MVT::i32),
14148 SDValue(Sum.getNode(), 1));
14150 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14153 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14154 SelectionDAG &DAG) const {
14156 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14157 MVT VT = Op.getSimpleValueType();
14159 if (!Subtarget->hasSSE2() || !VT.isVector())
14162 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14163 ExtraVT.getScalarType().getSizeInBits();
14165 switch (VT.SimpleTy) {
14166 default: return SDValue();
14169 if (!Subtarget->hasFp256())
14171 if (!Subtarget->hasInt256()) {
14172 // needs to be split
14173 unsigned NumElems = VT.getVectorNumElements();
14175 // Extract the LHS vectors
14176 SDValue LHS = Op.getOperand(0);
14177 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14178 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14180 MVT EltVT = VT.getVectorElementType();
14181 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14183 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14184 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14185 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14187 SDValue Extra = DAG.getValueType(ExtraVT);
14189 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14190 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14192 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14197 SDValue Op0 = Op.getOperand(0);
14198 SDValue Op00 = Op0.getOperand(0);
14200 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14201 if (Op0.getOpcode() == ISD::BITCAST &&
14202 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14203 // (sext (vzext x)) -> (vsext x)
14204 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14205 if (Tmp1.getNode()) {
14206 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14207 // This folding is only valid when the in-reg type is a vector of i8,
14209 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14210 ExtraEltVT == MVT::i32) {
14211 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14212 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14213 "This optimization is invalid without a VZEXT.");
14214 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14220 // If the above didn't work, then just use Shift-Left + Shift-Right.
14221 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14223 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14229 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14230 SelectionDAG &DAG) {
14232 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14233 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14234 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14235 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14237 // The only fence that needs an instruction is a sequentially-consistent
14238 // cross-thread fence.
14239 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14240 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14241 // no-sse2). There isn't any reason to disable it if the target processor
14243 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14244 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14246 SDValue Chain = Op.getOperand(0);
14247 SDValue Zero = DAG.getConstant(0, MVT::i32);
14249 DAG.getRegister(X86::ESP, MVT::i32), // Base
14250 DAG.getTargetConstant(1, MVT::i8), // Scale
14251 DAG.getRegister(0, MVT::i32), // Index
14252 DAG.getTargetConstant(0, MVT::i32), // Disp
14253 DAG.getRegister(0, MVT::i32), // Segment.
14257 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14258 return SDValue(Res, 0);
14261 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14262 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14265 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14266 SelectionDAG &DAG) {
14267 MVT T = Op.getSimpleValueType();
14271 switch(T.SimpleTy) {
14272 default: llvm_unreachable("Invalid value type!");
14273 case MVT::i8: Reg = X86::AL; size = 1; break;
14274 case MVT::i16: Reg = X86::AX; size = 2; break;
14275 case MVT::i32: Reg = X86::EAX; size = 4; break;
14277 assert(Subtarget->is64Bit() && "Node not type legal!");
14278 Reg = X86::RAX; size = 8;
14281 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14282 Op.getOperand(2), SDValue());
14283 SDValue Ops[] = { cpIn.getValue(0),
14286 DAG.getTargetConstant(size, MVT::i8),
14287 cpIn.getValue(1) };
14288 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14289 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14290 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14293 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14297 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14298 SelectionDAG &DAG) {
14299 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14300 MVT DstVT = Op.getSimpleValueType();
14302 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14303 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14304 if (DstVT != MVT::f64)
14305 // This conversion needs to be expanded.
14308 SDValue InVec = Op->getOperand(0);
14310 unsigned NumElts = SrcVT.getVectorNumElements();
14311 EVT SVT = SrcVT.getVectorElementType();
14313 // Widen the vector in input in the case of MVT::v2i32.
14314 // Example: from MVT::v2i32 to MVT::v4i32.
14315 SmallVector<SDValue, 16> Elts;
14316 for (unsigned i = 0, e = NumElts; i != e; ++i)
14317 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14318 DAG.getIntPtrConstant(i)));
14320 // Explicitly mark the extra elements as Undef.
14321 SDValue Undef = DAG.getUNDEF(SVT);
14322 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14323 Elts.push_back(Undef);
14325 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14326 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14327 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14328 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14329 DAG.getIntPtrConstant(0));
14332 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14333 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14334 assert((DstVT == MVT::i64 ||
14335 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14336 "Unexpected custom BITCAST");
14337 // i64 <=> MMX conversions are Legal.
14338 if (SrcVT==MVT::i64 && DstVT.isVector())
14340 if (DstVT==MVT::i64 && SrcVT.isVector())
14342 // MMX <=> MMX conversions are Legal.
14343 if (SrcVT.isVector() && DstVT.isVector())
14345 // All other conversions need to be expanded.
14349 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14350 SDNode *Node = Op.getNode();
14352 EVT T = Node->getValueType(0);
14353 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14354 DAG.getConstant(0, T), Node->getOperand(2));
14355 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14356 cast<AtomicSDNode>(Node)->getMemoryVT(),
14357 Node->getOperand(0),
14358 Node->getOperand(1), negOp,
14359 cast<AtomicSDNode>(Node)->getMemOperand(),
14360 cast<AtomicSDNode>(Node)->getOrdering(),
14361 cast<AtomicSDNode>(Node)->getSynchScope());
14364 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14365 SDNode *Node = Op.getNode();
14367 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14369 // Convert seq_cst store -> xchg
14370 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14371 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14372 // (The only way to get a 16-byte store is cmpxchg16b)
14373 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14374 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14375 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14376 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14377 cast<AtomicSDNode>(Node)->getMemoryVT(),
14378 Node->getOperand(0),
14379 Node->getOperand(1), Node->getOperand(2),
14380 cast<AtomicSDNode>(Node)->getMemOperand(),
14381 cast<AtomicSDNode>(Node)->getOrdering(),
14382 cast<AtomicSDNode>(Node)->getSynchScope());
14383 return Swap.getValue(1);
14385 // Other atomic stores have a simple pattern.
14389 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14390 EVT VT = Op.getNode()->getSimpleValueType(0);
14392 // Let legalize expand this if it isn't a legal type yet.
14393 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14396 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14399 bool ExtraOp = false;
14400 switch (Op.getOpcode()) {
14401 default: llvm_unreachable("Invalid code");
14402 case ISD::ADDC: Opc = X86ISD::ADD; break;
14403 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14404 case ISD::SUBC: Opc = X86ISD::SUB; break;
14405 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14409 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14411 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14412 Op.getOperand(1), Op.getOperand(2));
14415 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14416 SelectionDAG &DAG) {
14417 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14419 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14420 // which returns the values as { float, float } (in XMM0) or
14421 // { double, double } (which is returned in XMM0, XMM1).
14423 SDValue Arg = Op.getOperand(0);
14424 EVT ArgVT = Arg.getValueType();
14425 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14427 TargetLowering::ArgListTy Args;
14428 TargetLowering::ArgListEntry Entry;
14432 Entry.isSExt = false;
14433 Entry.isZExt = false;
14434 Args.push_back(Entry);
14436 bool isF64 = ArgVT == MVT::f64;
14437 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14438 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14439 // the results are returned via SRet in memory.
14440 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14441 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14442 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14444 Type *RetTy = isF64
14445 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14446 : (Type*)VectorType::get(ArgTy, 4);
14448 TargetLowering::CallLoweringInfo CLI(DAG);
14449 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14450 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14452 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14455 // Returned in xmm0 and xmm1.
14456 return CallResult.first;
14458 // Returned in bits 0:31 and 32:64 xmm0.
14459 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14460 CallResult.first, DAG.getIntPtrConstant(0));
14461 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14462 CallResult.first, DAG.getIntPtrConstant(1));
14463 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14464 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14467 /// LowerOperation - Provide custom lowering hooks for some operations.
14469 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14470 switch (Op.getOpcode()) {
14471 default: llvm_unreachable("Should not custom lower this!");
14472 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14473 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14474 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14475 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14476 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14477 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14478 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14479 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14480 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14481 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14482 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14483 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14484 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14485 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14486 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14487 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14488 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14489 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14490 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14491 case ISD::SHL_PARTS:
14492 case ISD::SRA_PARTS:
14493 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14494 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14495 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14496 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14497 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14498 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14499 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14500 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14501 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14502 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14503 case ISD::FABS: return LowerFABS(Op, DAG);
14504 case ISD::FNEG: return LowerFNEG(Op, DAG);
14505 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14506 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14507 case ISD::SETCC: return LowerSETCC(Op, DAG);
14508 case ISD::SELECT: return LowerSELECT(Op, DAG);
14509 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14510 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14511 case ISD::VASTART: return LowerVASTART(Op, DAG);
14512 case ISD::VAARG: return LowerVAARG(Op, DAG);
14513 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14514 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14515 case ISD::INTRINSIC_VOID:
14516 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14517 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14518 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14519 case ISD::FRAME_TO_ARGS_OFFSET:
14520 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14521 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14522 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14523 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14524 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14525 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14526 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14527 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14528 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14529 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14530 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14531 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14532 case ISD::UMUL_LOHI:
14533 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14536 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14542 case ISD::UMULO: return LowerXALUO(Op, DAG);
14543 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14544 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14548 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14549 case ISD::ADD: return LowerADD(Op, DAG);
14550 case ISD::SUB: return LowerSUB(Op, DAG);
14551 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14555 static void ReplaceATOMIC_LOAD(SDNode *Node,
14556 SmallVectorImpl<SDValue> &Results,
14557 SelectionDAG &DAG) {
14559 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14561 // Convert wide load -> cmpxchg8b/cmpxchg16b
14562 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14563 // (The only way to get a 16-byte load is cmpxchg16b)
14564 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14565 SDValue Zero = DAG.getConstant(0, VT);
14566 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14567 Node->getOperand(0),
14568 Node->getOperand(1), Zero, Zero,
14569 cast<AtomicSDNode>(Node)->getMemOperand(),
14570 cast<AtomicSDNode>(Node)->getOrdering(),
14571 cast<AtomicSDNode>(Node)->getOrdering(),
14572 cast<AtomicSDNode>(Node)->getSynchScope());
14573 Results.push_back(Swap.getValue(0));
14574 Results.push_back(Swap.getValue(1));
14578 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14579 SelectionDAG &DAG, unsigned NewOp) {
14581 assert (Node->getValueType(0) == MVT::i64 &&
14582 "Only know how to expand i64 atomics");
14584 SDValue Chain = Node->getOperand(0);
14585 SDValue In1 = Node->getOperand(1);
14586 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14587 Node->getOperand(2), DAG.getIntPtrConstant(0));
14588 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14589 Node->getOperand(2), DAG.getIntPtrConstant(1));
14590 SDValue Ops[] = { Chain, In1, In2L, In2H };
14591 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14593 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14594 cast<MemSDNode>(Node)->getMemOperand());
14595 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14596 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14597 Results.push_back(Result.getValue(2));
14600 /// ReplaceNodeResults - Replace a node with an illegal result type
14601 /// with a new node built out of custom code.
14602 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14603 SmallVectorImpl<SDValue>&Results,
14604 SelectionDAG &DAG) const {
14606 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14607 switch (N->getOpcode()) {
14609 llvm_unreachable("Do not know how to custom type legalize this operation!");
14610 case ISD::SIGN_EXTEND_INREG:
14615 // We don't want to expand or promote these.
14622 case ISD::UDIVREM: {
14623 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14624 Results.push_back(V);
14627 case ISD::FP_TO_SINT:
14628 case ISD::FP_TO_UINT: {
14629 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14631 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14634 std::pair<SDValue,SDValue> Vals =
14635 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14636 SDValue FIST = Vals.first, StackSlot = Vals.second;
14637 if (FIST.getNode()) {
14638 EVT VT = N->getValueType(0);
14639 // Return a load from the stack slot.
14640 if (StackSlot.getNode())
14641 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14642 MachinePointerInfo(),
14643 false, false, false, 0));
14645 Results.push_back(FIST);
14649 case ISD::UINT_TO_FP: {
14650 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14651 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14652 N->getValueType(0) != MVT::v2f32)
14654 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14656 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14658 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14659 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14660 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14661 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14662 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14663 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14666 case ISD::FP_ROUND: {
14667 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14669 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14670 Results.push_back(V);
14673 case ISD::INTRINSIC_W_CHAIN: {
14674 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14676 default : llvm_unreachable("Do not know how to custom type "
14677 "legalize this intrinsic operation!");
14678 case Intrinsic::x86_rdtsc:
14679 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14681 case Intrinsic::x86_rdtscp:
14682 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14686 case ISD::READCYCLECOUNTER: {
14687 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14690 case ISD::ATOMIC_CMP_SWAP: {
14691 EVT T = N->getValueType(0);
14692 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14693 bool Regs64bit = T == MVT::i128;
14694 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14695 SDValue cpInL, cpInH;
14696 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14697 DAG.getConstant(0, HalfT));
14698 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14699 DAG.getConstant(1, HalfT));
14700 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14701 Regs64bit ? X86::RAX : X86::EAX,
14703 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14704 Regs64bit ? X86::RDX : X86::EDX,
14705 cpInH, cpInL.getValue(1));
14706 SDValue swapInL, swapInH;
14707 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14708 DAG.getConstant(0, HalfT));
14709 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14710 DAG.getConstant(1, HalfT));
14711 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14712 Regs64bit ? X86::RBX : X86::EBX,
14713 swapInL, cpInH.getValue(1));
14714 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14715 Regs64bit ? X86::RCX : X86::ECX,
14716 swapInH, swapInL.getValue(1));
14717 SDValue Ops[] = { swapInH.getValue(0),
14719 swapInH.getValue(1) };
14720 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14721 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14722 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14723 X86ISD::LCMPXCHG8_DAG;
14724 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14725 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14726 Regs64bit ? X86::RAX : X86::EAX,
14727 HalfT, Result.getValue(1));
14728 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14729 Regs64bit ? X86::RDX : X86::EDX,
14730 HalfT, cpOutL.getValue(2));
14731 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14732 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14733 Results.push_back(cpOutH.getValue(1));
14736 case ISD::ATOMIC_LOAD_ADD:
14737 case ISD::ATOMIC_LOAD_AND:
14738 case ISD::ATOMIC_LOAD_NAND:
14739 case ISD::ATOMIC_LOAD_OR:
14740 case ISD::ATOMIC_LOAD_SUB:
14741 case ISD::ATOMIC_LOAD_XOR:
14742 case ISD::ATOMIC_LOAD_MAX:
14743 case ISD::ATOMIC_LOAD_MIN:
14744 case ISD::ATOMIC_LOAD_UMAX:
14745 case ISD::ATOMIC_LOAD_UMIN:
14746 case ISD::ATOMIC_SWAP: {
14748 switch (N->getOpcode()) {
14749 default: llvm_unreachable("Unexpected opcode");
14750 case ISD::ATOMIC_LOAD_ADD:
14751 Opc = X86ISD::ATOMADD64_DAG;
14753 case ISD::ATOMIC_LOAD_AND:
14754 Opc = X86ISD::ATOMAND64_DAG;
14756 case ISD::ATOMIC_LOAD_NAND:
14757 Opc = X86ISD::ATOMNAND64_DAG;
14759 case ISD::ATOMIC_LOAD_OR:
14760 Opc = X86ISD::ATOMOR64_DAG;
14762 case ISD::ATOMIC_LOAD_SUB:
14763 Opc = X86ISD::ATOMSUB64_DAG;
14765 case ISD::ATOMIC_LOAD_XOR:
14766 Opc = X86ISD::ATOMXOR64_DAG;
14768 case ISD::ATOMIC_LOAD_MAX:
14769 Opc = X86ISD::ATOMMAX64_DAG;
14771 case ISD::ATOMIC_LOAD_MIN:
14772 Opc = X86ISD::ATOMMIN64_DAG;
14774 case ISD::ATOMIC_LOAD_UMAX:
14775 Opc = X86ISD::ATOMUMAX64_DAG;
14777 case ISD::ATOMIC_LOAD_UMIN:
14778 Opc = X86ISD::ATOMUMIN64_DAG;
14780 case ISD::ATOMIC_SWAP:
14781 Opc = X86ISD::ATOMSWAP64_DAG;
14784 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14787 case ISD::ATOMIC_LOAD: {
14788 ReplaceATOMIC_LOAD(N, Results, DAG);
14791 case ISD::BITCAST: {
14792 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14793 EVT DstVT = N->getValueType(0);
14794 EVT SrcVT = N->getOperand(0)->getValueType(0);
14796 if (SrcVT != MVT::f64 ||
14797 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14800 unsigned NumElts = DstVT.getVectorNumElements();
14801 EVT SVT = DstVT.getVectorElementType();
14802 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14803 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14804 MVT::v2f64, N->getOperand(0));
14805 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14807 SmallVector<SDValue, 8> Elts;
14808 for (unsigned i = 0, e = NumElts; i != e; ++i)
14809 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14810 ToVecInt, DAG.getIntPtrConstant(i)));
14812 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14817 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14819 default: return nullptr;
14820 case X86ISD::BSF: return "X86ISD::BSF";
14821 case X86ISD::BSR: return "X86ISD::BSR";
14822 case X86ISD::SHLD: return "X86ISD::SHLD";
14823 case X86ISD::SHRD: return "X86ISD::SHRD";
14824 case X86ISD::FAND: return "X86ISD::FAND";
14825 case X86ISD::FANDN: return "X86ISD::FANDN";
14826 case X86ISD::FOR: return "X86ISD::FOR";
14827 case X86ISD::FXOR: return "X86ISD::FXOR";
14828 case X86ISD::FSRL: return "X86ISD::FSRL";
14829 case X86ISD::FILD: return "X86ISD::FILD";
14830 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14831 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14832 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14833 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14834 case X86ISD::FLD: return "X86ISD::FLD";
14835 case X86ISD::FST: return "X86ISD::FST";
14836 case X86ISD::CALL: return "X86ISD::CALL";
14837 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14838 case X86ISD::BT: return "X86ISD::BT";
14839 case X86ISD::CMP: return "X86ISD::CMP";
14840 case X86ISD::COMI: return "X86ISD::COMI";
14841 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14842 case X86ISD::CMPM: return "X86ISD::CMPM";
14843 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14844 case X86ISD::SETCC: return "X86ISD::SETCC";
14845 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14846 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14847 case X86ISD::CMOV: return "X86ISD::CMOV";
14848 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14849 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14850 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14851 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14852 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14853 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14854 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14855 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14856 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14857 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14858 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14859 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14860 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14861 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14862 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14863 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14864 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14865 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14866 case X86ISD::HADD: return "X86ISD::HADD";
14867 case X86ISD::HSUB: return "X86ISD::HSUB";
14868 case X86ISD::FHADD: return "X86ISD::FHADD";
14869 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14870 case X86ISD::UMAX: return "X86ISD::UMAX";
14871 case X86ISD::UMIN: return "X86ISD::UMIN";
14872 case X86ISD::SMAX: return "X86ISD::SMAX";
14873 case X86ISD::SMIN: return "X86ISD::SMIN";
14874 case X86ISD::FMAX: return "X86ISD::FMAX";
14875 case X86ISD::FMIN: return "X86ISD::FMIN";
14876 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14877 case X86ISD::FMINC: return "X86ISD::FMINC";
14878 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14879 case X86ISD::FRCP: return "X86ISD::FRCP";
14880 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14881 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14882 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14883 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14884 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14885 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14886 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14887 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14888 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14889 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14890 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14891 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14892 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14893 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14894 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14895 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14896 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14897 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14898 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14899 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14900 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14901 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14902 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14903 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14904 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14905 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14906 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14907 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14908 case X86ISD::VSHL: return "X86ISD::VSHL";
14909 case X86ISD::VSRL: return "X86ISD::VSRL";
14910 case X86ISD::VSRA: return "X86ISD::VSRA";
14911 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14912 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14913 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14914 case X86ISD::CMPP: return "X86ISD::CMPP";
14915 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14916 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14917 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14918 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14919 case X86ISD::ADD: return "X86ISD::ADD";
14920 case X86ISD::SUB: return "X86ISD::SUB";
14921 case X86ISD::ADC: return "X86ISD::ADC";
14922 case X86ISD::SBB: return "X86ISD::SBB";
14923 case X86ISD::SMUL: return "X86ISD::SMUL";
14924 case X86ISD::UMUL: return "X86ISD::UMUL";
14925 case X86ISD::INC: return "X86ISD::INC";
14926 case X86ISD::DEC: return "X86ISD::DEC";
14927 case X86ISD::OR: return "X86ISD::OR";
14928 case X86ISD::XOR: return "X86ISD::XOR";
14929 case X86ISD::AND: return "X86ISD::AND";
14930 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14931 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14932 case X86ISD::PTEST: return "X86ISD::PTEST";
14933 case X86ISD::TESTP: return "X86ISD::TESTP";
14934 case X86ISD::TESTM: return "X86ISD::TESTM";
14935 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14936 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14937 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14938 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14939 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14940 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14941 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14942 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14943 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14944 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14945 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14946 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14947 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14948 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14949 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14950 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14951 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14952 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14953 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14954 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14955 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14956 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14957 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14958 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14959 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14960 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14961 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14962 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14963 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14964 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14965 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14966 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14967 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14968 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14969 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14970 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14971 case X86ISD::SAHF: return "X86ISD::SAHF";
14972 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14973 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14974 case X86ISD::FMADD: return "X86ISD::FMADD";
14975 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14976 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14977 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14978 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14979 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14980 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14981 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14982 case X86ISD::XTEST: return "X86ISD::XTEST";
14986 // isLegalAddressingMode - Return true if the addressing mode represented
14987 // by AM is legal for this target, for a load/store of the specified type.
14988 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14990 // X86 supports extremely general addressing modes.
14991 CodeModel::Model M = getTargetMachine().getCodeModel();
14992 Reloc::Model R = getTargetMachine().getRelocationModel();
14994 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14995 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15000 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15002 // If a reference to this global requires an extra load, we can't fold it.
15003 if (isGlobalStubReference(GVFlags))
15006 // If BaseGV requires a register for the PIC base, we cannot also have a
15007 // BaseReg specified.
15008 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15011 // If lower 4G is not available, then we must use rip-relative addressing.
15012 if ((M != CodeModel::Small || R != Reloc::Static) &&
15013 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15017 switch (AM.Scale) {
15023 // These scales always work.
15028 // These scales are formed with basereg+scalereg. Only accept if there is
15033 default: // Other stuff never works.
15040 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15041 unsigned Bits = Ty->getScalarSizeInBits();
15043 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15044 // particularly cheaper than those without.
15048 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15049 // variable shifts just as cheap as scalar ones.
15050 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15053 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15054 // fully general vector.
15058 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15059 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15061 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15062 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15063 return NumBits1 > NumBits2;
15066 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15067 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15070 if (!isTypeLegal(EVT::getEVT(Ty1)))
15073 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15075 // Assuming the caller doesn't have a zeroext or signext return parameter,
15076 // truncation all the way down to i1 is valid.
15080 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15081 return isInt<32>(Imm);
15084 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15085 // Can also use sub to handle negated immediates.
15086 return isInt<32>(Imm);
15089 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15090 if (!VT1.isInteger() || !VT2.isInteger())
15092 unsigned NumBits1 = VT1.getSizeInBits();
15093 unsigned NumBits2 = VT2.getSizeInBits();
15094 return NumBits1 > NumBits2;
15097 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15098 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15099 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15102 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15103 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15104 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15107 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15108 EVT VT1 = Val.getValueType();
15109 if (isZExtFree(VT1, VT2))
15112 if (Val.getOpcode() != ISD::LOAD)
15115 if (!VT1.isSimple() || !VT1.isInteger() ||
15116 !VT2.isSimple() || !VT2.isInteger())
15119 switch (VT1.getSimpleVT().SimpleTy) {
15124 // X86 has 8, 16, and 32-bit zero-extending loads.
15132 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15133 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15136 VT = VT.getScalarType();
15138 if (!VT.isSimple())
15141 switch (VT.getSimpleVT().SimpleTy) {
15152 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15153 // i16 instructions are longer (0x66 prefix) and potentially slower.
15154 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15157 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15158 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15159 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15160 /// are assumed to be legal.
15162 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15164 if (!VT.isSimple())
15167 MVT SVT = VT.getSimpleVT();
15169 // Very little shuffling can be done for 64-bit vectors right now.
15170 if (VT.getSizeInBits() == 64)
15173 // If this is a single-input shuffle with no 128 bit lane crossings we can
15174 // lower it into pshufb.
15175 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15176 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15177 bool isLegal = true;
15178 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15179 if (M[I] >= (int)SVT.getVectorNumElements() ||
15180 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15189 // FIXME: blends, shifts.
15190 return (SVT.getVectorNumElements() == 2 ||
15191 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15192 isMOVLMask(M, SVT) ||
15193 isSHUFPMask(M, SVT) ||
15194 isPSHUFDMask(M, SVT) ||
15195 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15196 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15197 isPALIGNRMask(M, SVT, Subtarget) ||
15198 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15199 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15200 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15201 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15202 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15206 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15208 if (!VT.isSimple())
15211 MVT SVT = VT.getSimpleVT();
15212 unsigned NumElts = SVT.getVectorNumElements();
15213 // FIXME: This collection of masks seems suspect.
15216 if (NumElts == 4 && SVT.is128BitVector()) {
15217 return (isMOVLMask(Mask, SVT) ||
15218 isCommutedMOVLMask(Mask, SVT, true) ||
15219 isSHUFPMask(Mask, SVT) ||
15220 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15225 //===----------------------------------------------------------------------===//
15226 // X86 Scheduler Hooks
15227 //===----------------------------------------------------------------------===//
15229 /// Utility function to emit xbegin specifying the start of an RTM region.
15230 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15231 const TargetInstrInfo *TII) {
15232 DebugLoc DL = MI->getDebugLoc();
15234 const BasicBlock *BB = MBB->getBasicBlock();
15235 MachineFunction::iterator I = MBB;
15238 // For the v = xbegin(), we generate
15249 MachineBasicBlock *thisMBB = MBB;
15250 MachineFunction *MF = MBB->getParent();
15251 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15252 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15253 MF->insert(I, mainMBB);
15254 MF->insert(I, sinkMBB);
15256 // Transfer the remainder of BB and its successor edges to sinkMBB.
15257 sinkMBB->splice(sinkMBB->begin(), MBB,
15258 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15259 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15263 // # fallthrough to mainMBB
15264 // # abortion to sinkMBB
15265 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15266 thisMBB->addSuccessor(mainMBB);
15267 thisMBB->addSuccessor(sinkMBB);
15271 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15272 mainMBB->addSuccessor(sinkMBB);
15275 // EAX is live into the sinkMBB
15276 sinkMBB->addLiveIn(X86::EAX);
15277 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15278 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15281 MI->eraseFromParent();
15285 // Get CMPXCHG opcode for the specified data type.
15286 static unsigned getCmpXChgOpcode(EVT VT) {
15287 switch (VT.getSimpleVT().SimpleTy) {
15288 case MVT::i8: return X86::LCMPXCHG8;
15289 case MVT::i16: return X86::LCMPXCHG16;
15290 case MVT::i32: return X86::LCMPXCHG32;
15291 case MVT::i64: return X86::LCMPXCHG64;
15295 llvm_unreachable("Invalid operand size!");
15298 // Get LOAD opcode for the specified data type.
15299 static unsigned getLoadOpcode(EVT VT) {
15300 switch (VT.getSimpleVT().SimpleTy) {
15301 case MVT::i8: return X86::MOV8rm;
15302 case MVT::i16: return X86::MOV16rm;
15303 case MVT::i32: return X86::MOV32rm;
15304 case MVT::i64: return X86::MOV64rm;
15308 llvm_unreachable("Invalid operand size!");
15311 // Get opcode of the non-atomic one from the specified atomic instruction.
15312 static unsigned getNonAtomicOpcode(unsigned Opc) {
15314 case X86::ATOMAND8: return X86::AND8rr;
15315 case X86::ATOMAND16: return X86::AND16rr;
15316 case X86::ATOMAND32: return X86::AND32rr;
15317 case X86::ATOMAND64: return X86::AND64rr;
15318 case X86::ATOMOR8: return X86::OR8rr;
15319 case X86::ATOMOR16: return X86::OR16rr;
15320 case X86::ATOMOR32: return X86::OR32rr;
15321 case X86::ATOMOR64: return X86::OR64rr;
15322 case X86::ATOMXOR8: return X86::XOR8rr;
15323 case X86::ATOMXOR16: return X86::XOR16rr;
15324 case X86::ATOMXOR32: return X86::XOR32rr;
15325 case X86::ATOMXOR64: return X86::XOR64rr;
15327 llvm_unreachable("Unhandled atomic-load-op opcode!");
15330 // Get opcode of the non-atomic one from the specified atomic instruction with
15332 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15333 unsigned &ExtraOpc) {
15335 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15336 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15337 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15338 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15339 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15340 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15341 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15342 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15343 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15344 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15345 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15346 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15347 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15348 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15349 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15350 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15351 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15352 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15353 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15354 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15356 llvm_unreachable("Unhandled atomic-load-op opcode!");
15359 // Get opcode of the non-atomic one from the specified atomic instruction for
15360 // 64-bit data type on 32-bit target.
15361 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15363 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15364 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15365 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15366 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15367 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15368 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15369 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15370 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15371 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15372 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15374 llvm_unreachable("Unhandled atomic-load-op opcode!");
15377 // Get opcode of the non-atomic one from the specified atomic instruction for
15378 // 64-bit data type on 32-bit target with extra opcode.
15379 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15381 unsigned &ExtraOpc) {
15383 case X86::ATOMNAND6432:
15384 ExtraOpc = X86::NOT32r;
15385 HiOpc = X86::AND32rr;
15386 return X86::AND32rr;
15388 llvm_unreachable("Unhandled atomic-load-op opcode!");
15391 // Get pseudo CMOV opcode from the specified data type.
15392 static unsigned getPseudoCMOVOpc(EVT VT) {
15393 switch (VT.getSimpleVT().SimpleTy) {
15394 case MVT::i8: return X86::CMOV_GR8;
15395 case MVT::i16: return X86::CMOV_GR16;
15396 case MVT::i32: return X86::CMOV_GR32;
15400 llvm_unreachable("Unknown CMOV opcode!");
15403 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15404 // They will be translated into a spin-loop or compare-exchange loop from
15407 // dst = atomic-fetch-op MI.addr, MI.val
15413 // t1 = LOAD MI.addr
15415 // t4 = phi(t1, t3 / loop)
15416 // t2 = OP MI.val, t4
15418 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15424 MachineBasicBlock *
15425 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15426 MachineBasicBlock *MBB) const {
15427 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15428 DebugLoc DL = MI->getDebugLoc();
15430 MachineFunction *MF = MBB->getParent();
15431 MachineRegisterInfo &MRI = MF->getRegInfo();
15433 const BasicBlock *BB = MBB->getBasicBlock();
15434 MachineFunction::iterator I = MBB;
15437 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15438 "Unexpected number of operands");
15440 assert(MI->hasOneMemOperand() &&
15441 "Expected atomic-load-op to have one memoperand");
15443 // Memory Reference
15444 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15445 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15447 unsigned DstReg, SrcReg;
15448 unsigned MemOpndSlot;
15450 unsigned CurOp = 0;
15452 DstReg = MI->getOperand(CurOp++).getReg();
15453 MemOpndSlot = CurOp;
15454 CurOp += X86::AddrNumOperands;
15455 SrcReg = MI->getOperand(CurOp++).getReg();
15457 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15458 MVT::SimpleValueType VT = *RC->vt_begin();
15459 unsigned t1 = MRI.createVirtualRegister(RC);
15460 unsigned t2 = MRI.createVirtualRegister(RC);
15461 unsigned t3 = MRI.createVirtualRegister(RC);
15462 unsigned t4 = MRI.createVirtualRegister(RC);
15463 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15465 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15466 unsigned LOADOpc = getLoadOpcode(VT);
15468 // For the atomic load-arith operator, we generate
15471 // t1 = LOAD [MI.addr]
15473 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15474 // t1 = OP MI.val, EAX
15476 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15482 MachineBasicBlock *thisMBB = MBB;
15483 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15484 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15485 MF->insert(I, mainMBB);
15486 MF->insert(I, sinkMBB);
15488 MachineInstrBuilder MIB;
15490 // Transfer the remainder of BB and its successor edges to sinkMBB.
15491 sinkMBB->splice(sinkMBB->begin(), MBB,
15492 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15493 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15496 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15497 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15498 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15500 NewMO.setIsKill(false);
15501 MIB.addOperand(NewMO);
15503 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15504 unsigned flags = (*MMOI)->getFlags();
15505 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15506 MachineMemOperand *MMO =
15507 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15508 (*MMOI)->getSize(),
15509 (*MMOI)->getBaseAlignment(),
15510 (*MMOI)->getTBAAInfo(),
15511 (*MMOI)->getRanges());
15512 MIB.addMemOperand(MMO);
15515 thisMBB->addSuccessor(mainMBB);
15518 MachineBasicBlock *origMainMBB = mainMBB;
15521 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15522 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15524 unsigned Opc = MI->getOpcode();
15527 llvm_unreachable("Unhandled atomic-load-op opcode!");
15528 case X86::ATOMAND8:
15529 case X86::ATOMAND16:
15530 case X86::ATOMAND32:
15531 case X86::ATOMAND64:
15533 case X86::ATOMOR16:
15534 case X86::ATOMOR32:
15535 case X86::ATOMOR64:
15536 case X86::ATOMXOR8:
15537 case X86::ATOMXOR16:
15538 case X86::ATOMXOR32:
15539 case X86::ATOMXOR64: {
15540 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15541 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15545 case X86::ATOMNAND8:
15546 case X86::ATOMNAND16:
15547 case X86::ATOMNAND32:
15548 case X86::ATOMNAND64: {
15549 unsigned Tmp = MRI.createVirtualRegister(RC);
15551 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15552 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15554 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15557 case X86::ATOMMAX8:
15558 case X86::ATOMMAX16:
15559 case X86::ATOMMAX32:
15560 case X86::ATOMMAX64:
15561 case X86::ATOMMIN8:
15562 case X86::ATOMMIN16:
15563 case X86::ATOMMIN32:
15564 case X86::ATOMMIN64:
15565 case X86::ATOMUMAX8:
15566 case X86::ATOMUMAX16:
15567 case X86::ATOMUMAX32:
15568 case X86::ATOMUMAX64:
15569 case X86::ATOMUMIN8:
15570 case X86::ATOMUMIN16:
15571 case X86::ATOMUMIN32:
15572 case X86::ATOMUMIN64: {
15574 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15576 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15580 if (Subtarget->hasCMov()) {
15581 if (VT != MVT::i8) {
15583 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15587 // Promote i8 to i32 to use CMOV32
15588 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15589 const TargetRegisterClass *RC32 =
15590 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15591 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15592 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15593 unsigned Tmp = MRI.createVirtualRegister(RC32);
15595 unsigned Undef = MRI.createVirtualRegister(RC32);
15596 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15598 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15601 .addImm(X86::sub_8bit);
15602 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15605 .addImm(X86::sub_8bit);
15607 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15611 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15612 .addReg(Tmp, 0, X86::sub_8bit);
15615 // Use pseudo select and lower them.
15616 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15617 "Invalid atomic-load-op transformation!");
15618 unsigned SelOpc = getPseudoCMOVOpc(VT);
15619 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15620 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15621 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15622 .addReg(SrcReg).addReg(t4)
15624 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15625 // Replace the original PHI node as mainMBB is changed after CMOV
15627 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15628 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15629 Phi->eraseFromParent();
15635 // Copy PhyReg back from virtual register.
15636 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15639 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15640 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15641 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15643 NewMO.setIsKill(false);
15644 MIB.addOperand(NewMO);
15647 MIB.setMemRefs(MMOBegin, MMOEnd);
15649 // Copy PhyReg back to virtual register.
15650 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15653 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15655 mainMBB->addSuccessor(origMainMBB);
15656 mainMBB->addSuccessor(sinkMBB);
15659 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15660 TII->get(TargetOpcode::COPY), DstReg)
15663 MI->eraseFromParent();
15667 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15668 // instructions. They will be translated into a spin-loop or compare-exchange
15672 // dst = atomic-fetch-op MI.addr, MI.val
15678 // t1L = LOAD [MI.addr + 0]
15679 // t1H = LOAD [MI.addr + 4]
15681 // t4L = phi(t1L, t3L / loop)
15682 // t4H = phi(t1H, t3H / loop)
15683 // t2L = OP MI.val.lo, t4L
15684 // t2H = OP MI.val.hi, t4H
15689 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15697 MachineBasicBlock *
15698 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15699 MachineBasicBlock *MBB) const {
15700 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15701 DebugLoc DL = MI->getDebugLoc();
15703 MachineFunction *MF = MBB->getParent();
15704 MachineRegisterInfo &MRI = MF->getRegInfo();
15706 const BasicBlock *BB = MBB->getBasicBlock();
15707 MachineFunction::iterator I = MBB;
15710 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15711 "Unexpected number of operands");
15713 assert(MI->hasOneMemOperand() &&
15714 "Expected atomic-load-op32 to have one memoperand");
15716 // Memory Reference
15717 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15718 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15720 unsigned DstLoReg, DstHiReg;
15721 unsigned SrcLoReg, SrcHiReg;
15722 unsigned MemOpndSlot;
15724 unsigned CurOp = 0;
15726 DstLoReg = MI->getOperand(CurOp++).getReg();
15727 DstHiReg = MI->getOperand(CurOp++).getReg();
15728 MemOpndSlot = CurOp;
15729 CurOp += X86::AddrNumOperands;
15730 SrcLoReg = MI->getOperand(CurOp++).getReg();
15731 SrcHiReg = MI->getOperand(CurOp++).getReg();
15733 const TargetRegisterClass *RC = &X86::GR32RegClass;
15734 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15736 unsigned t1L = MRI.createVirtualRegister(RC);
15737 unsigned t1H = MRI.createVirtualRegister(RC);
15738 unsigned t2L = MRI.createVirtualRegister(RC);
15739 unsigned t2H = MRI.createVirtualRegister(RC);
15740 unsigned t3L = MRI.createVirtualRegister(RC);
15741 unsigned t3H = MRI.createVirtualRegister(RC);
15742 unsigned t4L = MRI.createVirtualRegister(RC);
15743 unsigned t4H = MRI.createVirtualRegister(RC);
15745 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15746 unsigned LOADOpc = X86::MOV32rm;
15748 // For the atomic load-arith operator, we generate
15751 // t1L = LOAD [MI.addr + 0]
15752 // t1H = LOAD [MI.addr + 4]
15754 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15755 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15756 // t2L = OP MI.val.lo, t4L
15757 // t2H = OP MI.val.hi, t4H
15760 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15768 MachineBasicBlock *thisMBB = MBB;
15769 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15770 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15771 MF->insert(I, mainMBB);
15772 MF->insert(I, sinkMBB);
15774 MachineInstrBuilder MIB;
15776 // Transfer the remainder of BB and its successor edges to sinkMBB.
15777 sinkMBB->splice(sinkMBB->begin(), MBB,
15778 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15779 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15783 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15784 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15785 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15787 NewMO.setIsKill(false);
15788 MIB.addOperand(NewMO);
15790 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15791 unsigned flags = (*MMOI)->getFlags();
15792 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15793 MachineMemOperand *MMO =
15794 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15795 (*MMOI)->getSize(),
15796 (*MMOI)->getBaseAlignment(),
15797 (*MMOI)->getTBAAInfo(),
15798 (*MMOI)->getRanges());
15799 MIB.addMemOperand(MMO);
15801 MachineInstr *LowMI = MIB;
15804 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15805 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15806 if (i == X86::AddrDisp) {
15807 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15809 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15811 NewMO.setIsKill(false);
15812 MIB.addOperand(NewMO);
15815 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15817 thisMBB->addSuccessor(mainMBB);
15820 MachineBasicBlock *origMainMBB = mainMBB;
15823 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15824 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15825 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15826 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15828 unsigned Opc = MI->getOpcode();
15831 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15832 case X86::ATOMAND6432:
15833 case X86::ATOMOR6432:
15834 case X86::ATOMXOR6432:
15835 case X86::ATOMADD6432:
15836 case X86::ATOMSUB6432: {
15838 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15839 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15841 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15845 case X86::ATOMNAND6432: {
15846 unsigned HiOpc, NOTOpc;
15847 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15848 unsigned TmpL = MRI.createVirtualRegister(RC);
15849 unsigned TmpH = MRI.createVirtualRegister(RC);
15850 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15852 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15854 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15855 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15858 case X86::ATOMMAX6432:
15859 case X86::ATOMMIN6432:
15860 case X86::ATOMUMAX6432:
15861 case X86::ATOMUMIN6432: {
15863 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15864 unsigned cL = MRI.createVirtualRegister(RC8);
15865 unsigned cH = MRI.createVirtualRegister(RC8);
15866 unsigned cL32 = MRI.createVirtualRegister(RC);
15867 unsigned cH32 = MRI.createVirtualRegister(RC);
15868 unsigned cc = MRI.createVirtualRegister(RC);
15869 // cl := cmp src_lo, lo
15870 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15871 .addReg(SrcLoReg).addReg(t4L);
15872 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15873 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15874 // ch := cmp src_hi, hi
15875 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15876 .addReg(SrcHiReg).addReg(t4H);
15877 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15878 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15879 // cc := if (src_hi == hi) ? cl : ch;
15880 if (Subtarget->hasCMov()) {
15881 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15882 .addReg(cH32).addReg(cL32);
15884 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15885 .addReg(cH32).addReg(cL32)
15886 .addImm(X86::COND_E);
15887 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15889 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15890 if (Subtarget->hasCMov()) {
15891 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15892 .addReg(SrcLoReg).addReg(t4L);
15893 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15894 .addReg(SrcHiReg).addReg(t4H);
15896 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15897 .addReg(SrcLoReg).addReg(t4L)
15898 .addImm(X86::COND_NE);
15899 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15900 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15901 // 2nd CMOV lowering.
15902 mainMBB->addLiveIn(X86::EFLAGS);
15903 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15904 .addReg(SrcHiReg).addReg(t4H)
15905 .addImm(X86::COND_NE);
15906 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15907 // Replace the original PHI node as mainMBB is changed after CMOV
15909 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15910 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15911 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15912 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15913 PhiL->eraseFromParent();
15914 PhiH->eraseFromParent();
15918 case X86::ATOMSWAP6432: {
15920 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15921 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15922 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15927 // Copy EDX:EAX back from HiReg:LoReg
15928 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15929 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15930 // Copy ECX:EBX from t1H:t1L
15931 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15932 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15934 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15935 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15936 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15938 NewMO.setIsKill(false);
15939 MIB.addOperand(NewMO);
15941 MIB.setMemRefs(MMOBegin, MMOEnd);
15943 // Copy EDX:EAX back to t3H:t3L
15944 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15945 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15947 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15949 mainMBB->addSuccessor(origMainMBB);
15950 mainMBB->addSuccessor(sinkMBB);
15953 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15954 TII->get(TargetOpcode::COPY), DstLoReg)
15956 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15957 TII->get(TargetOpcode::COPY), DstHiReg)
15960 MI->eraseFromParent();
15964 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15965 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15966 // in the .td file.
15967 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15968 const TargetInstrInfo *TII) {
15970 switch (MI->getOpcode()) {
15971 default: llvm_unreachable("illegal opcode!");
15972 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15973 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15974 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15975 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15976 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15977 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15978 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15979 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15982 DebugLoc dl = MI->getDebugLoc();
15983 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15985 unsigned NumArgs = MI->getNumOperands();
15986 for (unsigned i = 1; i < NumArgs; ++i) {
15987 MachineOperand &Op = MI->getOperand(i);
15988 if (!(Op.isReg() && Op.isImplicit()))
15989 MIB.addOperand(Op);
15991 if (MI->hasOneMemOperand())
15992 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15994 BuildMI(*BB, MI, dl,
15995 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15996 .addReg(X86::XMM0);
15998 MI->eraseFromParent();
16002 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16003 // defs in an instruction pattern
16004 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16005 const TargetInstrInfo *TII) {
16007 switch (MI->getOpcode()) {
16008 default: llvm_unreachable("illegal opcode!");
16009 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16010 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16011 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16012 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16013 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16014 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16015 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16016 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16019 DebugLoc dl = MI->getDebugLoc();
16020 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16022 unsigned NumArgs = MI->getNumOperands(); // remove the results
16023 for (unsigned i = 1; i < NumArgs; ++i) {
16024 MachineOperand &Op = MI->getOperand(i);
16025 if (!(Op.isReg() && Op.isImplicit()))
16026 MIB.addOperand(Op);
16028 if (MI->hasOneMemOperand())
16029 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16031 BuildMI(*BB, MI, dl,
16032 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16035 MI->eraseFromParent();
16039 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16040 const TargetInstrInfo *TII,
16041 const X86Subtarget* Subtarget) {
16042 DebugLoc dl = MI->getDebugLoc();
16044 // Address into RAX/EAX, other two args into ECX, EDX.
16045 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16046 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16047 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16048 for (int i = 0; i < X86::AddrNumOperands; ++i)
16049 MIB.addOperand(MI->getOperand(i));
16051 unsigned ValOps = X86::AddrNumOperands;
16052 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16053 .addReg(MI->getOperand(ValOps).getReg());
16054 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16055 .addReg(MI->getOperand(ValOps+1).getReg());
16057 // The instruction doesn't actually take any operands though.
16058 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16060 MI->eraseFromParent(); // The pseudo is gone now.
16064 MachineBasicBlock *
16065 X86TargetLowering::EmitVAARG64WithCustomInserter(
16067 MachineBasicBlock *MBB) const {
16068 // Emit va_arg instruction on X86-64.
16070 // Operands to this pseudo-instruction:
16071 // 0 ) Output : destination address (reg)
16072 // 1-5) Input : va_list address (addr, i64mem)
16073 // 6 ) ArgSize : Size (in bytes) of vararg type
16074 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16075 // 8 ) Align : Alignment of type
16076 // 9 ) EFLAGS (implicit-def)
16078 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16079 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16081 unsigned DestReg = MI->getOperand(0).getReg();
16082 MachineOperand &Base = MI->getOperand(1);
16083 MachineOperand &Scale = MI->getOperand(2);
16084 MachineOperand &Index = MI->getOperand(3);
16085 MachineOperand &Disp = MI->getOperand(4);
16086 MachineOperand &Segment = MI->getOperand(5);
16087 unsigned ArgSize = MI->getOperand(6).getImm();
16088 unsigned ArgMode = MI->getOperand(7).getImm();
16089 unsigned Align = MI->getOperand(8).getImm();
16091 // Memory Reference
16092 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16093 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16094 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16096 // Machine Information
16097 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16098 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16099 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16100 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16101 DebugLoc DL = MI->getDebugLoc();
16103 // struct va_list {
16106 // i64 overflow_area (address)
16107 // i64 reg_save_area (address)
16109 // sizeof(va_list) = 24
16110 // alignment(va_list) = 8
16112 unsigned TotalNumIntRegs = 6;
16113 unsigned TotalNumXMMRegs = 8;
16114 bool UseGPOffset = (ArgMode == 1);
16115 bool UseFPOffset = (ArgMode == 2);
16116 unsigned MaxOffset = TotalNumIntRegs * 8 +
16117 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16119 /* Align ArgSize to a multiple of 8 */
16120 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16121 bool NeedsAlign = (Align > 8);
16123 MachineBasicBlock *thisMBB = MBB;
16124 MachineBasicBlock *overflowMBB;
16125 MachineBasicBlock *offsetMBB;
16126 MachineBasicBlock *endMBB;
16128 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16129 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16130 unsigned OffsetReg = 0;
16132 if (!UseGPOffset && !UseFPOffset) {
16133 // If we only pull from the overflow region, we don't create a branch.
16134 // We don't need to alter control flow.
16135 OffsetDestReg = 0; // unused
16136 OverflowDestReg = DestReg;
16138 offsetMBB = nullptr;
16139 overflowMBB = thisMBB;
16142 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16143 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16144 // If not, pull from overflow_area. (branch to overflowMBB)
16149 // offsetMBB overflowMBB
16154 // Registers for the PHI in endMBB
16155 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16156 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16158 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16159 MachineFunction *MF = MBB->getParent();
16160 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16161 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16162 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16164 MachineFunction::iterator MBBIter = MBB;
16167 // Insert the new basic blocks
16168 MF->insert(MBBIter, offsetMBB);
16169 MF->insert(MBBIter, overflowMBB);
16170 MF->insert(MBBIter, endMBB);
16172 // Transfer the remainder of MBB and its successor edges to endMBB.
16173 endMBB->splice(endMBB->begin(), thisMBB,
16174 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16175 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16177 // Make offsetMBB and overflowMBB successors of thisMBB
16178 thisMBB->addSuccessor(offsetMBB);
16179 thisMBB->addSuccessor(overflowMBB);
16181 // endMBB is a successor of both offsetMBB and overflowMBB
16182 offsetMBB->addSuccessor(endMBB);
16183 overflowMBB->addSuccessor(endMBB);
16185 // Load the offset value into a register
16186 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16187 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16191 .addDisp(Disp, UseFPOffset ? 4 : 0)
16192 .addOperand(Segment)
16193 .setMemRefs(MMOBegin, MMOEnd);
16195 // Check if there is enough room left to pull this argument.
16196 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16198 .addImm(MaxOffset + 8 - ArgSizeA8);
16200 // Branch to "overflowMBB" if offset >= max
16201 // Fall through to "offsetMBB" otherwise
16202 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16203 .addMBB(overflowMBB);
16206 // In offsetMBB, emit code to use the reg_save_area.
16208 assert(OffsetReg != 0);
16210 // Read the reg_save_area address.
16211 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16212 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16217 .addOperand(Segment)
16218 .setMemRefs(MMOBegin, MMOEnd);
16220 // Zero-extend the offset
16221 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16222 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16225 .addImm(X86::sub_32bit);
16227 // Add the offset to the reg_save_area to get the final address.
16228 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16229 .addReg(OffsetReg64)
16230 .addReg(RegSaveReg);
16232 // Compute the offset for the next argument
16233 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16234 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16236 .addImm(UseFPOffset ? 16 : 8);
16238 // Store it back into the va_list.
16239 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16243 .addDisp(Disp, UseFPOffset ? 4 : 0)
16244 .addOperand(Segment)
16245 .addReg(NextOffsetReg)
16246 .setMemRefs(MMOBegin, MMOEnd);
16249 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16254 // Emit code to use overflow area
16257 // Load the overflow_area address into a register.
16258 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16259 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16264 .addOperand(Segment)
16265 .setMemRefs(MMOBegin, MMOEnd);
16267 // If we need to align it, do so. Otherwise, just copy the address
16268 // to OverflowDestReg.
16270 // Align the overflow address
16271 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16272 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16274 // aligned_addr = (addr + (align-1)) & ~(align-1)
16275 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16276 .addReg(OverflowAddrReg)
16279 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16281 .addImm(~(uint64_t)(Align-1));
16283 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16284 .addReg(OverflowAddrReg);
16287 // Compute the next overflow address after this argument.
16288 // (the overflow address should be kept 8-byte aligned)
16289 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16290 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16291 .addReg(OverflowDestReg)
16292 .addImm(ArgSizeA8);
16294 // Store the new overflow address.
16295 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16300 .addOperand(Segment)
16301 .addReg(NextAddrReg)
16302 .setMemRefs(MMOBegin, MMOEnd);
16304 // If we branched, emit the PHI to the front of endMBB.
16306 BuildMI(*endMBB, endMBB->begin(), DL,
16307 TII->get(X86::PHI), DestReg)
16308 .addReg(OffsetDestReg).addMBB(offsetMBB)
16309 .addReg(OverflowDestReg).addMBB(overflowMBB);
16312 // Erase the pseudo instruction
16313 MI->eraseFromParent();
16318 MachineBasicBlock *
16319 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16321 MachineBasicBlock *MBB) const {
16322 // Emit code to save XMM registers to the stack. The ABI says that the
16323 // number of registers to save is given in %al, so it's theoretically
16324 // possible to do an indirect jump trick to avoid saving all of them,
16325 // however this code takes a simpler approach and just executes all
16326 // of the stores if %al is non-zero. It's less code, and it's probably
16327 // easier on the hardware branch predictor, and stores aren't all that
16328 // expensive anyway.
16330 // Create the new basic blocks. One block contains all the XMM stores,
16331 // and one block is the final destination regardless of whether any
16332 // stores were performed.
16333 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16334 MachineFunction *F = MBB->getParent();
16335 MachineFunction::iterator MBBIter = MBB;
16337 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16338 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16339 F->insert(MBBIter, XMMSaveMBB);
16340 F->insert(MBBIter, EndMBB);
16342 // Transfer the remainder of MBB and its successor edges to EndMBB.
16343 EndMBB->splice(EndMBB->begin(), MBB,
16344 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16345 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16347 // The original block will now fall through to the XMM save block.
16348 MBB->addSuccessor(XMMSaveMBB);
16349 // The XMMSaveMBB will fall through to the end block.
16350 XMMSaveMBB->addSuccessor(EndMBB);
16352 // Now add the instructions.
16353 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16354 DebugLoc DL = MI->getDebugLoc();
16356 unsigned CountReg = MI->getOperand(0).getReg();
16357 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16358 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16360 if (!Subtarget->isTargetWin64()) {
16361 // If %al is 0, branch around the XMM save block.
16362 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16363 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16364 MBB->addSuccessor(EndMBB);
16367 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16368 // that was just emitted, but clearly shouldn't be "saved".
16369 assert((MI->getNumOperands() <= 3 ||
16370 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16371 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16372 && "Expected last argument to be EFLAGS");
16373 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16374 // In the XMM save block, save all the XMM argument registers.
16375 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16376 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16377 MachineMemOperand *MMO =
16378 F->getMachineMemOperand(
16379 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16380 MachineMemOperand::MOStore,
16381 /*Size=*/16, /*Align=*/16);
16382 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16383 .addFrameIndex(RegSaveFrameIndex)
16384 .addImm(/*Scale=*/1)
16385 .addReg(/*IndexReg=*/0)
16386 .addImm(/*Disp=*/Offset)
16387 .addReg(/*Segment=*/0)
16388 .addReg(MI->getOperand(i).getReg())
16389 .addMemOperand(MMO);
16392 MI->eraseFromParent(); // The pseudo instruction is gone now.
16397 // The EFLAGS operand of SelectItr might be missing a kill marker
16398 // because there were multiple uses of EFLAGS, and ISel didn't know
16399 // which to mark. Figure out whether SelectItr should have had a
16400 // kill marker, and set it if it should. Returns the correct kill
16402 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16403 MachineBasicBlock* BB,
16404 const TargetRegisterInfo* TRI) {
16405 // Scan forward through BB for a use/def of EFLAGS.
16406 MachineBasicBlock::iterator miI(std::next(SelectItr));
16407 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16408 const MachineInstr& mi = *miI;
16409 if (mi.readsRegister(X86::EFLAGS))
16411 if (mi.definesRegister(X86::EFLAGS))
16412 break; // Should have kill-flag - update below.
16415 // If we hit the end of the block, check whether EFLAGS is live into a
16417 if (miI == BB->end()) {
16418 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16419 sEnd = BB->succ_end();
16420 sItr != sEnd; ++sItr) {
16421 MachineBasicBlock* succ = *sItr;
16422 if (succ->isLiveIn(X86::EFLAGS))
16427 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16428 // out. SelectMI should have a kill flag on EFLAGS.
16429 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16433 MachineBasicBlock *
16434 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16435 MachineBasicBlock *BB) const {
16436 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16437 DebugLoc DL = MI->getDebugLoc();
16439 // To "insert" a SELECT_CC instruction, we actually have to insert the
16440 // diamond control-flow pattern. The incoming instruction knows the
16441 // destination vreg to set, the condition code register to branch on, the
16442 // true/false values to select between, and a branch opcode to use.
16443 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16444 MachineFunction::iterator It = BB;
16450 // cmpTY ccX, r1, r2
16452 // fallthrough --> copy0MBB
16453 MachineBasicBlock *thisMBB = BB;
16454 MachineFunction *F = BB->getParent();
16455 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16456 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16457 F->insert(It, copy0MBB);
16458 F->insert(It, sinkMBB);
16460 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16461 // live into the sink and copy blocks.
16462 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16463 if (!MI->killsRegister(X86::EFLAGS) &&
16464 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16465 copy0MBB->addLiveIn(X86::EFLAGS);
16466 sinkMBB->addLiveIn(X86::EFLAGS);
16469 // Transfer the remainder of BB and its successor edges to sinkMBB.
16470 sinkMBB->splice(sinkMBB->begin(), BB,
16471 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16472 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16474 // Add the true and fallthrough blocks as its successors.
16475 BB->addSuccessor(copy0MBB);
16476 BB->addSuccessor(sinkMBB);
16478 // Create the conditional branch instruction.
16480 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16481 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16484 // %FalseValue = ...
16485 // # fallthrough to sinkMBB
16486 copy0MBB->addSuccessor(sinkMBB);
16489 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16491 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16492 TII->get(X86::PHI), MI->getOperand(0).getReg())
16493 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16494 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16496 MI->eraseFromParent(); // The pseudo instruction is gone now.
16500 MachineBasicBlock *
16501 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16502 bool Is64Bit) const {
16503 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16504 DebugLoc DL = MI->getDebugLoc();
16505 MachineFunction *MF = BB->getParent();
16506 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16508 assert(MF->shouldSplitStack());
16510 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16511 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16514 // ... [Till the alloca]
16515 // If stacklet is not large enough, jump to mallocMBB
16518 // Allocate by subtracting from RSP
16519 // Jump to continueMBB
16522 // Allocate by call to runtime
16526 // [rest of original BB]
16529 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16530 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16531 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16533 MachineRegisterInfo &MRI = MF->getRegInfo();
16534 const TargetRegisterClass *AddrRegClass =
16535 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16537 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16538 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16539 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16540 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16541 sizeVReg = MI->getOperand(1).getReg(),
16542 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16544 MachineFunction::iterator MBBIter = BB;
16547 MF->insert(MBBIter, bumpMBB);
16548 MF->insert(MBBIter, mallocMBB);
16549 MF->insert(MBBIter, continueMBB);
16551 continueMBB->splice(continueMBB->begin(), BB,
16552 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16553 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16555 // Add code to the main basic block to check if the stack limit has been hit,
16556 // and if so, jump to mallocMBB otherwise to bumpMBB.
16557 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16558 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16559 .addReg(tmpSPVReg).addReg(sizeVReg);
16560 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16561 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16562 .addReg(SPLimitVReg);
16563 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16565 // bumpMBB simply decreases the stack pointer, since we know the current
16566 // stacklet has enough space.
16567 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16568 .addReg(SPLimitVReg);
16569 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16570 .addReg(SPLimitVReg);
16571 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16573 // Calls into a routine in libgcc to allocate more space from the heap.
16574 const uint32_t *RegMask =
16575 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16577 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16579 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16580 .addExternalSymbol("__morestack_allocate_stack_space")
16581 .addRegMask(RegMask)
16582 .addReg(X86::RDI, RegState::Implicit)
16583 .addReg(X86::RAX, RegState::ImplicitDefine);
16585 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16587 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16588 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16589 .addExternalSymbol("__morestack_allocate_stack_space")
16590 .addRegMask(RegMask)
16591 .addReg(X86::EAX, RegState::ImplicitDefine);
16595 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16598 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16599 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16600 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16602 // Set up the CFG correctly.
16603 BB->addSuccessor(bumpMBB);
16604 BB->addSuccessor(mallocMBB);
16605 mallocMBB->addSuccessor(continueMBB);
16606 bumpMBB->addSuccessor(continueMBB);
16608 // Take care of the PHI nodes.
16609 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16610 MI->getOperand(0).getReg())
16611 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16612 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16614 // Delete the original pseudo instruction.
16615 MI->eraseFromParent();
16618 return continueMBB;
16621 MachineBasicBlock *
16622 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16623 MachineBasicBlock *BB) const {
16624 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16625 DebugLoc DL = MI->getDebugLoc();
16627 assert(!Subtarget->isTargetMacho());
16629 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16630 // non-trivial part is impdef of ESP.
16632 if (Subtarget->isTargetWin64()) {
16633 if (Subtarget->isTargetCygMing()) {
16634 // ___chkstk(Mingw64):
16635 // Clobbers R10, R11, RAX and EFLAGS.
16637 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16638 .addExternalSymbol("___chkstk")
16639 .addReg(X86::RAX, RegState::Implicit)
16640 .addReg(X86::RSP, RegState::Implicit)
16641 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16642 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16643 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16645 // __chkstk(MSVCRT): does not update stack pointer.
16646 // Clobbers R10, R11 and EFLAGS.
16647 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16648 .addExternalSymbol("__chkstk")
16649 .addReg(X86::RAX, RegState::Implicit)
16650 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16651 // RAX has the offset to be subtracted from RSP.
16652 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16657 const char *StackProbeSymbol =
16658 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16660 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16661 .addExternalSymbol(StackProbeSymbol)
16662 .addReg(X86::EAX, RegState::Implicit)
16663 .addReg(X86::ESP, RegState::Implicit)
16664 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16665 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16666 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16669 MI->eraseFromParent(); // The pseudo instruction is gone now.
16673 MachineBasicBlock *
16674 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16675 MachineBasicBlock *BB) const {
16676 // This is pretty easy. We're taking the value that we received from
16677 // our load from the relocation, sticking it in either RDI (x86-64)
16678 // or EAX and doing an indirect call. The return value will then
16679 // be in the normal return register.
16680 const X86InstrInfo *TII
16681 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16682 DebugLoc DL = MI->getDebugLoc();
16683 MachineFunction *F = BB->getParent();
16685 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16686 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16688 // Get a register mask for the lowered call.
16689 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16690 // proper register mask.
16691 const uint32_t *RegMask =
16692 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16693 if (Subtarget->is64Bit()) {
16694 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16695 TII->get(X86::MOV64rm), X86::RDI)
16697 .addImm(0).addReg(0)
16698 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16699 MI->getOperand(3).getTargetFlags())
16701 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16702 addDirectMem(MIB, X86::RDI);
16703 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16704 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16705 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16706 TII->get(X86::MOV32rm), X86::EAX)
16708 .addImm(0).addReg(0)
16709 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16710 MI->getOperand(3).getTargetFlags())
16712 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16713 addDirectMem(MIB, X86::EAX);
16714 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16716 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16717 TII->get(X86::MOV32rm), X86::EAX)
16718 .addReg(TII->getGlobalBaseReg(F))
16719 .addImm(0).addReg(0)
16720 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16721 MI->getOperand(3).getTargetFlags())
16723 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16724 addDirectMem(MIB, X86::EAX);
16725 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16728 MI->eraseFromParent(); // The pseudo instruction is gone now.
16732 MachineBasicBlock *
16733 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16734 MachineBasicBlock *MBB) const {
16735 DebugLoc DL = MI->getDebugLoc();
16736 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16738 MachineFunction *MF = MBB->getParent();
16739 MachineRegisterInfo &MRI = MF->getRegInfo();
16741 const BasicBlock *BB = MBB->getBasicBlock();
16742 MachineFunction::iterator I = MBB;
16745 // Memory Reference
16746 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16747 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16750 unsigned MemOpndSlot = 0;
16752 unsigned CurOp = 0;
16754 DstReg = MI->getOperand(CurOp++).getReg();
16755 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16756 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16757 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16758 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16760 MemOpndSlot = CurOp;
16762 MVT PVT = getPointerTy();
16763 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16764 "Invalid Pointer Size!");
16766 // For v = setjmp(buf), we generate
16769 // buf[LabelOffset] = restoreMBB
16770 // SjLjSetup restoreMBB
16776 // v = phi(main, restore)
16781 MachineBasicBlock *thisMBB = MBB;
16782 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16783 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16784 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16785 MF->insert(I, mainMBB);
16786 MF->insert(I, sinkMBB);
16787 MF->push_back(restoreMBB);
16789 MachineInstrBuilder MIB;
16791 // Transfer the remainder of BB and its successor edges to sinkMBB.
16792 sinkMBB->splice(sinkMBB->begin(), MBB,
16793 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16794 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16797 unsigned PtrStoreOpc = 0;
16798 unsigned LabelReg = 0;
16799 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16800 Reloc::Model RM = getTargetMachine().getRelocationModel();
16801 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16802 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16804 // Prepare IP either in reg or imm.
16805 if (!UseImmLabel) {
16806 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16807 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16808 LabelReg = MRI.createVirtualRegister(PtrRC);
16809 if (Subtarget->is64Bit()) {
16810 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16814 .addMBB(restoreMBB)
16817 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16818 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16819 .addReg(XII->getGlobalBaseReg(MF))
16822 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16826 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16828 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16829 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16830 if (i == X86::AddrDisp)
16831 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16833 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16836 MIB.addReg(LabelReg);
16838 MIB.addMBB(restoreMBB);
16839 MIB.setMemRefs(MMOBegin, MMOEnd);
16841 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16842 .addMBB(restoreMBB);
16844 const X86RegisterInfo *RegInfo =
16845 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16846 MIB.addRegMask(RegInfo->getNoPreservedMask());
16847 thisMBB->addSuccessor(mainMBB);
16848 thisMBB->addSuccessor(restoreMBB);
16852 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16853 mainMBB->addSuccessor(sinkMBB);
16856 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16857 TII->get(X86::PHI), DstReg)
16858 .addReg(mainDstReg).addMBB(mainMBB)
16859 .addReg(restoreDstReg).addMBB(restoreMBB);
16862 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16863 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16864 restoreMBB->addSuccessor(sinkMBB);
16866 MI->eraseFromParent();
16870 MachineBasicBlock *
16871 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16872 MachineBasicBlock *MBB) const {
16873 DebugLoc DL = MI->getDebugLoc();
16874 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16876 MachineFunction *MF = MBB->getParent();
16877 MachineRegisterInfo &MRI = MF->getRegInfo();
16879 // Memory Reference
16880 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16881 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16883 MVT PVT = getPointerTy();
16884 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16885 "Invalid Pointer Size!");
16887 const TargetRegisterClass *RC =
16888 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16889 unsigned Tmp = MRI.createVirtualRegister(RC);
16890 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16891 const X86RegisterInfo *RegInfo =
16892 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16893 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16894 unsigned SP = RegInfo->getStackRegister();
16896 MachineInstrBuilder MIB;
16898 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16899 const int64_t SPOffset = 2 * PVT.getStoreSize();
16901 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16902 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16905 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16906 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16907 MIB.addOperand(MI->getOperand(i));
16908 MIB.setMemRefs(MMOBegin, MMOEnd);
16910 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16911 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16912 if (i == X86::AddrDisp)
16913 MIB.addDisp(MI->getOperand(i), LabelOffset);
16915 MIB.addOperand(MI->getOperand(i));
16917 MIB.setMemRefs(MMOBegin, MMOEnd);
16919 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16920 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16921 if (i == X86::AddrDisp)
16922 MIB.addDisp(MI->getOperand(i), SPOffset);
16924 MIB.addOperand(MI->getOperand(i));
16926 MIB.setMemRefs(MMOBegin, MMOEnd);
16928 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16930 MI->eraseFromParent();
16934 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16935 // accumulator loops. Writing back to the accumulator allows the coalescer
16936 // to remove extra copies in the loop.
16937 MachineBasicBlock *
16938 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16939 MachineBasicBlock *MBB) const {
16940 MachineOperand &AddendOp = MI->getOperand(3);
16942 // Bail out early if the addend isn't a register - we can't switch these.
16943 if (!AddendOp.isReg())
16946 MachineFunction &MF = *MBB->getParent();
16947 MachineRegisterInfo &MRI = MF.getRegInfo();
16949 // Check whether the addend is defined by a PHI:
16950 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16951 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16952 if (!AddendDef.isPHI())
16955 // Look for the following pattern:
16957 // %addend = phi [%entry, 0], [%loop, %result]
16959 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16963 // %addend = phi [%entry, 0], [%loop, %result]
16965 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16967 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16968 assert(AddendDef.getOperand(i).isReg());
16969 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16970 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16971 if (&PHISrcInst == MI) {
16972 // Found a matching instruction.
16973 unsigned NewFMAOpc = 0;
16974 switch (MI->getOpcode()) {
16975 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16976 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16977 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16978 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16979 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16980 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16981 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16982 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16983 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16984 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16985 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16986 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16987 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16988 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16989 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16990 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16991 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16992 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16993 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16994 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16995 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16996 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16997 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16998 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16999 default: llvm_unreachable("Unrecognized FMA variant.");
17002 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17003 MachineInstrBuilder MIB =
17004 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17005 .addOperand(MI->getOperand(0))
17006 .addOperand(MI->getOperand(3))
17007 .addOperand(MI->getOperand(2))
17008 .addOperand(MI->getOperand(1));
17009 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17010 MI->eraseFromParent();
17017 MachineBasicBlock *
17018 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17019 MachineBasicBlock *BB) const {
17020 switch (MI->getOpcode()) {
17021 default: llvm_unreachable("Unexpected instr type to insert");
17022 case X86::TAILJMPd64:
17023 case X86::TAILJMPr64:
17024 case X86::TAILJMPm64:
17025 llvm_unreachable("TAILJMP64 would not be touched here.");
17026 case X86::TCRETURNdi64:
17027 case X86::TCRETURNri64:
17028 case X86::TCRETURNmi64:
17030 case X86::WIN_ALLOCA:
17031 return EmitLoweredWinAlloca(MI, BB);
17032 case X86::SEG_ALLOCA_32:
17033 return EmitLoweredSegAlloca(MI, BB, false);
17034 case X86::SEG_ALLOCA_64:
17035 return EmitLoweredSegAlloca(MI, BB, true);
17036 case X86::TLSCall_32:
17037 case X86::TLSCall_64:
17038 return EmitLoweredTLSCall(MI, BB);
17039 case X86::CMOV_GR8:
17040 case X86::CMOV_FR32:
17041 case X86::CMOV_FR64:
17042 case X86::CMOV_V4F32:
17043 case X86::CMOV_V2F64:
17044 case X86::CMOV_V2I64:
17045 case X86::CMOV_V8F32:
17046 case X86::CMOV_V4F64:
17047 case X86::CMOV_V4I64:
17048 case X86::CMOV_V16F32:
17049 case X86::CMOV_V8F64:
17050 case X86::CMOV_V8I64:
17051 case X86::CMOV_GR16:
17052 case X86::CMOV_GR32:
17053 case X86::CMOV_RFP32:
17054 case X86::CMOV_RFP64:
17055 case X86::CMOV_RFP80:
17056 return EmitLoweredSelect(MI, BB);
17058 case X86::FP32_TO_INT16_IN_MEM:
17059 case X86::FP32_TO_INT32_IN_MEM:
17060 case X86::FP32_TO_INT64_IN_MEM:
17061 case X86::FP64_TO_INT16_IN_MEM:
17062 case X86::FP64_TO_INT32_IN_MEM:
17063 case X86::FP64_TO_INT64_IN_MEM:
17064 case X86::FP80_TO_INT16_IN_MEM:
17065 case X86::FP80_TO_INT32_IN_MEM:
17066 case X86::FP80_TO_INT64_IN_MEM: {
17067 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17068 DebugLoc DL = MI->getDebugLoc();
17070 // Change the floating point control register to use "round towards zero"
17071 // mode when truncating to an integer value.
17072 MachineFunction *F = BB->getParent();
17073 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17074 addFrameReference(BuildMI(*BB, MI, DL,
17075 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17077 // Load the old value of the high byte of the control word...
17079 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17080 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17083 // Set the high part to be round to zero...
17084 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17087 // Reload the modified control word now...
17088 addFrameReference(BuildMI(*BB, MI, DL,
17089 TII->get(X86::FLDCW16m)), CWFrameIdx);
17091 // Restore the memory image of control word to original value
17092 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17095 // Get the X86 opcode to use.
17097 switch (MI->getOpcode()) {
17098 default: llvm_unreachable("illegal opcode!");
17099 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17100 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17101 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17102 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17103 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17104 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17105 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17106 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17107 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17111 MachineOperand &Op = MI->getOperand(0);
17113 AM.BaseType = X86AddressMode::RegBase;
17114 AM.Base.Reg = Op.getReg();
17116 AM.BaseType = X86AddressMode::FrameIndexBase;
17117 AM.Base.FrameIndex = Op.getIndex();
17119 Op = MI->getOperand(1);
17121 AM.Scale = Op.getImm();
17122 Op = MI->getOperand(2);
17124 AM.IndexReg = Op.getImm();
17125 Op = MI->getOperand(3);
17126 if (Op.isGlobal()) {
17127 AM.GV = Op.getGlobal();
17129 AM.Disp = Op.getImm();
17131 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17132 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17134 // Reload the original control word now.
17135 addFrameReference(BuildMI(*BB, MI, DL,
17136 TII->get(X86::FLDCW16m)), CWFrameIdx);
17138 MI->eraseFromParent(); // The pseudo instruction is gone now.
17141 // String/text processing lowering.
17142 case X86::PCMPISTRM128REG:
17143 case X86::VPCMPISTRM128REG:
17144 case X86::PCMPISTRM128MEM:
17145 case X86::VPCMPISTRM128MEM:
17146 case X86::PCMPESTRM128REG:
17147 case X86::VPCMPESTRM128REG:
17148 case X86::PCMPESTRM128MEM:
17149 case X86::VPCMPESTRM128MEM:
17150 assert(Subtarget->hasSSE42() &&
17151 "Target must have SSE4.2 or AVX features enabled");
17152 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17154 // String/text processing lowering.
17155 case X86::PCMPISTRIREG:
17156 case X86::VPCMPISTRIREG:
17157 case X86::PCMPISTRIMEM:
17158 case X86::VPCMPISTRIMEM:
17159 case X86::PCMPESTRIREG:
17160 case X86::VPCMPESTRIREG:
17161 case X86::PCMPESTRIMEM:
17162 case X86::VPCMPESTRIMEM:
17163 assert(Subtarget->hasSSE42() &&
17164 "Target must have SSE4.2 or AVX features enabled");
17165 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17167 // Thread synchronization.
17169 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17173 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17175 // Atomic Lowering.
17176 case X86::ATOMAND8:
17177 case X86::ATOMAND16:
17178 case X86::ATOMAND32:
17179 case X86::ATOMAND64:
17182 case X86::ATOMOR16:
17183 case X86::ATOMOR32:
17184 case X86::ATOMOR64:
17186 case X86::ATOMXOR16:
17187 case X86::ATOMXOR8:
17188 case X86::ATOMXOR32:
17189 case X86::ATOMXOR64:
17191 case X86::ATOMNAND8:
17192 case X86::ATOMNAND16:
17193 case X86::ATOMNAND32:
17194 case X86::ATOMNAND64:
17196 case X86::ATOMMAX8:
17197 case X86::ATOMMAX16:
17198 case X86::ATOMMAX32:
17199 case X86::ATOMMAX64:
17201 case X86::ATOMMIN8:
17202 case X86::ATOMMIN16:
17203 case X86::ATOMMIN32:
17204 case X86::ATOMMIN64:
17206 case X86::ATOMUMAX8:
17207 case X86::ATOMUMAX16:
17208 case X86::ATOMUMAX32:
17209 case X86::ATOMUMAX64:
17211 case X86::ATOMUMIN8:
17212 case X86::ATOMUMIN16:
17213 case X86::ATOMUMIN32:
17214 case X86::ATOMUMIN64:
17215 return EmitAtomicLoadArith(MI, BB);
17217 // This group does 64-bit operations on a 32-bit host.
17218 case X86::ATOMAND6432:
17219 case X86::ATOMOR6432:
17220 case X86::ATOMXOR6432:
17221 case X86::ATOMNAND6432:
17222 case X86::ATOMADD6432:
17223 case X86::ATOMSUB6432:
17224 case X86::ATOMMAX6432:
17225 case X86::ATOMMIN6432:
17226 case X86::ATOMUMAX6432:
17227 case X86::ATOMUMIN6432:
17228 case X86::ATOMSWAP6432:
17229 return EmitAtomicLoadArith6432(MI, BB);
17231 case X86::VASTART_SAVE_XMM_REGS:
17232 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17234 case X86::VAARG_64:
17235 return EmitVAARG64WithCustomInserter(MI, BB);
17237 case X86::EH_SjLj_SetJmp32:
17238 case X86::EH_SjLj_SetJmp64:
17239 return emitEHSjLjSetJmp(MI, BB);
17241 case X86::EH_SjLj_LongJmp32:
17242 case X86::EH_SjLj_LongJmp64:
17243 return emitEHSjLjLongJmp(MI, BB);
17245 case TargetOpcode::STACKMAP:
17246 case TargetOpcode::PATCHPOINT:
17247 return emitPatchPoint(MI, BB);
17249 case X86::VFMADDPDr213r:
17250 case X86::VFMADDPSr213r:
17251 case X86::VFMADDSDr213r:
17252 case X86::VFMADDSSr213r:
17253 case X86::VFMSUBPDr213r:
17254 case X86::VFMSUBPSr213r:
17255 case X86::VFMSUBSDr213r:
17256 case X86::VFMSUBSSr213r:
17257 case X86::VFNMADDPDr213r:
17258 case X86::VFNMADDPSr213r:
17259 case X86::VFNMADDSDr213r:
17260 case X86::VFNMADDSSr213r:
17261 case X86::VFNMSUBPDr213r:
17262 case X86::VFNMSUBPSr213r:
17263 case X86::VFNMSUBSDr213r:
17264 case X86::VFNMSUBSSr213r:
17265 case X86::VFMADDPDr213rY:
17266 case X86::VFMADDPSr213rY:
17267 case X86::VFMSUBPDr213rY:
17268 case X86::VFMSUBPSr213rY:
17269 case X86::VFNMADDPDr213rY:
17270 case X86::VFNMADDPSr213rY:
17271 case X86::VFNMSUBPDr213rY:
17272 case X86::VFNMSUBPSr213rY:
17273 return emitFMA3Instr(MI, BB);
17277 //===----------------------------------------------------------------------===//
17278 // X86 Optimization Hooks
17279 //===----------------------------------------------------------------------===//
17281 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17284 const SelectionDAG &DAG,
17285 unsigned Depth) const {
17286 unsigned BitWidth = KnownZero.getBitWidth();
17287 unsigned Opc = Op.getOpcode();
17288 assert((Opc >= ISD::BUILTIN_OP_END ||
17289 Opc == ISD::INTRINSIC_WO_CHAIN ||
17290 Opc == ISD::INTRINSIC_W_CHAIN ||
17291 Opc == ISD::INTRINSIC_VOID) &&
17292 "Should use MaskedValueIsZero if you don't know whether Op"
17293 " is a target node!");
17295 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17309 // These nodes' second result is a boolean.
17310 if (Op.getResNo() == 0)
17313 case X86ISD::SETCC:
17314 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17316 case ISD::INTRINSIC_WO_CHAIN: {
17317 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17318 unsigned NumLoBits = 0;
17321 case Intrinsic::x86_sse_movmsk_ps:
17322 case Intrinsic::x86_avx_movmsk_ps_256:
17323 case Intrinsic::x86_sse2_movmsk_pd:
17324 case Intrinsic::x86_avx_movmsk_pd_256:
17325 case Intrinsic::x86_mmx_pmovmskb:
17326 case Intrinsic::x86_sse2_pmovmskb_128:
17327 case Intrinsic::x86_avx2_pmovmskb: {
17328 // High bits of movmskp{s|d}, pmovmskb are known zero.
17330 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17331 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17332 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17333 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17334 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17335 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17336 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17337 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17339 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17348 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17350 const SelectionDAG &,
17351 unsigned Depth) const {
17352 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17353 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17354 return Op.getValueType().getScalarType().getSizeInBits();
17360 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17361 /// node is a GlobalAddress + offset.
17362 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17363 const GlobalValue* &GA,
17364 int64_t &Offset) const {
17365 if (N->getOpcode() == X86ISD::Wrapper) {
17366 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17367 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17368 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17372 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17375 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17376 /// same as extracting the high 128-bit part of 256-bit vector and then
17377 /// inserting the result into the low part of a new 256-bit vector
17378 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17379 EVT VT = SVOp->getValueType(0);
17380 unsigned NumElems = VT.getVectorNumElements();
17382 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17383 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17384 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17385 SVOp->getMaskElt(j) >= 0)
17391 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17392 /// same as extracting the low 128-bit part of 256-bit vector and then
17393 /// inserting the result into the high part of a new 256-bit vector
17394 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17395 EVT VT = SVOp->getValueType(0);
17396 unsigned NumElems = VT.getVectorNumElements();
17398 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17399 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17400 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17401 SVOp->getMaskElt(j) >= 0)
17407 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17408 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17409 TargetLowering::DAGCombinerInfo &DCI,
17410 const X86Subtarget* Subtarget) {
17412 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17413 SDValue V1 = SVOp->getOperand(0);
17414 SDValue V2 = SVOp->getOperand(1);
17415 EVT VT = SVOp->getValueType(0);
17416 unsigned NumElems = VT.getVectorNumElements();
17418 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17419 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17423 // V UNDEF BUILD_VECTOR UNDEF
17425 // CONCAT_VECTOR CONCAT_VECTOR
17428 // RESULT: V + zero extended
17430 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17431 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17432 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17435 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17438 // To match the shuffle mask, the first half of the mask should
17439 // be exactly the first vector, and all the rest a splat with the
17440 // first element of the second one.
17441 for (unsigned i = 0; i != NumElems/2; ++i)
17442 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17443 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17446 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17447 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17448 if (Ld->hasNUsesOfValue(1, 0)) {
17449 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17450 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17452 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17454 Ld->getPointerInfo(),
17455 Ld->getAlignment(),
17456 false/*isVolatile*/, true/*ReadMem*/,
17457 false/*WriteMem*/);
17459 // Make sure the newly-created LOAD is in the same position as Ld in
17460 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17461 // and update uses of Ld's output chain to use the TokenFactor.
17462 if (Ld->hasAnyUseOfValue(1)) {
17463 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17464 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17465 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17466 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17467 SDValue(ResNode.getNode(), 1));
17470 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17474 // Emit a zeroed vector and insert the desired subvector on its
17476 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17477 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17478 return DCI.CombineTo(N, InsV);
17481 //===--------------------------------------------------------------------===//
17482 // Combine some shuffles into subvector extracts and inserts:
17485 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17486 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17487 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17488 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17489 return DCI.CombineTo(N, InsV);
17492 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17493 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17494 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17495 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17496 return DCI.CombineTo(N, InsV);
17502 /// PerformShuffleCombine - Performs several different shuffle combines.
17503 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17504 TargetLowering::DAGCombinerInfo &DCI,
17505 const X86Subtarget *Subtarget) {
17507 SDValue N0 = N->getOperand(0);
17508 SDValue N1 = N->getOperand(1);
17509 EVT VT = N->getValueType(0);
17511 // Don't create instructions with illegal types after legalize types has run.
17512 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17513 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17516 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17517 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17518 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17519 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17521 // During Type Legalization, when promoting illegal vector types,
17522 // the backend might introduce new shuffle dag nodes and bitcasts.
17524 // This code performs the following transformation:
17525 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17526 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17528 // We do this only if both the bitcast and the BINOP dag nodes have
17529 // one use. Also, perform this transformation only if the new binary
17530 // operation is legal. This is to avoid introducing dag nodes that
17531 // potentially need to be further expanded (or custom lowered) into a
17532 // less optimal sequence of dag nodes.
17533 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17534 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17535 N0.getOpcode() == ISD::BITCAST) {
17536 SDValue BC0 = N0.getOperand(0);
17537 EVT SVT = BC0.getValueType();
17538 unsigned Opcode = BC0.getOpcode();
17539 unsigned NumElts = VT.getVectorNumElements();
17541 if (BC0.hasOneUse() && SVT.isVector() &&
17542 SVT.getVectorNumElements() * 2 == NumElts &&
17543 TLI.isOperationLegal(Opcode, VT)) {
17544 bool CanFold = false;
17556 unsigned SVTNumElts = SVT.getVectorNumElements();
17557 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17558 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17559 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17560 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17561 CanFold = SVOp->getMaskElt(i) < 0;
17564 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17565 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17566 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17567 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17572 // Only handle 128 wide vector from here on.
17573 if (!VT.is128BitVector())
17576 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17577 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17578 // consecutive, non-overlapping, and in the right order.
17579 SmallVector<SDValue, 16> Elts;
17580 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17581 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17583 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17586 /// PerformTruncateCombine - Converts truncate operation to
17587 /// a sequence of vector shuffle operations.
17588 /// It is possible when we truncate 256-bit vector to 128-bit vector
17589 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17590 TargetLowering::DAGCombinerInfo &DCI,
17591 const X86Subtarget *Subtarget) {
17595 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17596 /// specific shuffle of a load can be folded into a single element load.
17597 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17598 /// shuffles have been customed lowered so we need to handle those here.
17599 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17600 TargetLowering::DAGCombinerInfo &DCI) {
17601 if (DCI.isBeforeLegalizeOps())
17604 SDValue InVec = N->getOperand(0);
17605 SDValue EltNo = N->getOperand(1);
17607 if (!isa<ConstantSDNode>(EltNo))
17610 EVT VT = InVec.getValueType();
17612 bool HasShuffleIntoBitcast = false;
17613 if (InVec.getOpcode() == ISD::BITCAST) {
17614 // Don't duplicate a load with other uses.
17615 if (!InVec.hasOneUse())
17617 EVT BCVT = InVec.getOperand(0).getValueType();
17618 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17620 InVec = InVec.getOperand(0);
17621 HasShuffleIntoBitcast = true;
17624 if (!isTargetShuffle(InVec.getOpcode()))
17627 // Don't duplicate a load with other uses.
17628 if (!InVec.hasOneUse())
17631 SmallVector<int, 16> ShuffleMask;
17633 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17637 // Select the input vector, guarding against out of range extract vector.
17638 unsigned NumElems = VT.getVectorNumElements();
17639 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17640 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17641 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17642 : InVec.getOperand(1);
17644 // If inputs to shuffle are the same for both ops, then allow 2 uses
17645 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17647 if (LdNode.getOpcode() == ISD::BITCAST) {
17648 // Don't duplicate a load with other uses.
17649 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17652 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17653 LdNode = LdNode.getOperand(0);
17656 if (!ISD::isNormalLoad(LdNode.getNode()))
17659 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17661 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17664 if (HasShuffleIntoBitcast) {
17665 // If there's a bitcast before the shuffle, check if the load type and
17666 // alignment is valid.
17667 unsigned Align = LN0->getAlignment();
17668 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17669 unsigned NewAlign = TLI.getDataLayout()->
17670 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17672 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17676 // All checks match so transform back to vector_shuffle so that DAG combiner
17677 // can finish the job
17680 // Create shuffle node taking into account the case that its a unary shuffle
17681 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17682 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17683 InVec.getOperand(0), Shuffle,
17685 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17686 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17690 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17691 /// generation and convert it from being a bunch of shuffles and extracts
17692 /// to a simple store and scalar loads to extract the elements.
17693 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17694 TargetLowering::DAGCombinerInfo &DCI) {
17695 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17696 if (NewOp.getNode())
17699 SDValue InputVector = N->getOperand(0);
17701 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17702 // from mmx to v2i32 has a single usage.
17703 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17704 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17705 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17706 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17707 N->getValueType(0),
17708 InputVector.getNode()->getOperand(0));
17710 // Only operate on vectors of 4 elements, where the alternative shuffling
17711 // gets to be more expensive.
17712 if (InputVector.getValueType() != MVT::v4i32)
17715 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17716 // single use which is a sign-extend or zero-extend, and all elements are
17718 SmallVector<SDNode *, 4> Uses;
17719 unsigned ExtractedElements = 0;
17720 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17721 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17722 if (UI.getUse().getResNo() != InputVector.getResNo())
17725 SDNode *Extract = *UI;
17726 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17729 if (Extract->getValueType(0) != MVT::i32)
17731 if (!Extract->hasOneUse())
17733 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17734 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17736 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17739 // Record which element was extracted.
17740 ExtractedElements |=
17741 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17743 Uses.push_back(Extract);
17746 // If not all the elements were used, this may not be worthwhile.
17747 if (ExtractedElements != 15)
17750 // Ok, we've now decided to do the transformation.
17751 SDLoc dl(InputVector);
17753 // Store the value to a temporary stack slot.
17754 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17755 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17756 MachinePointerInfo(), false, false, 0);
17758 // Replace each use (extract) with a load of the appropriate element.
17759 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17760 UE = Uses.end(); UI != UE; ++UI) {
17761 SDNode *Extract = *UI;
17763 // cOMpute the element's address.
17764 SDValue Idx = Extract->getOperand(1);
17766 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17767 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17768 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17769 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17771 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17772 StackPtr, OffsetVal);
17774 // Load the scalar.
17775 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17776 ScalarAddr, MachinePointerInfo(),
17777 false, false, false, 0);
17779 // Replace the exact with the load.
17780 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17783 // The replacement was made in place; don't return anything.
17787 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17788 static std::pair<unsigned, bool>
17789 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17790 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17791 if (!VT.isVector())
17792 return std::make_pair(0, false);
17794 bool NeedSplit = false;
17795 switch (VT.getSimpleVT().SimpleTy) {
17796 default: return std::make_pair(0, false);
17800 if (!Subtarget->hasAVX2())
17802 if (!Subtarget->hasAVX())
17803 return std::make_pair(0, false);
17808 if (!Subtarget->hasSSE2())
17809 return std::make_pair(0, false);
17812 // SSE2 has only a small subset of the operations.
17813 bool hasUnsigned = Subtarget->hasSSE41() ||
17814 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17815 bool hasSigned = Subtarget->hasSSE41() ||
17816 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17818 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17821 // Check for x CC y ? x : y.
17822 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17823 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17828 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17831 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17834 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17837 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17839 // Check for x CC y ? y : x -- a min/max with reversed arms.
17840 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17841 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17846 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17849 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17852 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17855 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17859 return std::make_pair(Opc, NeedSplit);
17863 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17864 const X86Subtarget *Subtarget) {
17866 SDValue Cond = N->getOperand(0);
17867 SDValue LHS = N->getOperand(1);
17868 SDValue RHS = N->getOperand(2);
17870 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17871 SDValue CondSrc = Cond->getOperand(0);
17872 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17873 Cond = CondSrc->getOperand(0);
17876 MVT VT = N->getSimpleValueType(0);
17877 MVT EltVT = VT.getVectorElementType();
17878 unsigned NumElems = VT.getVectorNumElements();
17879 // There is no blend with immediate in AVX-512.
17880 if (VT.is512BitVector())
17883 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17885 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17888 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17891 unsigned MaskValue = 0;
17892 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
17895 SmallVector<int, 8> ShuffleMask(NumElems, -1);
17896 for (unsigned i = 0; i < NumElems; ++i) {
17897 // Be sure we emit undef where we can.
17898 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
17899 ShuffleMask[i] = -1;
17901 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
17904 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
17907 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17909 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17910 TargetLowering::DAGCombinerInfo &DCI,
17911 const X86Subtarget *Subtarget) {
17913 SDValue Cond = N->getOperand(0);
17914 // Get the LHS/RHS of the select.
17915 SDValue LHS = N->getOperand(1);
17916 SDValue RHS = N->getOperand(2);
17917 EVT VT = LHS.getValueType();
17918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17920 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17921 // instructions match the semantics of the common C idiom x<y?x:y but not
17922 // x<=y?x:y, because of how they handle negative zero (which can be
17923 // ignored in unsafe-math mode).
17924 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17925 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17926 (Subtarget->hasSSE2() ||
17927 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17928 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17930 unsigned Opcode = 0;
17931 // Check for x CC y ? x : y.
17932 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17933 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17937 // Converting this to a min would handle NaNs incorrectly, and swapping
17938 // the operands would cause it to handle comparisons between positive
17939 // and negative zero incorrectly.
17940 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17941 if (!DAG.getTarget().Options.UnsafeFPMath &&
17942 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17944 std::swap(LHS, RHS);
17946 Opcode = X86ISD::FMIN;
17949 // Converting this to a min would handle comparisons between positive
17950 // and negative zero incorrectly.
17951 if (!DAG.getTarget().Options.UnsafeFPMath &&
17952 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17954 Opcode = X86ISD::FMIN;
17957 // Converting this to a min would handle both negative zeros and NaNs
17958 // incorrectly, but we can swap the operands to fix both.
17959 std::swap(LHS, RHS);
17963 Opcode = X86ISD::FMIN;
17967 // Converting this to a max would handle comparisons between positive
17968 // and negative zero incorrectly.
17969 if (!DAG.getTarget().Options.UnsafeFPMath &&
17970 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17972 Opcode = X86ISD::FMAX;
17975 // Converting this to a max would handle NaNs incorrectly, and swapping
17976 // the operands would cause it to handle comparisons between positive
17977 // and negative zero incorrectly.
17978 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17979 if (!DAG.getTarget().Options.UnsafeFPMath &&
17980 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17982 std::swap(LHS, RHS);
17984 Opcode = X86ISD::FMAX;
17987 // Converting this to a max would handle both negative zeros and NaNs
17988 // incorrectly, but we can swap the operands to fix both.
17989 std::swap(LHS, RHS);
17993 Opcode = X86ISD::FMAX;
17996 // Check for x CC y ? y : x -- a min/max with reversed arms.
17997 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17998 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18002 // Converting this to a min would handle comparisons between positive
18003 // and negative zero incorrectly, and swapping the operands would
18004 // cause it to handle NaNs incorrectly.
18005 if (!DAG.getTarget().Options.UnsafeFPMath &&
18006 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18007 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18009 std::swap(LHS, RHS);
18011 Opcode = X86ISD::FMIN;
18014 // Converting this to a min would handle NaNs incorrectly.
18015 if (!DAG.getTarget().Options.UnsafeFPMath &&
18016 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18018 Opcode = X86ISD::FMIN;
18021 // Converting this to a min would handle both negative zeros and NaNs
18022 // incorrectly, but we can swap the operands to fix both.
18023 std::swap(LHS, RHS);
18027 Opcode = X86ISD::FMIN;
18031 // Converting this to a max would handle NaNs incorrectly.
18032 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18034 Opcode = X86ISD::FMAX;
18037 // Converting this to a max would handle comparisons between positive
18038 // and negative zero incorrectly, and swapping the operands would
18039 // cause it to handle NaNs incorrectly.
18040 if (!DAG.getTarget().Options.UnsafeFPMath &&
18041 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18042 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18044 std::swap(LHS, RHS);
18046 Opcode = X86ISD::FMAX;
18049 // Converting this to a max would handle both negative zeros and NaNs
18050 // incorrectly, but we can swap the operands to fix both.
18051 std::swap(LHS, RHS);
18055 Opcode = X86ISD::FMAX;
18061 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18064 EVT CondVT = Cond.getValueType();
18065 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18066 CondVT.getVectorElementType() == MVT::i1) {
18067 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18068 // lowering on AVX-512. In this case we convert it to
18069 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18070 // The same situation for all 128 and 256-bit vectors of i8 and i16
18071 EVT OpVT = LHS.getValueType();
18072 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18073 (OpVT.getVectorElementType() == MVT::i8 ||
18074 OpVT.getVectorElementType() == MVT::i16)) {
18075 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18076 DCI.AddToWorklist(Cond.getNode());
18077 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18080 // If this is a select between two integer constants, try to do some
18082 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18083 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18084 // Don't do this for crazy integer types.
18085 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18086 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18087 // so that TrueC (the true value) is larger than FalseC.
18088 bool NeedsCondInvert = false;
18090 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18091 // Efficiently invertible.
18092 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18093 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18094 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18095 NeedsCondInvert = true;
18096 std::swap(TrueC, FalseC);
18099 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18100 if (FalseC->getAPIntValue() == 0 &&
18101 TrueC->getAPIntValue().isPowerOf2()) {
18102 if (NeedsCondInvert) // Invert the condition if needed.
18103 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18104 DAG.getConstant(1, Cond.getValueType()));
18106 // Zero extend the condition if needed.
18107 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18109 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18110 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18111 DAG.getConstant(ShAmt, MVT::i8));
18114 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18115 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18116 if (NeedsCondInvert) // Invert the condition if needed.
18117 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18118 DAG.getConstant(1, Cond.getValueType()));
18120 // Zero extend the condition if needed.
18121 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18122 FalseC->getValueType(0), Cond);
18123 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18124 SDValue(FalseC, 0));
18127 // Optimize cases that will turn into an LEA instruction. This requires
18128 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18129 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18130 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18131 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18133 bool isFastMultiplier = false;
18135 switch ((unsigned char)Diff) {
18137 case 1: // result = add base, cond
18138 case 2: // result = lea base( , cond*2)
18139 case 3: // result = lea base(cond, cond*2)
18140 case 4: // result = lea base( , cond*4)
18141 case 5: // result = lea base(cond, cond*4)
18142 case 8: // result = lea base( , cond*8)
18143 case 9: // result = lea base(cond, cond*8)
18144 isFastMultiplier = true;
18149 if (isFastMultiplier) {
18150 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18151 if (NeedsCondInvert) // Invert the condition if needed.
18152 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18153 DAG.getConstant(1, Cond.getValueType()));
18155 // Zero extend the condition if needed.
18156 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18158 // Scale the condition by the difference.
18160 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18161 DAG.getConstant(Diff, Cond.getValueType()));
18163 // Add the base if non-zero.
18164 if (FalseC->getAPIntValue() != 0)
18165 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18166 SDValue(FalseC, 0));
18173 // Canonicalize max and min:
18174 // (x > y) ? x : y -> (x >= y) ? x : y
18175 // (x < y) ? x : y -> (x <= y) ? x : y
18176 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18177 // the need for an extra compare
18178 // against zero. e.g.
18179 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18181 // testl %edi, %edi
18183 // cmovgl %edi, %eax
18187 // cmovsl %eax, %edi
18188 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18189 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18190 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18191 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18196 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18197 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18198 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18199 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18204 // Early exit check
18205 if (!TLI.isTypeLegal(VT))
18208 // Match VSELECTs into subs with unsigned saturation.
18209 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18210 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18211 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18212 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18213 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18215 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18216 // left side invert the predicate to simplify logic below.
18218 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18220 CC = ISD::getSetCCInverse(CC, true);
18221 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18225 if (Other.getNode() && Other->getNumOperands() == 2 &&
18226 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18227 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18228 SDValue CondRHS = Cond->getOperand(1);
18230 // Look for a general sub with unsigned saturation first.
18231 // x >= y ? x-y : 0 --> subus x, y
18232 // x > y ? x-y : 0 --> subus x, y
18233 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18234 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18235 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18237 // If the RHS is a constant we have to reverse the const canonicalization.
18238 // x > C-1 ? x+-C : 0 --> subus x, C
18239 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18240 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18241 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18242 if (CondRHS.getConstantOperandVal(0) == -A-1)
18243 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18244 DAG.getConstant(-A, VT));
18247 // Another special case: If C was a sign bit, the sub has been
18248 // canonicalized into a xor.
18249 // FIXME: Would it be better to use computeKnownBits to determine whether
18250 // it's safe to decanonicalize the xor?
18251 // x s< 0 ? x^C : 0 --> subus x, C
18252 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18253 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18254 isSplatVector(OpRHS.getNode())) {
18255 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18257 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18262 // Try to match a min/max vector operation.
18263 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18264 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18265 unsigned Opc = ret.first;
18266 bool NeedSplit = ret.second;
18268 if (Opc && NeedSplit) {
18269 unsigned NumElems = VT.getVectorNumElements();
18270 // Extract the LHS vectors
18271 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18272 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18274 // Extract the RHS vectors
18275 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18276 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18278 // Create min/max for each subvector
18279 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18280 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18282 // Merge the result
18283 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18285 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18288 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18289 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18290 // Check if SETCC has already been promoted
18291 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18292 // Check that condition value type matches vselect operand type
18295 assert(Cond.getValueType().isVector() &&
18296 "vector select expects a vector selector!");
18298 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18299 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18301 if (!TValIsAllOnes && !FValIsAllZeros) {
18302 // Try invert the condition if true value is not all 1s and false value
18304 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18305 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18307 if (TValIsAllZeros || FValIsAllOnes) {
18308 SDValue CC = Cond.getOperand(2);
18309 ISD::CondCode NewCC =
18310 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18311 Cond.getOperand(0).getValueType().isInteger());
18312 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18313 std::swap(LHS, RHS);
18314 TValIsAllOnes = FValIsAllOnes;
18315 FValIsAllZeros = TValIsAllZeros;
18319 if (TValIsAllOnes || FValIsAllZeros) {
18322 if (TValIsAllOnes && FValIsAllZeros)
18324 else if (TValIsAllOnes)
18325 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18326 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18327 else if (FValIsAllZeros)
18328 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18329 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18331 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18335 // Try to fold this VSELECT into a MOVSS/MOVSD
18336 if (N->getOpcode() == ISD::VSELECT &&
18337 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18338 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18339 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18340 bool CanFold = false;
18341 unsigned NumElems = Cond.getNumOperands();
18345 if (isZero(Cond.getOperand(0))) {
18348 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18349 // fold (vselect <0,-1> -> (movsd A, B)
18350 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18351 CanFold = isAllOnes(Cond.getOperand(i));
18352 } else if (isAllOnes(Cond.getOperand(0))) {
18356 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18357 // fold (vselect <-1,0> -> (movsd B, A)
18358 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18359 CanFold = isZero(Cond.getOperand(i));
18363 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18364 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18365 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18368 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18369 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18370 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18371 // (v2i64 (bitcast B)))))
18373 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18374 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18375 // (v2f64 (bitcast B)))))
18377 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18378 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18379 // (v2i64 (bitcast A)))))
18381 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18382 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18383 // (v2f64 (bitcast A)))))
18385 CanFold = (isZero(Cond.getOperand(0)) &&
18386 isZero(Cond.getOperand(1)) &&
18387 isAllOnes(Cond.getOperand(2)) &&
18388 isAllOnes(Cond.getOperand(3)));
18390 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18391 isAllOnes(Cond.getOperand(1)) &&
18392 isZero(Cond.getOperand(2)) &&
18393 isZero(Cond.getOperand(3))) {
18395 std::swap(LHS, RHS);
18399 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18400 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18401 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18402 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18404 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18410 // If we know that this node is legal then we know that it is going to be
18411 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18412 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18413 // to simplify previous instructions.
18414 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18415 !DCI.isBeforeLegalize() &&
18416 // We explicitly check against v8i16 and v16i16 because, although
18417 // they're marked as Custom, they might only be legal when Cond is a
18418 // build_vector of constants. This will be taken care in a later
18420 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18421 VT != MVT::v8i16)) {
18422 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18424 // Don't optimize vector selects that map to mask-registers.
18428 // Check all uses of that condition operand to check whether it will be
18429 // consumed by non-BLEND instructions, which may depend on all bits are set
18431 for (SDNode::use_iterator I = Cond->use_begin(),
18432 E = Cond->use_end(); I != E; ++I)
18433 if (I->getOpcode() != ISD::VSELECT)
18434 // TODO: Add other opcodes eventually lowered into BLEND.
18437 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18438 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18440 APInt KnownZero, KnownOne;
18441 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18442 DCI.isBeforeLegalizeOps());
18443 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18444 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18445 DCI.CommitTargetLoweringOpt(TLO);
18448 // We should generate an X86ISD::BLENDI from a vselect if its argument
18449 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18450 // constants. This specific pattern gets generated when we split a
18451 // selector for a 512 bit vector in a machine without AVX512 (but with
18452 // 256-bit vectors), during legalization:
18454 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18456 // Iff we find this pattern and the build_vectors are built from
18457 // constants, we translate the vselect into a shuffle_vector that we
18458 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18459 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18460 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18461 if (Shuffle.getNode())
18468 // Check whether a boolean test is testing a boolean value generated by
18469 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18472 // Simplify the following patterns:
18473 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18474 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18475 // to (Op EFLAGS Cond)
18477 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18478 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18479 // to (Op EFLAGS !Cond)
18481 // where Op could be BRCOND or CMOV.
18483 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18484 // Quit if not CMP and SUB with its value result used.
18485 if (Cmp.getOpcode() != X86ISD::CMP &&
18486 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18489 // Quit if not used as a boolean value.
18490 if (CC != X86::COND_E && CC != X86::COND_NE)
18493 // Check CMP operands. One of them should be 0 or 1 and the other should be
18494 // an SetCC or extended from it.
18495 SDValue Op1 = Cmp.getOperand(0);
18496 SDValue Op2 = Cmp.getOperand(1);
18499 const ConstantSDNode* C = nullptr;
18500 bool needOppositeCond = (CC == X86::COND_E);
18501 bool checkAgainstTrue = false; // Is it a comparison against 1?
18503 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18505 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18507 else // Quit if all operands are not constants.
18510 if (C->getZExtValue() == 1) {
18511 needOppositeCond = !needOppositeCond;
18512 checkAgainstTrue = true;
18513 } else if (C->getZExtValue() != 0)
18514 // Quit if the constant is neither 0 or 1.
18517 bool truncatedToBoolWithAnd = false;
18518 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18519 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18520 SetCC.getOpcode() == ISD::TRUNCATE ||
18521 SetCC.getOpcode() == ISD::AND) {
18522 if (SetCC.getOpcode() == ISD::AND) {
18524 ConstantSDNode *CS;
18525 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18526 CS->getZExtValue() == 1)
18528 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18529 CS->getZExtValue() == 1)
18533 SetCC = SetCC.getOperand(OpIdx);
18534 truncatedToBoolWithAnd = true;
18536 SetCC = SetCC.getOperand(0);
18539 switch (SetCC.getOpcode()) {
18540 case X86ISD::SETCC_CARRY:
18541 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18542 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18543 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18544 // truncated to i1 using 'and'.
18545 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18547 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18548 "Invalid use of SETCC_CARRY!");
18550 case X86ISD::SETCC:
18551 // Set the condition code or opposite one if necessary.
18552 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18553 if (needOppositeCond)
18554 CC = X86::GetOppositeBranchCondition(CC);
18555 return SetCC.getOperand(1);
18556 case X86ISD::CMOV: {
18557 // Check whether false/true value has canonical one, i.e. 0 or 1.
18558 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18559 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18560 // Quit if true value is not a constant.
18563 // Quit if false value is not a constant.
18565 SDValue Op = SetCC.getOperand(0);
18566 // Skip 'zext' or 'trunc' node.
18567 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18568 Op.getOpcode() == ISD::TRUNCATE)
18569 Op = Op.getOperand(0);
18570 // A special case for rdrand/rdseed, where 0 is set if false cond is
18572 if ((Op.getOpcode() != X86ISD::RDRAND &&
18573 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18576 // Quit if false value is not the constant 0 or 1.
18577 bool FValIsFalse = true;
18578 if (FVal && FVal->getZExtValue() != 0) {
18579 if (FVal->getZExtValue() != 1)
18581 // If FVal is 1, opposite cond is needed.
18582 needOppositeCond = !needOppositeCond;
18583 FValIsFalse = false;
18585 // Quit if TVal is not the constant opposite of FVal.
18586 if (FValIsFalse && TVal->getZExtValue() != 1)
18588 if (!FValIsFalse && TVal->getZExtValue() != 0)
18590 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18591 if (needOppositeCond)
18592 CC = X86::GetOppositeBranchCondition(CC);
18593 return SetCC.getOperand(3);
18600 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18601 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18602 TargetLowering::DAGCombinerInfo &DCI,
18603 const X86Subtarget *Subtarget) {
18606 // If the flag operand isn't dead, don't touch this CMOV.
18607 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18610 SDValue FalseOp = N->getOperand(0);
18611 SDValue TrueOp = N->getOperand(1);
18612 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18613 SDValue Cond = N->getOperand(3);
18615 if (CC == X86::COND_E || CC == X86::COND_NE) {
18616 switch (Cond.getOpcode()) {
18620 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18621 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18622 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18628 Flags = checkBoolTestSetCCCombine(Cond, CC);
18629 if (Flags.getNode() &&
18630 // Extra check as FCMOV only supports a subset of X86 cond.
18631 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18632 SDValue Ops[] = { FalseOp, TrueOp,
18633 DAG.getConstant(CC, MVT::i8), Flags };
18634 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18637 // If this is a select between two integer constants, try to do some
18638 // optimizations. Note that the operands are ordered the opposite of SELECT
18640 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18641 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18642 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18643 // larger than FalseC (the false value).
18644 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18645 CC = X86::GetOppositeBranchCondition(CC);
18646 std::swap(TrueC, FalseC);
18647 std::swap(TrueOp, FalseOp);
18650 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18651 // This is efficient for any integer data type (including i8/i16) and
18653 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18654 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18655 DAG.getConstant(CC, MVT::i8), Cond);
18657 // Zero extend the condition if needed.
18658 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18660 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18661 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18662 DAG.getConstant(ShAmt, MVT::i8));
18663 if (N->getNumValues() == 2) // Dead flag value?
18664 return DCI.CombineTo(N, Cond, SDValue());
18668 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18669 // for any integer data type, including i8/i16.
18670 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18671 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18672 DAG.getConstant(CC, MVT::i8), Cond);
18674 // Zero extend the condition if needed.
18675 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18676 FalseC->getValueType(0), Cond);
18677 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18678 SDValue(FalseC, 0));
18680 if (N->getNumValues() == 2) // Dead flag value?
18681 return DCI.CombineTo(N, Cond, SDValue());
18685 // Optimize cases that will turn into an LEA instruction. This requires
18686 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18687 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18688 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18689 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18691 bool isFastMultiplier = false;
18693 switch ((unsigned char)Diff) {
18695 case 1: // result = add base, cond
18696 case 2: // result = lea base( , cond*2)
18697 case 3: // result = lea base(cond, cond*2)
18698 case 4: // result = lea base( , cond*4)
18699 case 5: // result = lea base(cond, cond*4)
18700 case 8: // result = lea base( , cond*8)
18701 case 9: // result = lea base(cond, cond*8)
18702 isFastMultiplier = true;
18707 if (isFastMultiplier) {
18708 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18709 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18710 DAG.getConstant(CC, MVT::i8), Cond);
18711 // Zero extend the condition if needed.
18712 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18714 // Scale the condition by the difference.
18716 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18717 DAG.getConstant(Diff, Cond.getValueType()));
18719 // Add the base if non-zero.
18720 if (FalseC->getAPIntValue() != 0)
18721 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18722 SDValue(FalseC, 0));
18723 if (N->getNumValues() == 2) // Dead flag value?
18724 return DCI.CombineTo(N, Cond, SDValue());
18731 // Handle these cases:
18732 // (select (x != c), e, c) -> select (x != c), e, x),
18733 // (select (x == c), c, e) -> select (x == c), x, e)
18734 // where the c is an integer constant, and the "select" is the combination
18735 // of CMOV and CMP.
18737 // The rationale for this change is that the conditional-move from a constant
18738 // needs two instructions, however, conditional-move from a register needs
18739 // only one instruction.
18741 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18742 // some instruction-combining opportunities. This opt needs to be
18743 // postponed as late as possible.
18745 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18746 // the DCI.xxxx conditions are provided to postpone the optimization as
18747 // late as possible.
18749 ConstantSDNode *CmpAgainst = nullptr;
18750 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18751 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18752 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18754 if (CC == X86::COND_NE &&
18755 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18756 CC = X86::GetOppositeBranchCondition(CC);
18757 std::swap(TrueOp, FalseOp);
18760 if (CC == X86::COND_E &&
18761 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18762 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18763 DAG.getConstant(CC, MVT::i8), Cond };
18764 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18772 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18773 const X86Subtarget *Subtarget) {
18774 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18776 default: return SDValue();
18777 // SSE/AVX/AVX2 blend intrinsics.
18778 case Intrinsic::x86_avx2_pblendvb:
18779 case Intrinsic::x86_avx2_pblendw:
18780 case Intrinsic::x86_avx2_pblendd_128:
18781 case Intrinsic::x86_avx2_pblendd_256:
18782 // Don't try to simplify this intrinsic if we don't have AVX2.
18783 if (!Subtarget->hasAVX2())
18786 case Intrinsic::x86_avx_blend_pd_256:
18787 case Intrinsic::x86_avx_blend_ps_256:
18788 case Intrinsic::x86_avx_blendv_pd_256:
18789 case Intrinsic::x86_avx_blendv_ps_256:
18790 // Don't try to simplify this intrinsic if we don't have AVX.
18791 if (!Subtarget->hasAVX())
18794 case Intrinsic::x86_sse41_pblendw:
18795 case Intrinsic::x86_sse41_blendpd:
18796 case Intrinsic::x86_sse41_blendps:
18797 case Intrinsic::x86_sse41_blendvps:
18798 case Intrinsic::x86_sse41_blendvpd:
18799 case Intrinsic::x86_sse41_pblendvb: {
18800 SDValue Op0 = N->getOperand(1);
18801 SDValue Op1 = N->getOperand(2);
18802 SDValue Mask = N->getOperand(3);
18804 // Don't try to simplify this intrinsic if we don't have SSE4.1.
18805 if (!Subtarget->hasSSE41())
18808 // fold (blend A, A, Mask) -> A
18811 // fold (blend A, B, allZeros) -> A
18812 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18814 // fold (blend A, B, allOnes) -> B
18815 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18818 // Simplify the case where the mask is a constant i32 value.
18819 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18820 if (C->isNullValue())
18822 if (C->isAllOnesValue())
18827 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18828 case Intrinsic::x86_sse2_psrai_w:
18829 case Intrinsic::x86_sse2_psrai_d:
18830 case Intrinsic::x86_avx2_psrai_w:
18831 case Intrinsic::x86_avx2_psrai_d:
18832 case Intrinsic::x86_sse2_psra_w:
18833 case Intrinsic::x86_sse2_psra_d:
18834 case Intrinsic::x86_avx2_psra_w:
18835 case Intrinsic::x86_avx2_psra_d: {
18836 SDValue Op0 = N->getOperand(1);
18837 SDValue Op1 = N->getOperand(2);
18838 EVT VT = Op0.getValueType();
18839 assert(VT.isVector() && "Expected a vector type!");
18841 if (isa<BuildVectorSDNode>(Op1))
18842 Op1 = Op1.getOperand(0);
18844 if (!isa<ConstantSDNode>(Op1))
18847 EVT SVT = VT.getVectorElementType();
18848 unsigned SVTBits = SVT.getSizeInBits();
18850 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18851 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18852 uint64_t ShAmt = C.getZExtValue();
18854 // Don't try to convert this shift into a ISD::SRA if the shift
18855 // count is bigger than or equal to the element size.
18856 if (ShAmt >= SVTBits)
18859 // Trivial case: if the shift count is zero, then fold this
18860 // into the first operand.
18864 // Replace this packed shift intrinsic with a target independent
18866 SDValue Splat = DAG.getConstant(C, VT);
18867 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18872 /// PerformMulCombine - Optimize a single multiply with constant into two
18873 /// in order to implement it with two cheaper instructions, e.g.
18874 /// LEA + SHL, LEA + LEA.
18875 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18876 TargetLowering::DAGCombinerInfo &DCI) {
18877 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18880 EVT VT = N->getValueType(0);
18881 if (VT != MVT::i64)
18884 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18887 uint64_t MulAmt = C->getZExtValue();
18888 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18891 uint64_t MulAmt1 = 0;
18892 uint64_t MulAmt2 = 0;
18893 if ((MulAmt % 9) == 0) {
18895 MulAmt2 = MulAmt / 9;
18896 } else if ((MulAmt % 5) == 0) {
18898 MulAmt2 = MulAmt / 5;
18899 } else if ((MulAmt % 3) == 0) {
18901 MulAmt2 = MulAmt / 3;
18904 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18907 if (isPowerOf2_64(MulAmt2) &&
18908 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18909 // If second multiplifer is pow2, issue it first. We want the multiply by
18910 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18912 std::swap(MulAmt1, MulAmt2);
18915 if (isPowerOf2_64(MulAmt1))
18916 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18917 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18919 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18920 DAG.getConstant(MulAmt1, VT));
18922 if (isPowerOf2_64(MulAmt2))
18923 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18924 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18926 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18927 DAG.getConstant(MulAmt2, VT));
18929 // Do not add new nodes to DAG combiner worklist.
18930 DCI.CombineTo(N, NewMul, false);
18935 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18936 SDValue N0 = N->getOperand(0);
18937 SDValue N1 = N->getOperand(1);
18938 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18939 EVT VT = N0.getValueType();
18941 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18942 // since the result of setcc_c is all zero's or all ones.
18943 if (VT.isInteger() && !VT.isVector() &&
18944 N1C && N0.getOpcode() == ISD::AND &&
18945 N0.getOperand(1).getOpcode() == ISD::Constant) {
18946 SDValue N00 = N0.getOperand(0);
18947 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18948 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18949 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18950 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18951 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18952 APInt ShAmt = N1C->getAPIntValue();
18953 Mask = Mask.shl(ShAmt);
18955 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18956 N00, DAG.getConstant(Mask, VT));
18960 // Hardware support for vector shifts is sparse which makes us scalarize the
18961 // vector operations in many cases. Also, on sandybridge ADD is faster than
18963 // (shl V, 1) -> add V,V
18964 if (isSplatVector(N1.getNode())) {
18965 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18966 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18967 // We shift all of the values by one. In many cases we do not have
18968 // hardware support for this operation. This is better expressed as an ADD
18970 if (N1C && (1 == N1C->getZExtValue())) {
18971 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18978 /// \brief Returns a vector of 0s if the node in input is a vector logical
18979 /// shift by a constant amount which is known to be bigger than or equal
18980 /// to the vector element size in bits.
18981 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18982 const X86Subtarget *Subtarget) {
18983 EVT VT = N->getValueType(0);
18985 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18986 (!Subtarget->hasInt256() ||
18987 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18990 SDValue Amt = N->getOperand(1);
18992 if (isSplatVector(Amt.getNode())) {
18993 SDValue SclrAmt = Amt->getOperand(0);
18994 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18995 APInt ShiftAmt = C->getAPIntValue();
18996 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18998 // SSE2/AVX2 logical shifts always return a vector of 0s
18999 // if the shift amount is bigger than or equal to
19000 // the element size. The constant shift amount will be
19001 // encoded as a 8-bit immediate.
19002 if (ShiftAmt.trunc(8).uge(MaxAmount))
19003 return getZeroVector(VT, Subtarget, DAG, DL);
19010 /// PerformShiftCombine - Combine shifts.
19011 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19012 TargetLowering::DAGCombinerInfo &DCI,
19013 const X86Subtarget *Subtarget) {
19014 if (N->getOpcode() == ISD::SHL) {
19015 SDValue V = PerformSHLCombine(N, DAG);
19016 if (V.getNode()) return V;
19019 if (N->getOpcode() != ISD::SRA) {
19020 // Try to fold this logical shift into a zero vector.
19021 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19022 if (V.getNode()) return V;
19028 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19029 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19030 // and friends. Likewise for OR -> CMPNEQSS.
19031 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19032 TargetLowering::DAGCombinerInfo &DCI,
19033 const X86Subtarget *Subtarget) {
19036 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19037 // we're requiring SSE2 for both.
19038 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19039 SDValue N0 = N->getOperand(0);
19040 SDValue N1 = N->getOperand(1);
19041 SDValue CMP0 = N0->getOperand(1);
19042 SDValue CMP1 = N1->getOperand(1);
19045 // The SETCCs should both refer to the same CMP.
19046 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19049 SDValue CMP00 = CMP0->getOperand(0);
19050 SDValue CMP01 = CMP0->getOperand(1);
19051 EVT VT = CMP00.getValueType();
19053 if (VT == MVT::f32 || VT == MVT::f64) {
19054 bool ExpectingFlags = false;
19055 // Check for any users that want flags:
19056 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19057 !ExpectingFlags && UI != UE; ++UI)
19058 switch (UI->getOpcode()) {
19063 ExpectingFlags = true;
19065 case ISD::CopyToReg:
19066 case ISD::SIGN_EXTEND:
19067 case ISD::ZERO_EXTEND:
19068 case ISD::ANY_EXTEND:
19072 if (!ExpectingFlags) {
19073 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19074 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19076 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19077 X86::CondCode tmp = cc0;
19082 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19083 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19084 // FIXME: need symbolic constants for these magic numbers.
19085 // See X86ATTInstPrinter.cpp:printSSECC().
19086 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19087 if (Subtarget->hasAVX512()) {
19088 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19089 CMP01, DAG.getConstant(x86cc, MVT::i8));
19090 if (N->getValueType(0) != MVT::i1)
19091 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19095 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19096 CMP00.getValueType(), CMP00, CMP01,
19097 DAG.getConstant(x86cc, MVT::i8));
19099 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19100 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19102 if (is64BitFP && !Subtarget->is64Bit()) {
19103 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19104 // 64-bit integer, since that's not a legal type. Since
19105 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19106 // bits, but can do this little dance to extract the lowest 32 bits
19107 // and work with those going forward.
19108 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19110 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19112 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19113 Vector32, DAG.getIntPtrConstant(0));
19117 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19118 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19119 DAG.getConstant(1, IntVT));
19120 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19121 return OneBitOfTruth;
19129 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19130 /// so it can be folded inside ANDNP.
19131 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19132 EVT VT = N->getValueType(0);
19134 // Match direct AllOnes for 128 and 256-bit vectors
19135 if (ISD::isBuildVectorAllOnes(N))
19138 // Look through a bit convert.
19139 if (N->getOpcode() == ISD::BITCAST)
19140 N = N->getOperand(0).getNode();
19142 // Sometimes the operand may come from a insert_subvector building a 256-bit
19144 if (VT.is256BitVector() &&
19145 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19146 SDValue V1 = N->getOperand(0);
19147 SDValue V2 = N->getOperand(1);
19149 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19150 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19151 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19152 ISD::isBuildVectorAllOnes(V2.getNode()))
19159 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19160 // register. In most cases we actually compare or select YMM-sized registers
19161 // and mixing the two types creates horrible code. This method optimizes
19162 // some of the transition sequences.
19163 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19164 TargetLowering::DAGCombinerInfo &DCI,
19165 const X86Subtarget *Subtarget) {
19166 EVT VT = N->getValueType(0);
19167 if (!VT.is256BitVector())
19170 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19171 N->getOpcode() == ISD::ZERO_EXTEND ||
19172 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19174 SDValue Narrow = N->getOperand(0);
19175 EVT NarrowVT = Narrow->getValueType(0);
19176 if (!NarrowVT.is128BitVector())
19179 if (Narrow->getOpcode() != ISD::XOR &&
19180 Narrow->getOpcode() != ISD::AND &&
19181 Narrow->getOpcode() != ISD::OR)
19184 SDValue N0 = Narrow->getOperand(0);
19185 SDValue N1 = Narrow->getOperand(1);
19188 // The Left side has to be a trunc.
19189 if (N0.getOpcode() != ISD::TRUNCATE)
19192 // The type of the truncated inputs.
19193 EVT WideVT = N0->getOperand(0)->getValueType(0);
19197 // The right side has to be a 'trunc' or a constant vector.
19198 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19199 bool RHSConst = (isSplatVector(N1.getNode()) &&
19200 isa<ConstantSDNode>(N1->getOperand(0)));
19201 if (!RHSTrunc && !RHSConst)
19204 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19206 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19209 // Set N0 and N1 to hold the inputs to the new wide operation.
19210 N0 = N0->getOperand(0);
19212 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19213 N1->getOperand(0));
19214 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19215 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19216 } else if (RHSTrunc) {
19217 N1 = N1->getOperand(0);
19220 // Generate the wide operation.
19221 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19222 unsigned Opcode = N->getOpcode();
19224 case ISD::ANY_EXTEND:
19226 case ISD::ZERO_EXTEND: {
19227 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19228 APInt Mask = APInt::getAllOnesValue(InBits);
19229 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19230 return DAG.getNode(ISD::AND, DL, VT,
19231 Op, DAG.getConstant(Mask, VT));
19233 case ISD::SIGN_EXTEND:
19234 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19235 Op, DAG.getValueType(NarrowVT));
19237 llvm_unreachable("Unexpected opcode");
19241 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19242 TargetLowering::DAGCombinerInfo &DCI,
19243 const X86Subtarget *Subtarget) {
19244 EVT VT = N->getValueType(0);
19245 if (DCI.isBeforeLegalizeOps())
19248 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19252 // Create BEXTR instructions
19253 // BEXTR is ((X >> imm) & (2**size-1))
19254 if (VT == MVT::i32 || VT == MVT::i64) {
19255 SDValue N0 = N->getOperand(0);
19256 SDValue N1 = N->getOperand(1);
19259 // Check for BEXTR.
19260 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19261 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19262 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19263 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19264 if (MaskNode && ShiftNode) {
19265 uint64_t Mask = MaskNode->getZExtValue();
19266 uint64_t Shift = ShiftNode->getZExtValue();
19267 if (isMask_64(Mask)) {
19268 uint64_t MaskSize = CountPopulation_64(Mask);
19269 if (Shift + MaskSize <= VT.getSizeInBits())
19270 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19271 DAG.getConstant(Shift | (MaskSize << 8), VT));
19279 // Want to form ANDNP nodes:
19280 // 1) In the hopes of then easily combining them with OR and AND nodes
19281 // to form PBLEND/PSIGN.
19282 // 2) To match ANDN packed intrinsics
19283 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19286 SDValue N0 = N->getOperand(0);
19287 SDValue N1 = N->getOperand(1);
19290 // Check LHS for vnot
19291 if (N0.getOpcode() == ISD::XOR &&
19292 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19293 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19294 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19296 // Check RHS for vnot
19297 if (N1.getOpcode() == ISD::XOR &&
19298 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19299 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19300 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19305 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19306 TargetLowering::DAGCombinerInfo &DCI,
19307 const X86Subtarget *Subtarget) {
19308 if (DCI.isBeforeLegalizeOps())
19311 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19315 SDValue N0 = N->getOperand(0);
19316 SDValue N1 = N->getOperand(1);
19317 EVT VT = N->getValueType(0);
19319 // look for psign/blend
19320 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19321 if (!Subtarget->hasSSSE3() ||
19322 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19325 // Canonicalize pandn to RHS
19326 if (N0.getOpcode() == X86ISD::ANDNP)
19328 // or (and (m, y), (pandn m, x))
19329 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19330 SDValue Mask = N1.getOperand(0);
19331 SDValue X = N1.getOperand(1);
19333 if (N0.getOperand(0) == Mask)
19334 Y = N0.getOperand(1);
19335 if (N0.getOperand(1) == Mask)
19336 Y = N0.getOperand(0);
19338 // Check to see if the mask appeared in both the AND and ANDNP and
19342 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19343 // Look through mask bitcast.
19344 if (Mask.getOpcode() == ISD::BITCAST)
19345 Mask = Mask.getOperand(0);
19346 if (X.getOpcode() == ISD::BITCAST)
19347 X = X.getOperand(0);
19348 if (Y.getOpcode() == ISD::BITCAST)
19349 Y = Y.getOperand(0);
19351 EVT MaskVT = Mask.getValueType();
19353 // Validate that the Mask operand is a vector sra node.
19354 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19355 // there is no psrai.b
19356 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19357 unsigned SraAmt = ~0;
19358 if (Mask.getOpcode() == ISD::SRA) {
19359 SDValue Amt = Mask.getOperand(1);
19360 if (isSplatVector(Amt.getNode())) {
19361 SDValue SclrAmt = Amt->getOperand(0);
19362 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19363 SraAmt = C->getZExtValue();
19365 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19366 SDValue SraC = Mask.getOperand(1);
19367 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19369 if ((SraAmt + 1) != EltBits)
19374 // Now we know we at least have a plendvb with the mask val. See if
19375 // we can form a psignb/w/d.
19376 // psign = x.type == y.type == mask.type && y = sub(0, x);
19377 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19378 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19379 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19380 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19381 "Unsupported VT for PSIGN");
19382 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19383 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19385 // PBLENDVB only available on SSE 4.1
19386 if (!Subtarget->hasSSE41())
19389 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19391 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19392 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19393 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19394 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19395 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19399 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19402 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19403 MachineFunction &MF = DAG.getMachineFunction();
19404 bool OptForSize = MF.getFunction()->getAttributes().
19405 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19407 // SHLD/SHRD instructions have lower register pressure, but on some
19408 // platforms they have higher latency than the equivalent
19409 // series of shifts/or that would otherwise be generated.
19410 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19411 // have higher latencies and we are not optimizing for size.
19412 if (!OptForSize && Subtarget->isSHLDSlow())
19415 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19417 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19419 if (!N0.hasOneUse() || !N1.hasOneUse())
19422 SDValue ShAmt0 = N0.getOperand(1);
19423 if (ShAmt0.getValueType() != MVT::i8)
19425 SDValue ShAmt1 = N1.getOperand(1);
19426 if (ShAmt1.getValueType() != MVT::i8)
19428 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19429 ShAmt0 = ShAmt0.getOperand(0);
19430 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19431 ShAmt1 = ShAmt1.getOperand(0);
19434 unsigned Opc = X86ISD::SHLD;
19435 SDValue Op0 = N0.getOperand(0);
19436 SDValue Op1 = N1.getOperand(0);
19437 if (ShAmt0.getOpcode() == ISD::SUB) {
19438 Opc = X86ISD::SHRD;
19439 std::swap(Op0, Op1);
19440 std::swap(ShAmt0, ShAmt1);
19443 unsigned Bits = VT.getSizeInBits();
19444 if (ShAmt1.getOpcode() == ISD::SUB) {
19445 SDValue Sum = ShAmt1.getOperand(0);
19446 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19447 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19448 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19449 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19450 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19451 return DAG.getNode(Opc, DL, VT,
19453 DAG.getNode(ISD::TRUNCATE, DL,
19456 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19457 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19459 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19460 return DAG.getNode(Opc, DL, VT,
19461 N0.getOperand(0), N1.getOperand(0),
19462 DAG.getNode(ISD::TRUNCATE, DL,
19469 // Generate NEG and CMOV for integer abs.
19470 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19471 EVT VT = N->getValueType(0);
19473 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19474 // 8-bit integer abs to NEG and CMOV.
19475 if (VT.isInteger() && VT.getSizeInBits() == 8)
19478 SDValue N0 = N->getOperand(0);
19479 SDValue N1 = N->getOperand(1);
19482 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19483 // and change it to SUB and CMOV.
19484 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19485 N0.getOpcode() == ISD::ADD &&
19486 N0.getOperand(1) == N1 &&
19487 N1.getOpcode() == ISD::SRA &&
19488 N1.getOperand(0) == N0.getOperand(0))
19489 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19490 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19491 // Generate SUB & CMOV.
19492 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19493 DAG.getConstant(0, VT), N0.getOperand(0));
19495 SDValue Ops[] = { N0.getOperand(0), Neg,
19496 DAG.getConstant(X86::COND_GE, MVT::i8),
19497 SDValue(Neg.getNode(), 1) };
19498 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19503 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19504 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19505 TargetLowering::DAGCombinerInfo &DCI,
19506 const X86Subtarget *Subtarget) {
19507 if (DCI.isBeforeLegalizeOps())
19510 if (Subtarget->hasCMov()) {
19511 SDValue RV = performIntegerAbsCombine(N, DAG);
19519 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19520 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19521 TargetLowering::DAGCombinerInfo &DCI,
19522 const X86Subtarget *Subtarget) {
19523 LoadSDNode *Ld = cast<LoadSDNode>(N);
19524 EVT RegVT = Ld->getValueType(0);
19525 EVT MemVT = Ld->getMemoryVT();
19527 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19528 unsigned RegSz = RegVT.getSizeInBits();
19530 // On Sandybridge unaligned 256bit loads are inefficient.
19531 ISD::LoadExtType Ext = Ld->getExtensionType();
19532 unsigned Alignment = Ld->getAlignment();
19533 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19534 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19535 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19536 unsigned NumElems = RegVT.getVectorNumElements();
19540 SDValue Ptr = Ld->getBasePtr();
19541 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19543 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19545 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19546 Ld->getPointerInfo(), Ld->isVolatile(),
19547 Ld->isNonTemporal(), Ld->isInvariant(),
19549 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19550 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19551 Ld->getPointerInfo(), Ld->isVolatile(),
19552 Ld->isNonTemporal(), Ld->isInvariant(),
19553 std::min(16U, Alignment));
19554 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19556 Load2.getValue(1));
19558 SDValue NewVec = DAG.getUNDEF(RegVT);
19559 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19560 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19561 return DCI.CombineTo(N, NewVec, TF, true);
19564 // If this is a vector EXT Load then attempt to optimize it using a
19565 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19566 // expansion is still better than scalar code.
19567 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19568 // emit a shuffle and a arithmetic shift.
19569 // TODO: It is possible to support ZExt by zeroing the undef values
19570 // during the shuffle phase or after the shuffle.
19571 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19572 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19573 assert(MemVT != RegVT && "Cannot extend to the same type");
19574 assert(MemVT.isVector() && "Must load a vector from memory");
19576 unsigned NumElems = RegVT.getVectorNumElements();
19577 unsigned MemSz = MemVT.getSizeInBits();
19578 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19580 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19583 // All sizes must be a power of two.
19584 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19587 // Attempt to load the original value using scalar loads.
19588 // Find the largest scalar type that divides the total loaded size.
19589 MVT SclrLoadTy = MVT::i8;
19590 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19591 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19592 MVT Tp = (MVT::SimpleValueType)tp;
19593 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19598 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19599 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19601 SclrLoadTy = MVT::f64;
19603 // Calculate the number of scalar loads that we need to perform
19604 // in order to load our vector from memory.
19605 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19606 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19609 unsigned loadRegZize = RegSz;
19610 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19613 // Represent our vector as a sequence of elements which are the
19614 // largest scalar that we can load.
19615 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19616 loadRegZize/SclrLoadTy.getSizeInBits());
19618 // Represent the data using the same element type that is stored in
19619 // memory. In practice, we ''widen'' MemVT.
19621 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19622 loadRegZize/MemVT.getScalarType().getSizeInBits());
19624 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19625 "Invalid vector type");
19627 // We can't shuffle using an illegal type.
19628 if (!TLI.isTypeLegal(WideVecVT))
19631 SmallVector<SDValue, 8> Chains;
19632 SDValue Ptr = Ld->getBasePtr();
19633 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19634 TLI.getPointerTy());
19635 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19637 for (unsigned i = 0; i < NumLoads; ++i) {
19638 // Perform a single load.
19639 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19640 Ptr, Ld->getPointerInfo(),
19641 Ld->isVolatile(), Ld->isNonTemporal(),
19642 Ld->isInvariant(), Ld->getAlignment());
19643 Chains.push_back(ScalarLoad.getValue(1));
19644 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19645 // another round of DAGCombining.
19647 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19649 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19650 ScalarLoad, DAG.getIntPtrConstant(i));
19652 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19655 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19657 // Bitcast the loaded value to a vector of the original element type, in
19658 // the size of the target vector type.
19659 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19660 unsigned SizeRatio = RegSz/MemSz;
19662 if (Ext == ISD::SEXTLOAD) {
19663 // If we have SSE4.1 we can directly emit a VSEXT node.
19664 if (Subtarget->hasSSE41()) {
19665 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19666 return DCI.CombineTo(N, Sext, TF, true);
19669 // Otherwise we'll shuffle the small elements in the high bits of the
19670 // larger type and perform an arithmetic shift. If the shift is not legal
19671 // it's better to scalarize.
19672 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19675 // Redistribute the loaded elements into the different locations.
19676 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19677 for (unsigned i = 0; i != NumElems; ++i)
19678 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19680 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19681 DAG.getUNDEF(WideVecVT),
19684 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19686 // Build the arithmetic shift.
19687 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19688 MemVT.getVectorElementType().getSizeInBits();
19689 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19690 DAG.getConstant(Amt, RegVT));
19692 return DCI.CombineTo(N, Shuff, TF, true);
19695 // Redistribute the loaded elements into the different locations.
19696 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19697 for (unsigned i = 0; i != NumElems; ++i)
19698 ShuffleVec[i*SizeRatio] = i;
19700 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19701 DAG.getUNDEF(WideVecVT),
19704 // Bitcast to the requested type.
19705 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19706 // Replace the original load with the new sequence
19707 // and return the new chain.
19708 return DCI.CombineTo(N, Shuff, TF, true);
19714 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19715 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19716 const X86Subtarget *Subtarget) {
19717 StoreSDNode *St = cast<StoreSDNode>(N);
19718 EVT VT = St->getValue().getValueType();
19719 EVT StVT = St->getMemoryVT();
19721 SDValue StoredVal = St->getOperand(1);
19722 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19724 // If we are saving a concatenation of two XMM registers, perform two stores.
19725 // On Sandy Bridge, 256-bit memory operations are executed by two
19726 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19727 // memory operation.
19728 unsigned Alignment = St->getAlignment();
19729 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19730 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19731 StVT == VT && !IsAligned) {
19732 unsigned NumElems = VT.getVectorNumElements();
19736 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19737 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19739 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19740 SDValue Ptr0 = St->getBasePtr();
19741 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19743 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19744 St->getPointerInfo(), St->isVolatile(),
19745 St->isNonTemporal(), Alignment);
19746 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19747 St->getPointerInfo(), St->isVolatile(),
19748 St->isNonTemporal(),
19749 std::min(16U, Alignment));
19750 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19753 // Optimize trunc store (of multiple scalars) to shuffle and store.
19754 // First, pack all of the elements in one place. Next, store to memory
19755 // in fewer chunks.
19756 if (St->isTruncatingStore() && VT.isVector()) {
19757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19758 unsigned NumElems = VT.getVectorNumElements();
19759 assert(StVT != VT && "Cannot truncate to the same type");
19760 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19761 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19763 // From, To sizes and ElemCount must be pow of two
19764 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19765 // We are going to use the original vector elt for storing.
19766 // Accumulated smaller vector elements must be a multiple of the store size.
19767 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19769 unsigned SizeRatio = FromSz / ToSz;
19771 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19773 // Create a type on which we perform the shuffle
19774 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19775 StVT.getScalarType(), NumElems*SizeRatio);
19777 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19779 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19780 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19781 for (unsigned i = 0; i != NumElems; ++i)
19782 ShuffleVec[i] = i * SizeRatio;
19784 // Can't shuffle using an illegal type.
19785 if (!TLI.isTypeLegal(WideVecVT))
19788 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19789 DAG.getUNDEF(WideVecVT),
19791 // At this point all of the data is stored at the bottom of the
19792 // register. We now need to save it to mem.
19794 // Find the largest store unit
19795 MVT StoreType = MVT::i8;
19796 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19797 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19798 MVT Tp = (MVT::SimpleValueType)tp;
19799 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19803 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19804 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19805 (64 <= NumElems * ToSz))
19806 StoreType = MVT::f64;
19808 // Bitcast the original vector into a vector of store-size units
19809 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19810 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19811 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19812 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19813 SmallVector<SDValue, 8> Chains;
19814 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19815 TLI.getPointerTy());
19816 SDValue Ptr = St->getBasePtr();
19818 // Perform one or more big stores into memory.
19819 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19820 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19821 StoreType, ShuffWide,
19822 DAG.getIntPtrConstant(i));
19823 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19824 St->getPointerInfo(), St->isVolatile(),
19825 St->isNonTemporal(), St->getAlignment());
19826 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19827 Chains.push_back(Ch);
19830 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19833 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19834 // the FP state in cases where an emms may be missing.
19835 // A preferable solution to the general problem is to figure out the right
19836 // places to insert EMMS. This qualifies as a quick hack.
19838 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19839 if (VT.getSizeInBits() != 64)
19842 const Function *F = DAG.getMachineFunction().getFunction();
19843 bool NoImplicitFloatOps = F->getAttributes().
19844 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19845 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19846 && Subtarget->hasSSE2();
19847 if ((VT.isVector() ||
19848 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19849 isa<LoadSDNode>(St->getValue()) &&
19850 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19851 St->getChain().hasOneUse() && !St->isVolatile()) {
19852 SDNode* LdVal = St->getValue().getNode();
19853 LoadSDNode *Ld = nullptr;
19854 int TokenFactorIndex = -1;
19855 SmallVector<SDValue, 8> Ops;
19856 SDNode* ChainVal = St->getChain().getNode();
19857 // Must be a store of a load. We currently handle two cases: the load
19858 // is a direct child, and it's under an intervening TokenFactor. It is
19859 // possible to dig deeper under nested TokenFactors.
19860 if (ChainVal == LdVal)
19861 Ld = cast<LoadSDNode>(St->getChain());
19862 else if (St->getValue().hasOneUse() &&
19863 ChainVal->getOpcode() == ISD::TokenFactor) {
19864 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19865 if (ChainVal->getOperand(i).getNode() == LdVal) {
19866 TokenFactorIndex = i;
19867 Ld = cast<LoadSDNode>(St->getValue());
19869 Ops.push_back(ChainVal->getOperand(i));
19873 if (!Ld || !ISD::isNormalLoad(Ld))
19876 // If this is not the MMX case, i.e. we are just turning i64 load/store
19877 // into f64 load/store, avoid the transformation if there are multiple
19878 // uses of the loaded value.
19879 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19884 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19885 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19887 if (Subtarget->is64Bit() || F64IsLegal) {
19888 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19889 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19890 Ld->getPointerInfo(), Ld->isVolatile(),
19891 Ld->isNonTemporal(), Ld->isInvariant(),
19892 Ld->getAlignment());
19893 SDValue NewChain = NewLd.getValue(1);
19894 if (TokenFactorIndex != -1) {
19895 Ops.push_back(NewChain);
19896 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19898 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19899 St->getPointerInfo(),
19900 St->isVolatile(), St->isNonTemporal(),
19901 St->getAlignment());
19904 // Otherwise, lower to two pairs of 32-bit loads / stores.
19905 SDValue LoAddr = Ld->getBasePtr();
19906 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19907 DAG.getConstant(4, MVT::i32));
19909 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19910 Ld->getPointerInfo(),
19911 Ld->isVolatile(), Ld->isNonTemporal(),
19912 Ld->isInvariant(), Ld->getAlignment());
19913 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19914 Ld->getPointerInfo().getWithOffset(4),
19915 Ld->isVolatile(), Ld->isNonTemporal(),
19917 MinAlign(Ld->getAlignment(), 4));
19919 SDValue NewChain = LoLd.getValue(1);
19920 if (TokenFactorIndex != -1) {
19921 Ops.push_back(LoLd);
19922 Ops.push_back(HiLd);
19923 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19926 LoAddr = St->getBasePtr();
19927 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19928 DAG.getConstant(4, MVT::i32));
19930 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19931 St->getPointerInfo(),
19932 St->isVolatile(), St->isNonTemporal(),
19933 St->getAlignment());
19934 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19935 St->getPointerInfo().getWithOffset(4),
19937 St->isNonTemporal(),
19938 MinAlign(St->getAlignment(), 4));
19939 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19944 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19945 /// and return the operands for the horizontal operation in LHS and RHS. A
19946 /// horizontal operation performs the binary operation on successive elements
19947 /// of its first operand, then on successive elements of its second operand,
19948 /// returning the resulting values in a vector. For example, if
19949 /// A = < float a0, float a1, float a2, float a3 >
19951 /// B = < float b0, float b1, float b2, float b3 >
19952 /// then the result of doing a horizontal operation on A and B is
19953 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19954 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19955 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19956 /// set to A, RHS to B, and the routine returns 'true'.
19957 /// Note that the binary operation should have the property that if one of the
19958 /// operands is UNDEF then the result is UNDEF.
19959 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19960 // Look for the following pattern: if
19961 // A = < float a0, float a1, float a2, float a3 >
19962 // B = < float b0, float b1, float b2, float b3 >
19964 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19965 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19966 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19967 // which is A horizontal-op B.
19969 // At least one of the operands should be a vector shuffle.
19970 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19971 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19974 MVT VT = LHS.getSimpleValueType();
19976 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19977 "Unsupported vector type for horizontal add/sub");
19979 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19980 // operate independently on 128-bit lanes.
19981 unsigned NumElts = VT.getVectorNumElements();
19982 unsigned NumLanes = VT.getSizeInBits()/128;
19983 unsigned NumLaneElts = NumElts / NumLanes;
19984 assert((NumLaneElts % 2 == 0) &&
19985 "Vector type should have an even number of elements in each lane");
19986 unsigned HalfLaneElts = NumLaneElts/2;
19988 // View LHS in the form
19989 // LHS = VECTOR_SHUFFLE A, B, LMask
19990 // If LHS is not a shuffle then pretend it is the shuffle
19991 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19992 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19995 SmallVector<int, 16> LMask(NumElts);
19996 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19997 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19998 A = LHS.getOperand(0);
19999 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20000 B = LHS.getOperand(1);
20001 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20002 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20004 if (LHS.getOpcode() != ISD::UNDEF)
20006 for (unsigned i = 0; i != NumElts; ++i)
20010 // Likewise, view RHS in the form
20011 // RHS = VECTOR_SHUFFLE C, D, RMask
20013 SmallVector<int, 16> RMask(NumElts);
20014 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20015 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20016 C = RHS.getOperand(0);
20017 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20018 D = RHS.getOperand(1);
20019 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20020 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20022 if (RHS.getOpcode() != ISD::UNDEF)
20024 for (unsigned i = 0; i != NumElts; ++i)
20028 // Check that the shuffles are both shuffling the same vectors.
20029 if (!(A == C && B == D) && !(A == D && B == C))
20032 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20033 if (!A.getNode() && !B.getNode())
20036 // If A and B occur in reverse order in RHS, then "swap" them (which means
20037 // rewriting the mask).
20039 CommuteVectorShuffleMask(RMask, NumElts);
20041 // At this point LHS and RHS are equivalent to
20042 // LHS = VECTOR_SHUFFLE A, B, LMask
20043 // RHS = VECTOR_SHUFFLE A, B, RMask
20044 // Check that the masks correspond to performing a horizontal operation.
20045 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20046 for (unsigned i = 0; i != NumLaneElts; ++i) {
20047 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20049 // Ignore any UNDEF components.
20050 if (LIdx < 0 || RIdx < 0 ||
20051 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20052 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20055 // Check that successive elements are being operated on. If not, this is
20056 // not a horizontal operation.
20057 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20058 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20059 if (!(LIdx == Index && RIdx == Index + 1) &&
20060 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20065 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20066 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20070 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20071 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20072 const X86Subtarget *Subtarget) {
20073 EVT VT = N->getValueType(0);
20074 SDValue LHS = N->getOperand(0);
20075 SDValue RHS = N->getOperand(1);
20077 // Try to synthesize horizontal adds from adds of shuffles.
20078 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20079 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20080 isHorizontalBinOp(LHS, RHS, true))
20081 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20085 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20086 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20087 const X86Subtarget *Subtarget) {
20088 EVT VT = N->getValueType(0);
20089 SDValue LHS = N->getOperand(0);
20090 SDValue RHS = N->getOperand(1);
20092 // Try to synthesize horizontal subs from subs of shuffles.
20093 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20094 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20095 isHorizontalBinOp(LHS, RHS, false))
20096 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20100 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20101 /// X86ISD::FXOR nodes.
20102 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20103 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20104 // F[X]OR(0.0, x) -> x
20105 // F[X]OR(x, 0.0) -> x
20106 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20107 if (C->getValueAPF().isPosZero())
20108 return N->getOperand(1);
20109 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20110 if (C->getValueAPF().isPosZero())
20111 return N->getOperand(0);
20115 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20116 /// X86ISD::FMAX nodes.
20117 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20118 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20120 // Only perform optimizations if UnsafeMath is used.
20121 if (!DAG.getTarget().Options.UnsafeFPMath)
20124 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20125 // into FMINC and FMAXC, which are Commutative operations.
20126 unsigned NewOp = 0;
20127 switch (N->getOpcode()) {
20128 default: llvm_unreachable("unknown opcode");
20129 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20130 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20133 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20134 N->getOperand(0), N->getOperand(1));
20137 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20138 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20139 // FAND(0.0, x) -> 0.0
20140 // FAND(x, 0.0) -> 0.0
20141 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20142 if (C->getValueAPF().isPosZero())
20143 return N->getOperand(0);
20144 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20145 if (C->getValueAPF().isPosZero())
20146 return N->getOperand(1);
20150 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20151 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20152 // FANDN(x, 0.0) -> 0.0
20153 // FANDN(0.0, x) -> x
20154 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20155 if (C->getValueAPF().isPosZero())
20156 return N->getOperand(1);
20157 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20158 if (C->getValueAPF().isPosZero())
20159 return N->getOperand(1);
20163 static SDValue PerformBTCombine(SDNode *N,
20165 TargetLowering::DAGCombinerInfo &DCI) {
20166 // BT ignores high bits in the bit index operand.
20167 SDValue Op1 = N->getOperand(1);
20168 if (Op1.hasOneUse()) {
20169 unsigned BitWidth = Op1.getValueSizeInBits();
20170 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20171 APInt KnownZero, KnownOne;
20172 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20173 !DCI.isBeforeLegalizeOps());
20174 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20175 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20176 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20177 DCI.CommitTargetLoweringOpt(TLO);
20182 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20183 SDValue Op = N->getOperand(0);
20184 if (Op.getOpcode() == ISD::BITCAST)
20185 Op = Op.getOperand(0);
20186 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20187 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20188 VT.getVectorElementType().getSizeInBits() ==
20189 OpVT.getVectorElementType().getSizeInBits()) {
20190 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20195 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20196 const X86Subtarget *Subtarget) {
20197 EVT VT = N->getValueType(0);
20198 if (!VT.isVector())
20201 SDValue N0 = N->getOperand(0);
20202 SDValue N1 = N->getOperand(1);
20203 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20206 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20207 // both SSE and AVX2 since there is no sign-extended shift right
20208 // operation on a vector with 64-bit elements.
20209 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20210 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20211 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20212 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20213 SDValue N00 = N0.getOperand(0);
20215 // EXTLOAD has a better solution on AVX2,
20216 // it may be replaced with X86ISD::VSEXT node.
20217 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20218 if (!ISD::isNormalLoad(N00.getNode()))
20221 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20222 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20224 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20230 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20231 TargetLowering::DAGCombinerInfo &DCI,
20232 const X86Subtarget *Subtarget) {
20233 if (!DCI.isBeforeLegalizeOps())
20236 if (!Subtarget->hasFp256())
20239 EVT VT = N->getValueType(0);
20240 if (VT.isVector() && VT.getSizeInBits() == 256) {
20241 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20249 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20250 const X86Subtarget* Subtarget) {
20252 EVT VT = N->getValueType(0);
20254 // Let legalize expand this if it isn't a legal type yet.
20255 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20258 EVT ScalarVT = VT.getScalarType();
20259 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20260 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20263 SDValue A = N->getOperand(0);
20264 SDValue B = N->getOperand(1);
20265 SDValue C = N->getOperand(2);
20267 bool NegA = (A.getOpcode() == ISD::FNEG);
20268 bool NegB = (B.getOpcode() == ISD::FNEG);
20269 bool NegC = (C.getOpcode() == ISD::FNEG);
20271 // Negative multiplication when NegA xor NegB
20272 bool NegMul = (NegA != NegB);
20274 A = A.getOperand(0);
20276 B = B.getOperand(0);
20278 C = C.getOperand(0);
20282 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20284 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20286 return DAG.getNode(Opcode, dl, VT, A, B, C);
20289 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20290 TargetLowering::DAGCombinerInfo &DCI,
20291 const X86Subtarget *Subtarget) {
20292 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20293 // (and (i32 x86isd::setcc_carry), 1)
20294 // This eliminates the zext. This transformation is necessary because
20295 // ISD::SETCC is always legalized to i8.
20297 SDValue N0 = N->getOperand(0);
20298 EVT VT = N->getValueType(0);
20300 if (N0.getOpcode() == ISD::AND &&
20302 N0.getOperand(0).hasOneUse()) {
20303 SDValue N00 = N0.getOperand(0);
20304 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20305 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20306 if (!C || C->getZExtValue() != 1)
20308 return DAG.getNode(ISD::AND, dl, VT,
20309 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20310 N00.getOperand(0), N00.getOperand(1)),
20311 DAG.getConstant(1, VT));
20315 if (N0.getOpcode() == ISD::TRUNCATE &&
20317 N0.getOperand(0).hasOneUse()) {
20318 SDValue N00 = N0.getOperand(0);
20319 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20320 return DAG.getNode(ISD::AND, dl, VT,
20321 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20322 N00.getOperand(0), N00.getOperand(1)),
20323 DAG.getConstant(1, VT));
20326 if (VT.is256BitVector()) {
20327 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20335 // Optimize x == -y --> x+y == 0
20336 // x != -y --> x+y != 0
20337 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20338 const X86Subtarget* Subtarget) {
20339 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20340 SDValue LHS = N->getOperand(0);
20341 SDValue RHS = N->getOperand(1);
20342 EVT VT = N->getValueType(0);
20345 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20346 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20347 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20348 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20349 LHS.getValueType(), RHS, LHS.getOperand(1));
20350 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20351 addV, DAG.getConstant(0, addV.getValueType()), CC);
20353 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20354 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20355 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20356 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20357 RHS.getValueType(), LHS, RHS.getOperand(1));
20358 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20359 addV, DAG.getConstant(0, addV.getValueType()), CC);
20362 if (VT.getScalarType() == MVT::i1) {
20363 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20364 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20365 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20366 if (!IsSEXT0 && !IsVZero0)
20368 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20369 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20370 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20372 if (!IsSEXT1 && !IsVZero1)
20375 if (IsSEXT0 && IsVZero1) {
20376 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20377 if (CC == ISD::SETEQ)
20378 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20379 return LHS.getOperand(0);
20381 if (IsSEXT1 && IsVZero0) {
20382 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20383 if (CC == ISD::SETEQ)
20384 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20385 return RHS.getOperand(0);
20392 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20393 const X86Subtarget *Subtarget) {
20395 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20396 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20397 "X86insertps is only defined for v4x32");
20399 SDValue Ld = N->getOperand(1);
20400 if (MayFoldLoad(Ld)) {
20401 // Extract the countS bits from the immediate so we can get the proper
20402 // address when narrowing the vector load to a specific element.
20403 // When the second source op is a memory address, interps doesn't use
20404 // countS and just gets an f32 from that address.
20405 unsigned DestIndex =
20406 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20407 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20411 // Create this as a scalar to vector to match the instruction pattern.
20412 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20413 // countS bits are ignored when loading from memory on insertps, which
20414 // means we don't need to explicitly set them to 0.
20415 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20416 LoadScalarToVector, N->getOperand(2));
20419 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20420 // as "sbb reg,reg", since it can be extended without zext and produces
20421 // an all-ones bit which is more useful than 0/1 in some cases.
20422 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20425 return DAG.getNode(ISD::AND, DL, VT,
20426 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20427 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20428 DAG.getConstant(1, VT));
20429 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20430 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20431 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20432 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20435 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20436 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20437 TargetLowering::DAGCombinerInfo &DCI,
20438 const X86Subtarget *Subtarget) {
20440 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20441 SDValue EFLAGS = N->getOperand(1);
20443 if (CC == X86::COND_A) {
20444 // Try to convert COND_A into COND_B in an attempt to facilitate
20445 // materializing "setb reg".
20447 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20448 // cannot take an immediate as its first operand.
20450 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20451 EFLAGS.getValueType().isInteger() &&
20452 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20453 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20454 EFLAGS.getNode()->getVTList(),
20455 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20456 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20457 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20461 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20462 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20464 if (CC == X86::COND_B)
20465 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20469 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20470 if (Flags.getNode()) {
20471 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20472 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20478 // Optimize branch condition evaluation.
20480 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20481 TargetLowering::DAGCombinerInfo &DCI,
20482 const X86Subtarget *Subtarget) {
20484 SDValue Chain = N->getOperand(0);
20485 SDValue Dest = N->getOperand(1);
20486 SDValue EFLAGS = N->getOperand(3);
20487 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20491 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20492 if (Flags.getNode()) {
20493 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20494 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20501 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20502 const X86TargetLowering *XTLI) {
20503 SDValue Op0 = N->getOperand(0);
20504 EVT InVT = Op0->getValueType(0);
20506 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20507 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20509 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20510 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20511 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20514 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20515 // a 32-bit target where SSE doesn't support i64->FP operations.
20516 if (Op0.getOpcode() == ISD::LOAD) {
20517 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20518 EVT VT = Ld->getValueType(0);
20519 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20520 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20521 !XTLI->getSubtarget()->is64Bit() &&
20523 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20524 Ld->getChain(), Op0, DAG);
20525 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20532 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20533 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20534 X86TargetLowering::DAGCombinerInfo &DCI) {
20535 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20536 // the result is either zero or one (depending on the input carry bit).
20537 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20538 if (X86::isZeroNode(N->getOperand(0)) &&
20539 X86::isZeroNode(N->getOperand(1)) &&
20540 // We don't have a good way to replace an EFLAGS use, so only do this when
20542 SDValue(N, 1).use_empty()) {
20544 EVT VT = N->getValueType(0);
20545 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20546 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20547 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20548 DAG.getConstant(X86::COND_B,MVT::i8),
20550 DAG.getConstant(1, VT));
20551 return DCI.CombineTo(N, Res1, CarryOut);
20557 // fold (add Y, (sete X, 0)) -> adc 0, Y
20558 // (add Y, (setne X, 0)) -> sbb -1, Y
20559 // (sub (sete X, 0), Y) -> sbb 0, Y
20560 // (sub (setne X, 0), Y) -> adc -1, Y
20561 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20564 // Look through ZExts.
20565 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20566 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20569 SDValue SetCC = Ext.getOperand(0);
20570 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20573 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20574 if (CC != X86::COND_E && CC != X86::COND_NE)
20577 SDValue Cmp = SetCC.getOperand(1);
20578 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20579 !X86::isZeroNode(Cmp.getOperand(1)) ||
20580 !Cmp.getOperand(0).getValueType().isInteger())
20583 SDValue CmpOp0 = Cmp.getOperand(0);
20584 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20585 DAG.getConstant(1, CmpOp0.getValueType()));
20587 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20588 if (CC == X86::COND_NE)
20589 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20590 DL, OtherVal.getValueType(), OtherVal,
20591 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20592 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20593 DL, OtherVal.getValueType(), OtherVal,
20594 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20597 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20598 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20599 const X86Subtarget *Subtarget) {
20600 EVT VT = N->getValueType(0);
20601 SDValue Op0 = N->getOperand(0);
20602 SDValue Op1 = N->getOperand(1);
20604 // Try to synthesize horizontal adds from adds of shuffles.
20605 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20606 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20607 isHorizontalBinOp(Op0, Op1, true))
20608 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20610 return OptimizeConditionalInDecrement(N, DAG);
20613 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20614 const X86Subtarget *Subtarget) {
20615 SDValue Op0 = N->getOperand(0);
20616 SDValue Op1 = N->getOperand(1);
20618 // X86 can't encode an immediate LHS of a sub. See if we can push the
20619 // negation into a preceding instruction.
20620 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20621 // If the RHS of the sub is a XOR with one use and a constant, invert the
20622 // immediate. Then add one to the LHS of the sub so we can turn
20623 // X-Y -> X+~Y+1, saving one register.
20624 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20625 isa<ConstantSDNode>(Op1.getOperand(1))) {
20626 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20627 EVT VT = Op0.getValueType();
20628 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20630 DAG.getConstant(~XorC, VT));
20631 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20632 DAG.getConstant(C->getAPIntValue()+1, VT));
20636 // Try to synthesize horizontal adds from adds of shuffles.
20637 EVT VT = N->getValueType(0);
20638 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20639 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20640 isHorizontalBinOp(Op0, Op1, true))
20641 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20643 return OptimizeConditionalInDecrement(N, DAG);
20646 /// performVZEXTCombine - Performs build vector combines
20647 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20648 TargetLowering::DAGCombinerInfo &DCI,
20649 const X86Subtarget *Subtarget) {
20650 // (vzext (bitcast (vzext (x)) -> (vzext x)
20651 SDValue In = N->getOperand(0);
20652 while (In.getOpcode() == ISD::BITCAST)
20653 In = In.getOperand(0);
20655 if (In.getOpcode() != X86ISD::VZEXT)
20658 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20662 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20663 DAGCombinerInfo &DCI) const {
20664 SelectionDAG &DAG = DCI.DAG;
20665 switch (N->getOpcode()) {
20667 case ISD::EXTRACT_VECTOR_ELT:
20668 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20670 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20671 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20672 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20673 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20674 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20675 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20678 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20679 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20680 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20681 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20682 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20683 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20684 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20685 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20686 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20688 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20690 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20691 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20692 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20693 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20694 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20695 case ISD::ANY_EXTEND:
20696 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20697 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20698 case ISD::SIGN_EXTEND_INREG:
20699 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20700 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20701 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20702 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20703 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20704 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20705 case X86ISD::SHUFP: // Handle all target specific shuffles
20706 case X86ISD::PALIGNR:
20707 case X86ISD::UNPCKH:
20708 case X86ISD::UNPCKL:
20709 case X86ISD::MOVHLPS:
20710 case X86ISD::MOVLHPS:
20711 case X86ISD::PSHUFD:
20712 case X86ISD::PSHUFHW:
20713 case X86ISD::PSHUFLW:
20714 case X86ISD::MOVSS:
20715 case X86ISD::MOVSD:
20716 case X86ISD::VPERMILP:
20717 case X86ISD::VPERM2X128:
20718 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20719 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20720 case ISD::INTRINSIC_WO_CHAIN:
20721 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20722 case X86ISD::INSERTPS:
20723 return PerformINSERTPSCombine(N, DAG, Subtarget);
20729 /// isTypeDesirableForOp - Return true if the target has native support for
20730 /// the specified value type and it is 'desirable' to use the type for the
20731 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20732 /// instruction encodings are longer and some i16 instructions are slow.
20733 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20734 if (!isTypeLegal(VT))
20736 if (VT != MVT::i16)
20743 case ISD::SIGN_EXTEND:
20744 case ISD::ZERO_EXTEND:
20745 case ISD::ANY_EXTEND:
20758 /// IsDesirableToPromoteOp - This method query the target whether it is
20759 /// beneficial for dag combiner to promote the specified node. If true, it
20760 /// should return the desired promotion type by reference.
20761 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20762 EVT VT = Op.getValueType();
20763 if (VT != MVT::i16)
20766 bool Promote = false;
20767 bool Commute = false;
20768 switch (Op.getOpcode()) {
20771 LoadSDNode *LD = cast<LoadSDNode>(Op);
20772 // If the non-extending load has a single use and it's not live out, then it
20773 // might be folded.
20774 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20775 Op.hasOneUse()*/) {
20776 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20777 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20778 // The only case where we'd want to promote LOAD (rather then it being
20779 // promoted as an operand is when it's only use is liveout.
20780 if (UI->getOpcode() != ISD::CopyToReg)
20787 case ISD::SIGN_EXTEND:
20788 case ISD::ZERO_EXTEND:
20789 case ISD::ANY_EXTEND:
20794 SDValue N0 = Op.getOperand(0);
20795 // Look out for (store (shl (load), x)).
20796 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20809 SDValue N0 = Op.getOperand(0);
20810 SDValue N1 = Op.getOperand(1);
20811 if (!Commute && MayFoldLoad(N1))
20813 // Avoid disabling potential load folding opportunities.
20814 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20816 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20826 //===----------------------------------------------------------------------===//
20827 // X86 Inline Assembly Support
20828 //===----------------------------------------------------------------------===//
20831 // Helper to match a string separated by whitespace.
20832 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20833 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20835 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20836 StringRef piece(*args[i]);
20837 if (!s.startswith(piece)) // Check if the piece matches.
20840 s = s.substr(piece.size());
20841 StringRef::size_type pos = s.find_first_not_of(" \t");
20842 if (pos == 0) // We matched a prefix.
20850 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20853 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20855 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20856 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20857 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20858 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20860 if (AsmPieces.size() == 3)
20862 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20869 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20870 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20872 std::string AsmStr = IA->getAsmString();
20874 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20875 if (!Ty || Ty->getBitWidth() % 16 != 0)
20878 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20879 SmallVector<StringRef, 4> AsmPieces;
20880 SplitString(AsmStr, AsmPieces, ";\n");
20882 switch (AsmPieces.size()) {
20883 default: return false;
20885 // FIXME: this should verify that we are targeting a 486 or better. If not,
20886 // we will turn this bswap into something that will be lowered to logical
20887 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20888 // lower so don't worry about this.
20890 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20891 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20892 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20893 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20894 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20895 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20896 // No need to check constraints, nothing other than the equivalent of
20897 // "=r,0" would be valid here.
20898 return IntrinsicLowering::LowerToByteSwap(CI);
20901 // rorw $$8, ${0:w} --> llvm.bswap.i16
20902 if (CI->getType()->isIntegerTy(16) &&
20903 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20904 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20905 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20907 const std::string &ConstraintsStr = IA->getConstraintString();
20908 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20909 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20910 if (clobbersFlagRegisters(AsmPieces))
20911 return IntrinsicLowering::LowerToByteSwap(CI);
20915 if (CI->getType()->isIntegerTy(32) &&
20916 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20917 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20918 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20919 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20921 const std::string &ConstraintsStr = IA->getConstraintString();
20922 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20923 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20924 if (clobbersFlagRegisters(AsmPieces))
20925 return IntrinsicLowering::LowerToByteSwap(CI);
20928 if (CI->getType()->isIntegerTy(64)) {
20929 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20930 if (Constraints.size() >= 2 &&
20931 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20932 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20933 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20934 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20935 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20936 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20937 return IntrinsicLowering::LowerToByteSwap(CI);
20945 /// getConstraintType - Given a constraint letter, return the type of
20946 /// constraint it is for this target.
20947 X86TargetLowering::ConstraintType
20948 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20949 if (Constraint.size() == 1) {
20950 switch (Constraint[0]) {
20961 return C_RegisterClass;
20985 return TargetLowering::getConstraintType(Constraint);
20988 /// Examine constraint type and operand type and determine a weight value.
20989 /// This object must already have been set up with the operand type
20990 /// and the current alternative constraint selected.
20991 TargetLowering::ConstraintWeight
20992 X86TargetLowering::getSingleConstraintMatchWeight(
20993 AsmOperandInfo &info, const char *constraint) const {
20994 ConstraintWeight weight = CW_Invalid;
20995 Value *CallOperandVal = info.CallOperandVal;
20996 // If we don't have a value, we can't do a match,
20997 // but allow it at the lowest weight.
20998 if (!CallOperandVal)
21000 Type *type = CallOperandVal->getType();
21001 // Look at the constraint type.
21002 switch (*constraint) {
21004 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21015 if (CallOperandVal->getType()->isIntegerTy())
21016 weight = CW_SpecificReg;
21021 if (type->isFloatingPointTy())
21022 weight = CW_SpecificReg;
21025 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21026 weight = CW_SpecificReg;
21030 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21031 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21032 weight = CW_Register;
21035 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21036 if (C->getZExtValue() <= 31)
21037 weight = CW_Constant;
21041 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21042 if (C->getZExtValue() <= 63)
21043 weight = CW_Constant;
21047 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21048 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21049 weight = CW_Constant;
21053 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21054 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21055 weight = CW_Constant;
21059 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21060 if (C->getZExtValue() <= 3)
21061 weight = CW_Constant;
21065 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21066 if (C->getZExtValue() <= 0xff)
21067 weight = CW_Constant;
21072 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21073 weight = CW_Constant;
21077 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21078 if ((C->getSExtValue() >= -0x80000000LL) &&
21079 (C->getSExtValue() <= 0x7fffffffLL))
21080 weight = CW_Constant;
21084 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21085 if (C->getZExtValue() <= 0xffffffff)
21086 weight = CW_Constant;
21093 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21094 /// with another that has more specific requirements based on the type of the
21095 /// corresponding operand.
21096 const char *X86TargetLowering::
21097 LowerXConstraint(EVT ConstraintVT) const {
21098 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21099 // 'f' like normal targets.
21100 if (ConstraintVT.isFloatingPoint()) {
21101 if (Subtarget->hasSSE2())
21103 if (Subtarget->hasSSE1())
21107 return TargetLowering::LowerXConstraint(ConstraintVT);
21110 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21111 /// vector. If it is invalid, don't add anything to Ops.
21112 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21113 std::string &Constraint,
21114 std::vector<SDValue>&Ops,
21115 SelectionDAG &DAG) const {
21118 // Only support length 1 constraints for now.
21119 if (Constraint.length() > 1) return;
21121 char ConstraintLetter = Constraint[0];
21122 switch (ConstraintLetter) {
21125 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21126 if (C->getZExtValue() <= 31) {
21127 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21133 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21134 if (C->getZExtValue() <= 63) {
21135 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21142 if (isInt<8>(C->getSExtValue())) {
21143 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21150 if (C->getZExtValue() <= 255) {
21151 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21157 // 32-bit signed value
21158 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21159 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21160 C->getSExtValue())) {
21161 // Widen to 64 bits here to get it sign extended.
21162 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21165 // FIXME gcc accepts some relocatable values here too, but only in certain
21166 // memory models; it's complicated.
21171 // 32-bit unsigned value
21172 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21173 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21174 C->getZExtValue())) {
21175 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21179 // FIXME gcc accepts some relocatable values here too, but only in certain
21180 // memory models; it's complicated.
21184 // Literal immediates are always ok.
21185 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21186 // Widen to 64 bits here to get it sign extended.
21187 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21191 // In any sort of PIC mode addresses need to be computed at runtime by
21192 // adding in a register or some sort of table lookup. These can't
21193 // be used as immediates.
21194 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21197 // If we are in non-pic codegen mode, we allow the address of a global (with
21198 // an optional displacement) to be used with 'i'.
21199 GlobalAddressSDNode *GA = nullptr;
21200 int64_t Offset = 0;
21202 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21204 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21205 Offset += GA->getOffset();
21207 } else if (Op.getOpcode() == ISD::ADD) {
21208 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21209 Offset += C->getZExtValue();
21210 Op = Op.getOperand(0);
21213 } else if (Op.getOpcode() == ISD::SUB) {
21214 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21215 Offset += -C->getZExtValue();
21216 Op = Op.getOperand(0);
21221 // Otherwise, this isn't something we can handle, reject it.
21225 const GlobalValue *GV = GA->getGlobal();
21226 // If we require an extra load to get this address, as in PIC mode, we
21227 // can't accept it.
21228 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21229 getTargetMachine())))
21232 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21233 GA->getValueType(0), Offset);
21238 if (Result.getNode()) {
21239 Ops.push_back(Result);
21242 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21245 std::pair<unsigned, const TargetRegisterClass*>
21246 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21248 // First, see if this is a constraint that directly corresponds to an LLVM
21250 if (Constraint.size() == 1) {
21251 // GCC Constraint Letters
21252 switch (Constraint[0]) {
21254 // TODO: Slight differences here in allocation order and leaving
21255 // RIP in the class. Do they matter any more here than they do
21256 // in the normal allocation?
21257 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21258 if (Subtarget->is64Bit()) {
21259 if (VT == MVT::i32 || VT == MVT::f32)
21260 return std::make_pair(0U, &X86::GR32RegClass);
21261 if (VT == MVT::i16)
21262 return std::make_pair(0U, &X86::GR16RegClass);
21263 if (VT == MVT::i8 || VT == MVT::i1)
21264 return std::make_pair(0U, &X86::GR8RegClass);
21265 if (VT == MVT::i64 || VT == MVT::f64)
21266 return std::make_pair(0U, &X86::GR64RegClass);
21269 // 32-bit fallthrough
21270 case 'Q': // Q_REGS
21271 if (VT == MVT::i32 || VT == MVT::f32)
21272 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21273 if (VT == MVT::i16)
21274 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21275 if (VT == MVT::i8 || VT == MVT::i1)
21276 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21277 if (VT == MVT::i64)
21278 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21280 case 'r': // GENERAL_REGS
21281 case 'l': // INDEX_REGS
21282 if (VT == MVT::i8 || VT == MVT::i1)
21283 return std::make_pair(0U, &X86::GR8RegClass);
21284 if (VT == MVT::i16)
21285 return std::make_pair(0U, &X86::GR16RegClass);
21286 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21287 return std::make_pair(0U, &X86::GR32RegClass);
21288 return std::make_pair(0U, &X86::GR64RegClass);
21289 case 'R': // LEGACY_REGS
21290 if (VT == MVT::i8 || VT == MVT::i1)
21291 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21292 if (VT == MVT::i16)
21293 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21294 if (VT == MVT::i32 || !Subtarget->is64Bit())
21295 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21296 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21297 case 'f': // FP Stack registers.
21298 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21299 // value to the correct fpstack register class.
21300 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21301 return std::make_pair(0U, &X86::RFP32RegClass);
21302 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21303 return std::make_pair(0U, &X86::RFP64RegClass);
21304 return std::make_pair(0U, &X86::RFP80RegClass);
21305 case 'y': // MMX_REGS if MMX allowed.
21306 if (!Subtarget->hasMMX()) break;
21307 return std::make_pair(0U, &X86::VR64RegClass);
21308 case 'Y': // SSE_REGS if SSE2 allowed
21309 if (!Subtarget->hasSSE2()) break;
21311 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21312 if (!Subtarget->hasSSE1()) break;
21314 switch (VT.SimpleTy) {
21316 // Scalar SSE types.
21319 return std::make_pair(0U, &X86::FR32RegClass);
21322 return std::make_pair(0U, &X86::FR64RegClass);
21330 return std::make_pair(0U, &X86::VR128RegClass);
21338 return std::make_pair(0U, &X86::VR256RegClass);
21343 return std::make_pair(0U, &X86::VR512RegClass);
21349 // Use the default implementation in TargetLowering to convert the register
21350 // constraint into a member of a register class.
21351 std::pair<unsigned, const TargetRegisterClass*> Res;
21352 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21354 // Not found as a standard register?
21356 // Map st(0) -> st(7) -> ST0
21357 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21358 tolower(Constraint[1]) == 's' &&
21359 tolower(Constraint[2]) == 't' &&
21360 Constraint[3] == '(' &&
21361 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21362 Constraint[5] == ')' &&
21363 Constraint[6] == '}') {
21365 Res.first = X86::ST0+Constraint[4]-'0';
21366 Res.second = &X86::RFP80RegClass;
21370 // GCC allows "st(0)" to be called just plain "st".
21371 if (StringRef("{st}").equals_lower(Constraint)) {
21372 Res.first = X86::ST0;
21373 Res.second = &X86::RFP80RegClass;
21378 if (StringRef("{flags}").equals_lower(Constraint)) {
21379 Res.first = X86::EFLAGS;
21380 Res.second = &X86::CCRRegClass;
21384 // 'A' means EAX + EDX.
21385 if (Constraint == "A") {
21386 Res.first = X86::EAX;
21387 Res.second = &X86::GR32_ADRegClass;
21393 // Otherwise, check to see if this is a register class of the wrong value
21394 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21395 // turn into {ax},{dx}.
21396 if (Res.second->hasType(VT))
21397 return Res; // Correct type already, nothing to do.
21399 // All of the single-register GCC register classes map their values onto
21400 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21401 // really want an 8-bit or 32-bit register, map to the appropriate register
21402 // class and return the appropriate register.
21403 if (Res.second == &X86::GR16RegClass) {
21404 if (VT == MVT::i8 || VT == MVT::i1) {
21405 unsigned DestReg = 0;
21406 switch (Res.first) {
21408 case X86::AX: DestReg = X86::AL; break;
21409 case X86::DX: DestReg = X86::DL; break;
21410 case X86::CX: DestReg = X86::CL; break;
21411 case X86::BX: DestReg = X86::BL; break;
21414 Res.first = DestReg;
21415 Res.second = &X86::GR8RegClass;
21417 } else if (VT == MVT::i32 || VT == MVT::f32) {
21418 unsigned DestReg = 0;
21419 switch (Res.first) {
21421 case X86::AX: DestReg = X86::EAX; break;
21422 case X86::DX: DestReg = X86::EDX; break;
21423 case X86::CX: DestReg = X86::ECX; break;
21424 case X86::BX: DestReg = X86::EBX; break;
21425 case X86::SI: DestReg = X86::ESI; break;
21426 case X86::DI: DestReg = X86::EDI; break;
21427 case X86::BP: DestReg = X86::EBP; break;
21428 case X86::SP: DestReg = X86::ESP; break;
21431 Res.first = DestReg;
21432 Res.second = &X86::GR32RegClass;
21434 } else if (VT == MVT::i64 || VT == MVT::f64) {
21435 unsigned DestReg = 0;
21436 switch (Res.first) {
21438 case X86::AX: DestReg = X86::RAX; break;
21439 case X86::DX: DestReg = X86::RDX; break;
21440 case X86::CX: DestReg = X86::RCX; break;
21441 case X86::BX: DestReg = X86::RBX; break;
21442 case X86::SI: DestReg = X86::RSI; break;
21443 case X86::DI: DestReg = X86::RDI; break;
21444 case X86::BP: DestReg = X86::RBP; break;
21445 case X86::SP: DestReg = X86::RSP; break;
21448 Res.first = DestReg;
21449 Res.second = &X86::GR64RegClass;
21452 } else if (Res.second == &X86::FR32RegClass ||
21453 Res.second == &X86::FR64RegClass ||
21454 Res.second == &X86::VR128RegClass ||
21455 Res.second == &X86::VR256RegClass ||
21456 Res.second == &X86::FR32XRegClass ||
21457 Res.second == &X86::FR64XRegClass ||
21458 Res.second == &X86::VR128XRegClass ||
21459 Res.second == &X86::VR256XRegClass ||
21460 Res.second == &X86::VR512RegClass) {
21461 // Handle references to XMM physical registers that got mapped into the
21462 // wrong class. This can happen with constraints like {xmm0} where the
21463 // target independent register mapper will just pick the first match it can
21464 // find, ignoring the required type.
21466 if (VT == MVT::f32 || VT == MVT::i32)
21467 Res.second = &X86::FR32RegClass;
21468 else if (VT == MVT::f64 || VT == MVT::i64)
21469 Res.second = &X86::FR64RegClass;
21470 else if (X86::VR128RegClass.hasType(VT))
21471 Res.second = &X86::VR128RegClass;
21472 else if (X86::VR256RegClass.hasType(VT))
21473 Res.second = &X86::VR256RegClass;
21474 else if (X86::VR512RegClass.hasType(VT))
21475 Res.second = &X86::VR512RegClass;
21481 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21483 // Scaling factors are not free at all.
21484 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21485 // will take 2 allocations in the out of order engine instead of 1
21486 // for plain addressing mode, i.e. inst (reg1).
21488 // vaddps (%rsi,%drx), %ymm0, %ymm1
21489 // Requires two allocations (one for the load, one for the computation)
21491 // vaddps (%rsi), %ymm0, %ymm1
21492 // Requires just 1 allocation, i.e., freeing allocations for other operations
21493 // and having less micro operations to execute.
21495 // For some X86 architectures, this is even worse because for instance for
21496 // stores, the complex addressing mode forces the instruction to use the
21497 // "load" ports instead of the dedicated "store" port.
21498 // E.g., on Haswell:
21499 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21500 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21501 if (isLegalAddressingMode(AM, Ty))
21502 // Scale represents reg2 * scale, thus account for 1
21503 // as soon as we use a second register.
21504 return AM.Scale != 0;