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::f32, Expand);
444 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
445 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
447 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
448 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
449 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
450 if (Subtarget->is64Bit())
451 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
452 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
453 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
454 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
455 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
456 setOperationAction(ISD::FREM , MVT::f32 , Expand);
457 setOperationAction(ISD::FREM , MVT::f64 , Expand);
458 setOperationAction(ISD::FREM , MVT::f80 , Expand);
459 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
461 // Promote the i8 variants and force them on up to i32 which has a shorter
463 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
464 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
466 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
467 if (Subtarget->hasBMI()) {
468 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
469 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
473 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
474 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
475 if (Subtarget->is64Bit())
476 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
479 if (Subtarget->hasLZCNT()) {
480 // When promoting the i8 variants, force them to i32 for a shorter
482 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
483 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
485 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
487 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
488 if (Subtarget->is64Bit())
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
491 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
492 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
493 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
494 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
495 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
497 if (Subtarget->is64Bit()) {
498 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
503 if (Subtarget->hasPOPCNT()) {
504 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
506 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
507 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
508 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
509 if (Subtarget->is64Bit())
510 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
513 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
515 if (!Subtarget->hasMOVBE())
516 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
518 // These should be promoted to a larger select which is supported.
519 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
520 // X86 wants to expand cmov itself.
521 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
522 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
523 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
524 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
525 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
526 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
527 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
528 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
530 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
531 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
532 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
533 if (Subtarget->is64Bit()) {
534 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
535 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
537 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
538 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
539 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
540 // support continuation, user-level threading, and etc.. As a result, no
541 // other SjLj exception interfaces are implemented and please don't build
542 // your own exception handling based on them.
543 // LLVM/Clang supports zero-cost DWARF exception handling.
544 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
545 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
548 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
549 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
550 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
551 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
552 if (Subtarget->is64Bit())
553 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
554 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
555 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
556 if (Subtarget->is64Bit()) {
557 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
558 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
559 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
560 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
561 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
563 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
564 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
565 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
566 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
567 if (Subtarget->is64Bit()) {
568 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
569 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
570 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
573 if (Subtarget->hasSSE1())
574 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
576 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
578 // Expand certain atomics
579 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
581 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
583 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
586 if (!Subtarget->is64Bit()) {
587 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
595 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
596 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
597 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
598 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
601 if (Subtarget->hasCmpxchg16b()) {
602 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
605 // FIXME - use subtarget debug flags
606 if (!Subtarget->isTargetDarwin() &&
607 !Subtarget->isTargetELF() &&
608 !Subtarget->isTargetCygMing()) {
609 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
612 if (Subtarget->is64Bit()) {
613 setExceptionPointerRegister(X86::RAX);
614 setExceptionSelectorRegister(X86::RDX);
616 setExceptionPointerRegister(X86::EAX);
617 setExceptionSelectorRegister(X86::EDX);
619 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
620 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
622 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
623 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
625 setOperationAction(ISD::TRAP, MVT::Other, Legal);
626 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
628 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
629 setOperationAction(ISD::VASTART , MVT::Other, Custom);
630 setOperationAction(ISD::VAEND , MVT::Other, Expand);
631 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
632 // TargetInfo::X86_64ABIBuiltinVaList
633 setOperationAction(ISD::VAARG , MVT::Other, Custom);
634 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
636 // TargetInfo::CharPtrBuiltinVaList
637 setOperationAction(ISD::VAARG , MVT::Other, Expand);
638 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
641 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
642 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
644 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
645 MVT::i64 : MVT::i32, Custom);
647 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
648 // f32 and f64 use SSE.
649 // Set up the FP register classes.
650 addRegisterClass(MVT::f32, &X86::FR32RegClass);
651 addRegisterClass(MVT::f64, &X86::FR64RegClass);
653 // Use ANDPD to simulate FABS.
654 setOperationAction(ISD::FABS , MVT::f64, Custom);
655 setOperationAction(ISD::FABS , MVT::f32, Custom);
657 // Use XORP to simulate FNEG.
658 setOperationAction(ISD::FNEG , MVT::f64, Custom);
659 setOperationAction(ISD::FNEG , MVT::f32, Custom);
661 // Use ANDPD and ORPD to simulate FCOPYSIGN.
662 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
663 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
665 // Lower this to FGETSIGNx86 plus an AND.
666 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
667 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
669 // We don't support sin/cos/fmod
670 setOperationAction(ISD::FSIN , MVT::f64, Expand);
671 setOperationAction(ISD::FCOS , MVT::f64, Expand);
672 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
673 setOperationAction(ISD::FSIN , MVT::f32, Expand);
674 setOperationAction(ISD::FCOS , MVT::f32, Expand);
675 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
677 // Expand FP immediates into loads from the stack, except for the special
679 addLegalFPImmediate(APFloat(+0.0)); // xorpd
680 addLegalFPImmediate(APFloat(+0.0f)); // xorps
681 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
682 // Use SSE for f32, x87 for f64.
683 // Set up the FP register classes.
684 addRegisterClass(MVT::f32, &X86::FR32RegClass);
685 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
687 // Use ANDPS to simulate FABS.
688 setOperationAction(ISD::FABS , MVT::f32, Custom);
690 // Use XORP to simulate FNEG.
691 setOperationAction(ISD::FNEG , MVT::f32, Custom);
693 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
695 // Use ANDPS and ORPS to simulate FCOPYSIGN.
696 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
697 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
699 // We don't support sin/cos/fmod
700 setOperationAction(ISD::FSIN , MVT::f32, Expand);
701 setOperationAction(ISD::FCOS , MVT::f32, Expand);
702 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
704 // Special cases we handle for FP constants.
705 addLegalFPImmediate(APFloat(+0.0f)); // xorps
706 addLegalFPImmediate(APFloat(+0.0)); // FLD0
707 addLegalFPImmediate(APFloat(+1.0)); // FLD1
708 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
709 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
711 if (!TM.Options.UnsafeFPMath) {
712 setOperationAction(ISD::FSIN , MVT::f64, Expand);
713 setOperationAction(ISD::FCOS , MVT::f64, Expand);
714 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
716 } else if (!TM.Options.UseSoftFloat) {
717 // f32 and f64 in x87.
718 // Set up the FP register classes.
719 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
720 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
722 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
723 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
724 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
725 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
727 if (!TM.Options.UnsafeFPMath) {
728 setOperationAction(ISD::FSIN , MVT::f64, Expand);
729 setOperationAction(ISD::FSIN , MVT::f32, Expand);
730 setOperationAction(ISD::FCOS , MVT::f64, Expand);
731 setOperationAction(ISD::FCOS , MVT::f32, Expand);
732 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
735 addLegalFPImmediate(APFloat(+0.0)); // FLD0
736 addLegalFPImmediate(APFloat(+1.0)); // FLD1
737 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
738 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
739 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
740 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
741 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
742 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
745 // We don't support FMA.
746 setOperationAction(ISD::FMA, MVT::f64, Expand);
747 setOperationAction(ISD::FMA, MVT::f32, Expand);
749 // Long double always uses X87.
750 if (!TM.Options.UseSoftFloat) {
751 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
752 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
753 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
755 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
756 addLegalFPImmediate(TmpFlt); // FLD0
758 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
761 APFloat TmpFlt2(+1.0);
762 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
764 addLegalFPImmediate(TmpFlt2); // FLD1
765 TmpFlt2.changeSign();
766 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
769 if (!TM.Options.UnsafeFPMath) {
770 setOperationAction(ISD::FSIN , MVT::f80, Expand);
771 setOperationAction(ISD::FCOS , MVT::f80, Expand);
772 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
775 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
776 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
777 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
778 setOperationAction(ISD::FRINT, MVT::f80, Expand);
779 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
780 setOperationAction(ISD::FMA, MVT::f80, Expand);
783 // Always use a library call for pow.
784 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
785 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
786 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
788 setOperationAction(ISD::FLOG, MVT::f80, Expand);
789 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
790 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
791 setOperationAction(ISD::FEXP, MVT::f80, Expand);
792 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
794 // First set operation action for all vector types to either promote
795 // (for widening) or expand (for scalarization). Then we will selectively
796 // turn on ones that can be effectively codegen'd.
797 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
798 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
799 MVT VT = (MVT::SimpleValueType)i;
800 setOperationAction(ISD::ADD , VT, Expand);
801 setOperationAction(ISD::SUB , VT, Expand);
802 setOperationAction(ISD::FADD, VT, Expand);
803 setOperationAction(ISD::FNEG, VT, Expand);
804 setOperationAction(ISD::FSUB, VT, Expand);
805 setOperationAction(ISD::MUL , VT, Expand);
806 setOperationAction(ISD::FMUL, VT, Expand);
807 setOperationAction(ISD::SDIV, VT, Expand);
808 setOperationAction(ISD::UDIV, VT, Expand);
809 setOperationAction(ISD::FDIV, VT, Expand);
810 setOperationAction(ISD::SREM, VT, Expand);
811 setOperationAction(ISD::UREM, VT, Expand);
812 setOperationAction(ISD::LOAD, VT, Expand);
813 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
814 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
815 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
816 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
817 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
818 setOperationAction(ISD::FABS, VT, Expand);
819 setOperationAction(ISD::FSIN, VT, Expand);
820 setOperationAction(ISD::FSINCOS, VT, Expand);
821 setOperationAction(ISD::FCOS, VT, Expand);
822 setOperationAction(ISD::FSINCOS, VT, Expand);
823 setOperationAction(ISD::FREM, VT, Expand);
824 setOperationAction(ISD::FMA, VT, Expand);
825 setOperationAction(ISD::FPOWI, VT, Expand);
826 setOperationAction(ISD::FSQRT, VT, Expand);
827 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
828 setOperationAction(ISD::FFLOOR, VT, Expand);
829 setOperationAction(ISD::FCEIL, VT, Expand);
830 setOperationAction(ISD::FTRUNC, VT, Expand);
831 setOperationAction(ISD::FRINT, VT, Expand);
832 setOperationAction(ISD::FNEARBYINT, VT, Expand);
833 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
834 setOperationAction(ISD::MULHS, VT, Expand);
835 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::MULHU, VT, Expand);
837 setOperationAction(ISD::SDIVREM, VT, Expand);
838 setOperationAction(ISD::UDIVREM, VT, Expand);
839 setOperationAction(ISD::FPOW, VT, Expand);
840 setOperationAction(ISD::CTPOP, VT, Expand);
841 setOperationAction(ISD::CTTZ, VT, Expand);
842 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
843 setOperationAction(ISD::CTLZ, VT, Expand);
844 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
845 setOperationAction(ISD::SHL, VT, Expand);
846 setOperationAction(ISD::SRA, VT, Expand);
847 setOperationAction(ISD::SRL, VT, Expand);
848 setOperationAction(ISD::ROTL, VT, Expand);
849 setOperationAction(ISD::ROTR, VT, Expand);
850 setOperationAction(ISD::BSWAP, VT, Expand);
851 setOperationAction(ISD::SETCC, VT, Expand);
852 setOperationAction(ISD::FLOG, VT, Expand);
853 setOperationAction(ISD::FLOG2, VT, Expand);
854 setOperationAction(ISD::FLOG10, VT, Expand);
855 setOperationAction(ISD::FEXP, VT, Expand);
856 setOperationAction(ISD::FEXP2, VT, Expand);
857 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
858 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
859 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
860 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
861 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
862 setOperationAction(ISD::TRUNCATE, VT, Expand);
863 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
864 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
865 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
866 setOperationAction(ISD::VSELECT, VT, Expand);
867 setOperationAction(ISD::SELECT_CC, VT, Expand);
868 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
869 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
870 setTruncStoreAction(VT,
871 (MVT::SimpleValueType)InnerVT, Expand);
872 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
873 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
874 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
877 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
878 // with -msoft-float, disable use of MMX as well.
879 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
880 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
881 // No operations on x86mmx supported, everything uses intrinsics.
884 // MMX-sized vectors (other than x86mmx) are expected to be expanded
885 // into smaller operations.
886 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
887 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
888 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
889 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
890 setOperationAction(ISD::AND, MVT::v8i8, Expand);
891 setOperationAction(ISD::AND, MVT::v4i16, Expand);
892 setOperationAction(ISD::AND, MVT::v2i32, Expand);
893 setOperationAction(ISD::AND, MVT::v1i64, Expand);
894 setOperationAction(ISD::OR, MVT::v8i8, Expand);
895 setOperationAction(ISD::OR, MVT::v4i16, Expand);
896 setOperationAction(ISD::OR, MVT::v2i32, Expand);
897 setOperationAction(ISD::OR, MVT::v1i64, Expand);
898 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
899 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
900 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
901 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
902 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
903 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
904 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
905 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
906 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
907 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
908 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
909 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
910 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
911 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
912 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
913 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
914 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
916 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
917 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
919 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
920 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
921 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
922 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
923 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
924 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
925 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
926 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
927 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
928 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
929 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
930 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
933 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
934 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
936 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
937 // registers cannot be used even for integer operations.
938 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
939 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
940 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
941 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
943 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
944 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
945 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
946 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
947 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
948 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
949 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
950 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
951 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
952 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
953 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
954 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
955 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
956 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
957 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
958 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
959 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
960 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
961 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
962 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
963 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
964 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
966 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
967 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
968 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
969 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
971 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
972 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
973 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
974 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
975 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
977 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
978 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
979 MVT VT = (MVT::SimpleValueType)i;
980 // Do not attempt to custom lower non-power-of-2 vectors
981 if (!isPowerOf2_32(VT.getVectorNumElements()))
983 // Do not attempt to custom lower non-128-bit vectors
984 if (!VT.is128BitVector())
986 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
991 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
992 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
993 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
994 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
998 if (Subtarget->is64Bit()) {
999 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1004 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1005 MVT VT = (MVT::SimpleValueType)i;
1007 // Do not attempt to promote non-128-bit vectors
1008 if (!VT.is128BitVector())
1011 setOperationAction(ISD::AND, VT, Promote);
1012 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1013 setOperationAction(ISD::OR, VT, Promote);
1014 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1015 setOperationAction(ISD::XOR, VT, Promote);
1016 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1017 setOperationAction(ISD::LOAD, VT, Promote);
1018 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1019 setOperationAction(ISD::SELECT, VT, Promote);
1020 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1023 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1025 // Custom lower v2i64 and v2f64 selects.
1026 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1027 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1028 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1029 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1031 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1032 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1034 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1035 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1036 // As there is no 64-bit GPR available, we need build a special custom
1037 // sequence to convert from v2i32 to v2f32.
1038 if (!Subtarget->is64Bit())
1039 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1041 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1042 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1044 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1046 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1047 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1048 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1051 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1052 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1055 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1060 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1063 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1064 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1065 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1066 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1067 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1068 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1069 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1070 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1071 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1072 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1074 // FIXME: Do we need to handle scalar-to-vector here?
1075 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1077 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1078 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1079 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1080 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1081 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1082 // There is no BLENDI for byte vectors. We don't need to custom lower
1083 // some vselects for now.
1084 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1086 // i8 and i16 vectors are custom , because the source register and source
1087 // source memory operand types are not the same width. f32 vectors are
1088 // custom since the immediate controlling the insert encodes additional
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1091 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1093 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1095 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1096 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1098 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1100 // FIXME: these should be Legal but thats only for the case where
1101 // the index is constant. For now custom expand to deal with that.
1102 if (Subtarget->is64Bit()) {
1103 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1108 if (Subtarget->hasSSE2()) {
1109 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1110 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1112 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1113 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1115 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1116 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1118 // In the customized shift lowering, the legal cases in AVX2 will be
1120 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1121 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1123 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1124 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1126 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1129 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1130 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1131 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1132 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1133 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1134 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1135 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1137 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1138 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1139 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1141 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1148 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1152 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1154 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1161 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1165 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1167 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1168 // even though v8i16 is a legal type.
1169 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1170 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1171 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1173 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1174 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1175 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1177 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1178 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1180 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1182 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1183 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1185 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1186 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1188 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1189 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1191 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1192 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1193 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1194 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1196 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1197 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1198 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1200 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1201 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1202 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1203 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1205 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1206 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1207 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1208 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1209 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1210 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1211 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1212 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1213 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1214 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1215 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1216 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1218 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1219 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1220 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1221 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1222 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1223 setOperationAction(ISD::FMA, MVT::f32, Legal);
1224 setOperationAction(ISD::FMA, MVT::f64, Legal);
1227 if (Subtarget->hasInt256()) {
1228 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1229 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1230 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1231 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1233 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1234 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1235 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1236 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1238 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1239 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1240 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1241 // Don't lower v32i8 because there is no 128-bit byte mul
1243 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1244 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1245 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1246 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1248 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1249 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1251 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1252 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1253 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1254 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1256 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1257 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1258 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1259 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1261 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1262 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1263 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1264 // Don't lower v32i8 because there is no 128-bit byte mul
1267 // In the customized shift lowering, the legal cases in AVX2 will be
1269 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1270 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1272 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1273 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1275 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1277 // Custom lower several nodes for 256-bit types.
1278 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1279 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1280 MVT VT = (MVT::SimpleValueType)i;
1282 // Extract subvector is special because the value type
1283 // (result) is 128-bit but the source is 256-bit wide.
1284 if (VT.is128BitVector())
1285 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1287 // Do not attempt to custom lower other non-256-bit vectors
1288 if (!VT.is256BitVector())
1291 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1292 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1293 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1294 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1295 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1296 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1297 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1300 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1301 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1302 MVT VT = (MVT::SimpleValueType)i;
1304 // Do not attempt to promote non-256-bit vectors
1305 if (!VT.is256BitVector())
1308 setOperationAction(ISD::AND, VT, Promote);
1309 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1310 setOperationAction(ISD::OR, VT, Promote);
1311 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1312 setOperationAction(ISD::XOR, VT, Promote);
1313 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1314 setOperationAction(ISD::LOAD, VT, Promote);
1315 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1316 setOperationAction(ISD::SELECT, VT, Promote);
1317 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1321 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1322 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1323 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1324 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1325 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1327 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1328 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1329 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1331 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1332 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1333 setOperationAction(ISD::XOR, MVT::i1, Legal);
1334 setOperationAction(ISD::OR, MVT::i1, Legal);
1335 setOperationAction(ISD::AND, MVT::i1, Legal);
1336 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1337 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1338 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1341 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1343 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1344 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1350 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1351 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1352 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1355 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1356 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1357 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1359 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1361 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1363 if (Subtarget->is64Bit()) {
1364 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1365 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1366 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1367 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1369 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1370 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1371 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1373 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1374 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1375 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1376 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1377 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1378 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1380 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1381 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1382 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1383 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1384 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1385 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1386 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1387 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1388 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1389 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1390 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1391 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1392 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1394 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1395 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1396 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1397 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1398 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1399 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1401 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1402 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1404 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1409 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1410 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1411 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1412 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1413 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1414 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1416 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1417 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1419 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1420 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1422 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1424 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1425 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1427 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1428 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1430 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1431 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1433 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1434 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1435 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1436 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1437 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1438 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1440 // Custom lower several nodes.
1441 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1442 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1443 MVT VT = (MVT::SimpleValueType)i;
1445 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1446 // Extract subvector is special because the value type
1447 // (result) is 256/128-bit but the source is 512-bit wide.
1448 if (VT.is128BitVector() || VT.is256BitVector())
1449 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1451 if (VT.getVectorElementType() == MVT::i1)
1452 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1454 // Do not attempt to custom lower other non-512-bit vectors
1455 if (!VT.is512BitVector())
1458 if ( EltSize >= 32) {
1459 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1460 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1461 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1462 setOperationAction(ISD::VSELECT, VT, Legal);
1463 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1464 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1465 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1468 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1469 MVT VT = (MVT::SimpleValueType)i;
1471 // Do not attempt to promote non-256-bit vectors
1472 if (!VT.is512BitVector())
1475 setOperationAction(ISD::SELECT, VT, Promote);
1476 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1480 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1481 // of this type with custom code.
1482 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1483 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1484 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1488 // We want to custom lower some of our intrinsics.
1489 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1490 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1491 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1492 if (!Subtarget->is64Bit())
1493 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1495 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1496 // handle type legalization for these operations here.
1498 // FIXME: We really should do custom legalization for addition and
1499 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1500 // than generic legalization for 64-bit multiplication-with-overflow, though.
1501 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1502 // Add/Sub/Mul with overflow operations are custom lowered.
1504 setOperationAction(ISD::SADDO, VT, Custom);
1505 setOperationAction(ISD::UADDO, VT, Custom);
1506 setOperationAction(ISD::SSUBO, VT, Custom);
1507 setOperationAction(ISD::USUBO, VT, Custom);
1508 setOperationAction(ISD::SMULO, VT, Custom);
1509 setOperationAction(ISD::UMULO, VT, Custom);
1512 // There are no 8-bit 3-address imul/mul instructions
1513 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1514 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1516 if (!Subtarget->is64Bit()) {
1517 // These libcalls are not available in 32-bit.
1518 setLibcallName(RTLIB::SHL_I128, nullptr);
1519 setLibcallName(RTLIB::SRL_I128, nullptr);
1520 setLibcallName(RTLIB::SRA_I128, nullptr);
1523 // Combine sin / cos into one node or libcall if possible.
1524 if (Subtarget->hasSinCos()) {
1525 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1526 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1527 if (Subtarget->isTargetDarwin()) {
1528 // For MacOSX, we don't want to the normal expansion of a libcall to
1529 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1531 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1532 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1536 if (Subtarget->isTargetWin64()) {
1537 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1538 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1539 setOperationAction(ISD::SREM, MVT::i128, Custom);
1540 setOperationAction(ISD::UREM, MVT::i128, Custom);
1541 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1542 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1545 // We have target-specific dag combine patterns for the following nodes:
1546 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1547 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1548 setTargetDAGCombine(ISD::VSELECT);
1549 setTargetDAGCombine(ISD::SELECT);
1550 setTargetDAGCombine(ISD::SHL);
1551 setTargetDAGCombine(ISD::SRA);
1552 setTargetDAGCombine(ISD::SRL);
1553 setTargetDAGCombine(ISD::OR);
1554 setTargetDAGCombine(ISD::AND);
1555 setTargetDAGCombine(ISD::ADD);
1556 setTargetDAGCombine(ISD::FADD);
1557 setTargetDAGCombine(ISD::FSUB);
1558 setTargetDAGCombine(ISD::FMA);
1559 setTargetDAGCombine(ISD::SUB);
1560 setTargetDAGCombine(ISD::LOAD);
1561 setTargetDAGCombine(ISD::STORE);
1562 setTargetDAGCombine(ISD::ZERO_EXTEND);
1563 setTargetDAGCombine(ISD::ANY_EXTEND);
1564 setTargetDAGCombine(ISD::SIGN_EXTEND);
1565 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1566 setTargetDAGCombine(ISD::TRUNCATE);
1567 setTargetDAGCombine(ISD::SINT_TO_FP);
1568 setTargetDAGCombine(ISD::SETCC);
1569 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1570 setTargetDAGCombine(ISD::BUILD_VECTOR);
1571 if (Subtarget->is64Bit())
1572 setTargetDAGCombine(ISD::MUL);
1573 setTargetDAGCombine(ISD::XOR);
1575 computeRegisterProperties();
1577 // On Darwin, -Os means optimize for size without hurting performance,
1578 // do not reduce the limit.
1579 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1580 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1581 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1582 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1583 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1584 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1585 setPrefLoopAlignment(4); // 2^4 bytes.
1587 // Predictable cmov don't hurt on atom because it's in-order.
1588 PredictableSelectIsExpensive = !Subtarget->isAtom();
1590 setPrefFunctionAlignment(4); // 2^4 bytes.
1593 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1595 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1597 if (Subtarget->hasAVX512())
1598 switch(VT.getVectorNumElements()) {
1599 case 8: return MVT::v8i1;
1600 case 16: return MVT::v16i1;
1603 return VT.changeVectorElementTypeToInteger();
1606 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1607 /// the desired ByVal argument alignment.
1608 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1611 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1612 if (VTy->getBitWidth() == 128)
1614 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1615 unsigned EltAlign = 0;
1616 getMaxByValAlign(ATy->getElementType(), EltAlign);
1617 if (EltAlign > MaxAlign)
1618 MaxAlign = EltAlign;
1619 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1620 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1621 unsigned EltAlign = 0;
1622 getMaxByValAlign(STy->getElementType(i), EltAlign);
1623 if (EltAlign > MaxAlign)
1624 MaxAlign = EltAlign;
1631 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1632 /// function arguments in the caller parameter area. For X86, aggregates
1633 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1634 /// are at 4-byte boundaries.
1635 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1636 if (Subtarget->is64Bit()) {
1637 // Max of 8 and alignment of type.
1638 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1645 if (Subtarget->hasSSE1())
1646 getMaxByValAlign(Ty, Align);
1650 /// getOptimalMemOpType - Returns the target specific optimal type for load
1651 /// and store operations as a result of memset, memcpy, and memmove
1652 /// lowering. If DstAlign is zero that means it's safe to destination
1653 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1654 /// means there isn't a need to check it against alignment requirement,
1655 /// probably because the source does not need to be loaded. If 'IsMemset' is
1656 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1657 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1658 /// source is constant so it does not need to be loaded.
1659 /// It returns EVT::Other if the type should be determined using generic
1660 /// target-independent logic.
1662 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1663 unsigned DstAlign, unsigned SrcAlign,
1664 bool IsMemset, bool ZeroMemset,
1666 MachineFunction &MF) const {
1667 const Function *F = MF.getFunction();
1668 if ((!IsMemset || ZeroMemset) &&
1669 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1670 Attribute::NoImplicitFloat)) {
1672 (Subtarget->isUnalignedMemAccessFast() ||
1673 ((DstAlign == 0 || DstAlign >= 16) &&
1674 (SrcAlign == 0 || SrcAlign >= 16)))) {
1676 if (Subtarget->hasInt256())
1678 if (Subtarget->hasFp256())
1681 if (Subtarget->hasSSE2())
1683 if (Subtarget->hasSSE1())
1685 } else if (!MemcpyStrSrc && Size >= 8 &&
1686 !Subtarget->is64Bit() &&
1687 Subtarget->hasSSE2()) {
1688 // Do not use f64 to lower memcpy if source is string constant. It's
1689 // better to use i32 to avoid the loads.
1693 if (Subtarget->is64Bit() && Size >= 8)
1698 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1700 return X86ScalarSSEf32;
1701 else if (VT == MVT::f64)
1702 return X86ScalarSSEf64;
1707 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1711 *Fast = Subtarget->isUnalignedMemAccessFast();
1715 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1716 /// current function. The returned value is a member of the
1717 /// MachineJumpTableInfo::JTEntryKind enum.
1718 unsigned X86TargetLowering::getJumpTableEncoding() const {
1719 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1721 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1722 Subtarget->isPICStyleGOT())
1723 return MachineJumpTableInfo::EK_Custom32;
1725 // Otherwise, use the normal jump table encoding heuristics.
1726 return TargetLowering::getJumpTableEncoding();
1730 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1731 const MachineBasicBlock *MBB,
1732 unsigned uid,MCContext &Ctx) const{
1733 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1734 Subtarget->isPICStyleGOT());
1735 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1737 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1738 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1741 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1743 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1744 SelectionDAG &DAG) const {
1745 if (!Subtarget->is64Bit())
1746 // This doesn't have SDLoc associated with it, but is not really the
1747 // same as a Register.
1748 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1752 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1753 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1755 const MCExpr *X86TargetLowering::
1756 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1757 MCContext &Ctx) const {
1758 // X86-64 uses RIP relative addressing based on the jump table label.
1759 if (Subtarget->isPICStyleRIPRel())
1760 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1762 // Otherwise, the reference is relative to the PIC base.
1763 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1766 // FIXME: Why this routine is here? Move to RegInfo!
1767 std::pair<const TargetRegisterClass*, uint8_t>
1768 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1769 const TargetRegisterClass *RRC = nullptr;
1771 switch (VT.SimpleTy) {
1773 return TargetLowering::findRepresentativeClass(VT);
1774 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1775 RRC = Subtarget->is64Bit() ?
1776 (const TargetRegisterClass*)&X86::GR64RegClass :
1777 (const TargetRegisterClass*)&X86::GR32RegClass;
1780 RRC = &X86::VR64RegClass;
1782 case MVT::f32: case MVT::f64:
1783 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1784 case MVT::v4f32: case MVT::v2f64:
1785 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1787 RRC = &X86::VR128RegClass;
1790 return std::make_pair(RRC, Cost);
1793 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1794 unsigned &Offset) const {
1795 if (!Subtarget->isTargetLinux())
1798 if (Subtarget->is64Bit()) {
1799 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1801 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1813 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1814 unsigned DestAS) const {
1815 assert(SrcAS != DestAS && "Expected different address spaces!");
1817 return SrcAS < 256 && DestAS < 256;
1820 //===----------------------------------------------------------------------===//
1821 // Return Value Calling Convention Implementation
1822 //===----------------------------------------------------------------------===//
1824 #include "X86GenCallingConv.inc"
1827 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1828 MachineFunction &MF, bool isVarArg,
1829 const SmallVectorImpl<ISD::OutputArg> &Outs,
1830 LLVMContext &Context) const {
1831 SmallVector<CCValAssign, 16> RVLocs;
1832 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1834 return CCInfo.CheckReturn(Outs, RetCC_X86);
1837 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1838 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1843 X86TargetLowering::LowerReturn(SDValue Chain,
1844 CallingConv::ID CallConv, bool isVarArg,
1845 const SmallVectorImpl<ISD::OutputArg> &Outs,
1846 const SmallVectorImpl<SDValue> &OutVals,
1847 SDLoc dl, SelectionDAG &DAG) const {
1848 MachineFunction &MF = DAG.getMachineFunction();
1849 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1851 SmallVector<CCValAssign, 16> RVLocs;
1852 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1853 RVLocs, *DAG.getContext());
1854 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1857 SmallVector<SDValue, 6> RetOps;
1858 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1859 // Operand #1 = Bytes To Pop
1860 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1863 // Copy the result values into the output registers.
1864 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1865 CCValAssign &VA = RVLocs[i];
1866 assert(VA.isRegLoc() && "Can only return in registers!");
1867 SDValue ValToCopy = OutVals[i];
1868 EVT ValVT = ValToCopy.getValueType();
1870 // Promote values to the appropriate types
1871 if (VA.getLocInfo() == CCValAssign::SExt)
1872 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1873 else if (VA.getLocInfo() == CCValAssign::ZExt)
1874 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1875 else if (VA.getLocInfo() == CCValAssign::AExt)
1876 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1877 else if (VA.getLocInfo() == CCValAssign::BCvt)
1878 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1880 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1881 "Unexpected FP-extend for return value.");
1883 // If this is x86-64, and we disabled SSE, we can't return FP values,
1884 // or SSE or MMX vectors.
1885 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1886 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1887 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1888 report_fatal_error("SSE register return with SSE disabled");
1890 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1891 // llvm-gcc has never done it right and no one has noticed, so this
1892 // should be OK for now.
1893 if (ValVT == MVT::f64 &&
1894 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1895 report_fatal_error("SSE2 register return with SSE2 disabled");
1897 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1898 // the RET instruction and handled by the FP Stackifier.
1899 if (VA.getLocReg() == X86::ST0 ||
1900 VA.getLocReg() == X86::ST1) {
1901 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1902 // change the value to the FP stack register class.
1903 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1904 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1905 RetOps.push_back(ValToCopy);
1906 // Don't emit a copytoreg.
1910 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1911 // which is returned in RAX / RDX.
1912 if (Subtarget->is64Bit()) {
1913 if (ValVT == MVT::x86mmx) {
1914 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1915 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1916 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1918 // If we don't have SSE2 available, convert to v4f32 so the generated
1919 // register is legal.
1920 if (!Subtarget->hasSSE2())
1921 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1926 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1927 Flag = Chain.getValue(1);
1928 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1931 // The x86-64 ABIs require that for returning structs by value we copy
1932 // the sret argument into %rax/%eax (depending on ABI) for the return.
1933 // Win32 requires us to put the sret argument to %eax as well.
1934 // We saved the argument into a virtual register in the entry block,
1935 // so now we copy the value out and into %rax/%eax.
1936 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1937 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1938 MachineFunction &MF = DAG.getMachineFunction();
1939 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1940 unsigned Reg = FuncInfo->getSRetReturnReg();
1942 "SRetReturnReg should have been set in LowerFormalArguments().");
1943 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1946 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1947 X86::RAX : X86::EAX;
1948 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1949 Flag = Chain.getValue(1);
1951 // RAX/EAX now acts like a return value.
1952 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1955 RetOps[0] = Chain; // Update chain.
1957 // Add the flag if we have it.
1959 RetOps.push_back(Flag);
1961 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1964 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1965 if (N->getNumValues() != 1)
1967 if (!N->hasNUsesOfValue(1, 0))
1970 SDValue TCChain = Chain;
1971 SDNode *Copy = *N->use_begin();
1972 if (Copy->getOpcode() == ISD::CopyToReg) {
1973 // If the copy has a glue operand, we conservatively assume it isn't safe to
1974 // perform a tail call.
1975 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1977 TCChain = Copy->getOperand(0);
1978 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1981 bool HasRet = false;
1982 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1984 if (UI->getOpcode() != X86ISD::RET_FLAG)
1997 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1998 ISD::NodeType ExtendKind) const {
2000 // TODO: Is this also valid on 32-bit?
2001 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2002 ReturnMVT = MVT::i8;
2004 ReturnMVT = MVT::i32;
2006 MVT MinVT = getRegisterType(ReturnMVT);
2007 return VT.bitsLT(MinVT) ? MinVT : VT;
2010 /// LowerCallResult - Lower the result values of a call into the
2011 /// appropriate copies out of appropriate physical registers.
2014 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2015 CallingConv::ID CallConv, bool isVarArg,
2016 const SmallVectorImpl<ISD::InputArg> &Ins,
2017 SDLoc dl, SelectionDAG &DAG,
2018 SmallVectorImpl<SDValue> &InVals) const {
2020 // Assign locations to each value returned by this call.
2021 SmallVector<CCValAssign, 16> RVLocs;
2022 bool Is64Bit = Subtarget->is64Bit();
2023 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2024 getTargetMachine(), RVLocs, *DAG.getContext());
2025 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2027 // Copy all of the result registers out of their specified physreg.
2028 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2029 CCValAssign &VA = RVLocs[i];
2030 EVT CopyVT = VA.getValVT();
2032 // If this is x86-64, and we disabled SSE, we can't return FP values
2033 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2034 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2035 report_fatal_error("SSE register return with SSE disabled");
2040 // If this is a call to a function that returns an fp value on the floating
2041 // point stack, we must guarantee the value is popped from the stack, so
2042 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2043 // if the return value is not used. We use the FpPOP_RETVAL instruction
2045 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2046 // If we prefer to use the value in xmm registers, copy it out as f80 and
2047 // use a truncate to move it from fp stack reg to xmm reg.
2048 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2049 SDValue Ops[] = { Chain, InFlag };
2050 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2051 MVT::Other, MVT::Glue, Ops), 1);
2052 Val = Chain.getValue(0);
2054 // Round the f80 to the right size, which also moves it to the appropriate
2056 if (CopyVT != VA.getValVT())
2057 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2058 // This truncation won't change the value.
2059 DAG.getIntPtrConstant(1));
2061 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2062 CopyVT, InFlag).getValue(1);
2063 Val = Chain.getValue(0);
2065 InFlag = Chain.getValue(2);
2066 InVals.push_back(Val);
2072 //===----------------------------------------------------------------------===//
2073 // C & StdCall & Fast Calling Convention implementation
2074 //===----------------------------------------------------------------------===//
2075 // StdCall calling convention seems to be standard for many Windows' API
2076 // routines and around. It differs from C calling convention just a little:
2077 // callee should clean up the stack, not caller. Symbols should be also
2078 // decorated in some fancy way :) It doesn't support any vector arguments.
2079 // For info on fast calling convention see Fast Calling Convention (tail call)
2080 // implementation LowerX86_32FastCCCallTo.
2082 /// CallIsStructReturn - Determines whether a call uses struct return
2084 enum StructReturnType {
2089 static StructReturnType
2090 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2092 return NotStructReturn;
2094 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2095 if (!Flags.isSRet())
2096 return NotStructReturn;
2097 if (Flags.isInReg())
2098 return RegStructReturn;
2099 return StackStructReturn;
2102 /// ArgsAreStructReturn - Determines whether a function uses struct
2103 /// return semantics.
2104 static StructReturnType
2105 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2107 return NotStructReturn;
2109 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2110 if (!Flags.isSRet())
2111 return NotStructReturn;
2112 if (Flags.isInReg())
2113 return RegStructReturn;
2114 return StackStructReturn;
2117 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2118 /// by "Src" to address "Dst" with size and alignment information specified by
2119 /// the specific parameter attribute. The copy will be passed as a byval
2120 /// function parameter.
2122 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2123 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2125 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2127 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2128 /*isVolatile*/false, /*AlwaysInline=*/true,
2129 MachinePointerInfo(), MachinePointerInfo());
2132 /// IsTailCallConvention - Return true if the calling convention is one that
2133 /// supports tail call optimization.
2134 static bool IsTailCallConvention(CallingConv::ID CC) {
2135 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2136 CC == CallingConv::HiPE);
2139 /// \brief Return true if the calling convention is a C calling convention.
2140 static bool IsCCallConvention(CallingConv::ID CC) {
2141 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2142 CC == CallingConv::X86_64_SysV);
2145 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2146 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2150 CallingConv::ID CalleeCC = CS.getCallingConv();
2151 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2157 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2158 /// a tailcall target by changing its ABI.
2159 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2160 bool GuaranteedTailCallOpt) {
2161 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2165 X86TargetLowering::LowerMemArgument(SDValue Chain,
2166 CallingConv::ID CallConv,
2167 const SmallVectorImpl<ISD::InputArg> &Ins,
2168 SDLoc dl, SelectionDAG &DAG,
2169 const CCValAssign &VA,
2170 MachineFrameInfo *MFI,
2172 // Create the nodes corresponding to a load from this parameter slot.
2173 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2174 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2175 getTargetMachine().Options.GuaranteedTailCallOpt);
2176 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2179 // If value is passed by pointer we have address passed instead of the value
2181 if (VA.getLocInfo() == CCValAssign::Indirect)
2182 ValVT = VA.getLocVT();
2184 ValVT = VA.getValVT();
2186 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2187 // changed with more analysis.
2188 // In case of tail call optimization mark all arguments mutable. Since they
2189 // could be overwritten by lowering of arguments in case of a tail call.
2190 if (Flags.isByVal()) {
2191 unsigned Bytes = Flags.getByValSize();
2192 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2193 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2194 return DAG.getFrameIndex(FI, getPointerTy());
2196 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2197 VA.getLocMemOffset(), isImmutable);
2198 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2199 return DAG.getLoad(ValVT, dl, Chain, FIN,
2200 MachinePointerInfo::getFixedStack(FI),
2201 false, false, false, 0);
2206 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2207 CallingConv::ID CallConv,
2209 const SmallVectorImpl<ISD::InputArg> &Ins,
2212 SmallVectorImpl<SDValue> &InVals)
2214 MachineFunction &MF = DAG.getMachineFunction();
2215 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2217 const Function* Fn = MF.getFunction();
2218 if (Fn->hasExternalLinkage() &&
2219 Subtarget->isTargetCygMing() &&
2220 Fn->getName() == "main")
2221 FuncInfo->setForceFramePointer(true);
2223 MachineFrameInfo *MFI = MF.getFrameInfo();
2224 bool Is64Bit = Subtarget->is64Bit();
2225 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2227 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2228 "Var args not supported with calling convention fastcc, ghc or hipe");
2230 // Assign locations to all of the incoming arguments.
2231 SmallVector<CCValAssign, 16> ArgLocs;
2232 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2233 ArgLocs, *DAG.getContext());
2235 // Allocate shadow area for Win64
2237 CCInfo.AllocateStack(32, 8);
2239 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2241 unsigned LastVal = ~0U;
2243 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2244 CCValAssign &VA = ArgLocs[i];
2245 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2247 assert(VA.getValNo() != LastVal &&
2248 "Don't support value assigned to multiple locs yet");
2250 LastVal = VA.getValNo();
2252 if (VA.isRegLoc()) {
2253 EVT RegVT = VA.getLocVT();
2254 const TargetRegisterClass *RC;
2255 if (RegVT == MVT::i32)
2256 RC = &X86::GR32RegClass;
2257 else if (Is64Bit && RegVT == MVT::i64)
2258 RC = &X86::GR64RegClass;
2259 else if (RegVT == MVT::f32)
2260 RC = &X86::FR32RegClass;
2261 else if (RegVT == MVT::f64)
2262 RC = &X86::FR64RegClass;
2263 else if (RegVT.is512BitVector())
2264 RC = &X86::VR512RegClass;
2265 else if (RegVT.is256BitVector())
2266 RC = &X86::VR256RegClass;
2267 else if (RegVT.is128BitVector())
2268 RC = &X86::VR128RegClass;
2269 else if (RegVT == MVT::x86mmx)
2270 RC = &X86::VR64RegClass;
2271 else if (RegVT == MVT::i1)
2272 RC = &X86::VK1RegClass;
2273 else if (RegVT == MVT::v8i1)
2274 RC = &X86::VK8RegClass;
2275 else if (RegVT == MVT::v16i1)
2276 RC = &X86::VK16RegClass;
2278 llvm_unreachable("Unknown argument type!");
2280 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2281 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2283 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2284 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2286 if (VA.getLocInfo() == CCValAssign::SExt)
2287 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2288 DAG.getValueType(VA.getValVT()));
2289 else if (VA.getLocInfo() == CCValAssign::ZExt)
2290 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2291 DAG.getValueType(VA.getValVT()));
2292 else if (VA.getLocInfo() == CCValAssign::BCvt)
2293 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2295 if (VA.isExtInLoc()) {
2296 // Handle MMX values passed in XMM regs.
2297 if (RegVT.isVector())
2298 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2300 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2303 assert(VA.isMemLoc());
2304 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2307 // If value is passed via pointer - do a load.
2308 if (VA.getLocInfo() == CCValAssign::Indirect)
2309 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2310 MachinePointerInfo(), false, false, false, 0);
2312 InVals.push_back(ArgValue);
2315 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2316 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2317 // The x86-64 ABIs require that for returning structs by value we copy
2318 // the sret argument into %rax/%eax (depending on ABI) for the return.
2319 // Win32 requires us to put the sret argument to %eax as well.
2320 // Save the argument into a virtual register so that we can access it
2321 // from the return points.
2322 if (Ins[i].Flags.isSRet()) {
2323 unsigned Reg = FuncInfo->getSRetReturnReg();
2325 MVT PtrTy = getPointerTy();
2326 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2327 FuncInfo->setSRetReturnReg(Reg);
2329 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2330 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2336 unsigned StackSize = CCInfo.getNextStackOffset();
2337 // Align stack specially for tail calls.
2338 if (FuncIsMadeTailCallSafe(CallConv,
2339 MF.getTarget().Options.GuaranteedTailCallOpt))
2340 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2342 // If the function takes variable number of arguments, make a frame index for
2343 // the start of the first vararg value... for expansion of llvm.va_start.
2345 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2346 CallConv != CallingConv::X86_ThisCall)) {
2347 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2350 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2352 // FIXME: We should really autogenerate these arrays
2353 static const MCPhysReg GPR64ArgRegsWin64[] = {
2354 X86::RCX, X86::RDX, X86::R8, X86::R9
2356 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2357 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2359 static const MCPhysReg XMMArgRegs64Bit[] = {
2360 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2361 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2363 const MCPhysReg *GPR64ArgRegs;
2364 unsigned NumXMMRegs = 0;
2367 // The XMM registers which might contain var arg parameters are shadowed
2368 // in their paired GPR. So we only need to save the GPR to their home
2370 TotalNumIntRegs = 4;
2371 GPR64ArgRegs = GPR64ArgRegsWin64;
2373 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2374 GPR64ArgRegs = GPR64ArgRegs64Bit;
2376 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2379 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2382 bool NoImplicitFloatOps = Fn->getAttributes().
2383 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2384 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2385 "SSE register cannot be used when SSE is disabled!");
2386 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2387 NoImplicitFloatOps) &&
2388 "SSE register cannot be used when SSE is disabled!");
2389 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2390 !Subtarget->hasSSE1())
2391 // Kernel mode asks for SSE to be disabled, so don't push them
2393 TotalNumXMMRegs = 0;
2396 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2397 // Get to the caller-allocated home save location. Add 8 to account
2398 // for the return address.
2399 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2400 FuncInfo->setRegSaveFrameIndex(
2401 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2402 // Fixup to set vararg frame on shadow area (4 x i64).
2404 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2406 // For X86-64, if there are vararg parameters that are passed via
2407 // registers, then we must store them to their spots on the stack so
2408 // they may be loaded by deferencing the result of va_next.
2409 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2410 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2411 FuncInfo->setRegSaveFrameIndex(
2412 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2416 // Store the integer parameter registers.
2417 SmallVector<SDValue, 8> MemOps;
2418 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2420 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2421 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2422 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2423 DAG.getIntPtrConstant(Offset));
2424 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2425 &X86::GR64RegClass);
2426 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2428 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2429 MachinePointerInfo::getFixedStack(
2430 FuncInfo->getRegSaveFrameIndex(), Offset),
2432 MemOps.push_back(Store);
2436 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2437 // Now store the XMM (fp + vector) parameter registers.
2438 SmallVector<SDValue, 11> SaveXMMOps;
2439 SaveXMMOps.push_back(Chain);
2441 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2442 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2443 SaveXMMOps.push_back(ALVal);
2445 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2446 FuncInfo->getRegSaveFrameIndex()));
2447 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2448 FuncInfo->getVarArgsFPOffset()));
2450 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2451 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2452 &X86::VR128RegClass);
2453 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2454 SaveXMMOps.push_back(Val);
2456 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2457 MVT::Other, SaveXMMOps));
2460 if (!MemOps.empty())
2461 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2465 // Some CCs need callee pop.
2466 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2467 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2468 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2470 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2471 // If this is an sret function, the return should pop the hidden pointer.
2472 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2473 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2474 argsAreStructReturn(Ins) == StackStructReturn)
2475 FuncInfo->setBytesToPopOnReturn(4);
2479 // RegSaveFrameIndex is X86-64 only.
2480 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2481 if (CallConv == CallingConv::X86_FastCall ||
2482 CallConv == CallingConv::X86_ThisCall)
2483 // fastcc functions can't have varargs.
2484 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2487 FuncInfo->setArgumentStackSize(StackSize);
2493 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2494 SDValue StackPtr, SDValue Arg,
2495 SDLoc dl, SelectionDAG &DAG,
2496 const CCValAssign &VA,
2497 ISD::ArgFlagsTy Flags) const {
2498 unsigned LocMemOffset = VA.getLocMemOffset();
2499 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2500 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2501 if (Flags.isByVal())
2502 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2504 return DAG.getStore(Chain, dl, Arg, PtrOff,
2505 MachinePointerInfo::getStack(LocMemOffset),
2509 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2510 /// optimization is performed and it is required.
2512 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2513 SDValue &OutRetAddr, SDValue Chain,
2514 bool IsTailCall, bool Is64Bit,
2515 int FPDiff, SDLoc dl) const {
2516 // Adjust the Return address stack slot.
2517 EVT VT = getPointerTy();
2518 OutRetAddr = getReturnAddressFrameIndex(DAG);
2520 // Load the "old" Return address.
2521 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2522 false, false, false, 0);
2523 return SDValue(OutRetAddr.getNode(), 1);
2526 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2527 /// optimization is performed and it is required (FPDiff!=0).
2528 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2529 SDValue Chain, SDValue RetAddrFrIdx,
2530 EVT PtrVT, unsigned SlotSize,
2531 int FPDiff, SDLoc dl) {
2532 // Store the return address to the appropriate stack slot.
2533 if (!FPDiff) return Chain;
2534 // Calculate the new stack slot for the return address.
2535 int NewReturnAddrFI =
2536 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2538 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2539 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2540 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2546 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2547 SmallVectorImpl<SDValue> &InVals) const {
2548 SelectionDAG &DAG = CLI.DAG;
2550 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2551 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2552 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2553 SDValue Chain = CLI.Chain;
2554 SDValue Callee = CLI.Callee;
2555 CallingConv::ID CallConv = CLI.CallConv;
2556 bool &isTailCall = CLI.IsTailCall;
2557 bool isVarArg = CLI.IsVarArg;
2559 MachineFunction &MF = DAG.getMachineFunction();
2560 bool Is64Bit = Subtarget->is64Bit();
2561 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2562 StructReturnType SR = callIsStructReturn(Outs);
2563 bool IsSibcall = false;
2565 if (MF.getTarget().Options.DisableTailCalls)
2568 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2570 // Force this to be a tail call. The verifier rules are enough to ensure
2571 // that we can lower this successfully without moving the return address
2574 } else if (isTailCall) {
2575 // Check if it's really possible to do a tail call.
2576 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2577 isVarArg, SR != NotStructReturn,
2578 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2579 Outs, OutVals, Ins, DAG);
2581 // Sibcalls are automatically detected tailcalls which do not require
2583 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2590 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2591 "Var args not supported with calling convention fastcc, ghc or hipe");
2593 // Analyze operands of the call, assigning locations to each operand.
2594 SmallVector<CCValAssign, 16> ArgLocs;
2595 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2596 ArgLocs, *DAG.getContext());
2598 // Allocate shadow area for Win64
2600 CCInfo.AllocateStack(32, 8);
2602 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2604 // Get a count of how many bytes are to be pushed on the stack.
2605 unsigned NumBytes = CCInfo.getNextStackOffset();
2607 // This is a sibcall. The memory operands are available in caller's
2608 // own caller's stack.
2610 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2611 IsTailCallConvention(CallConv))
2612 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2615 if (isTailCall && !IsSibcall && !IsMustTail) {
2616 // Lower arguments at fp - stackoffset + fpdiff.
2617 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2618 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2620 FPDiff = NumBytesCallerPushed - NumBytes;
2622 // Set the delta of movement of the returnaddr stackslot.
2623 // But only set if delta is greater than previous delta.
2624 if (FPDiff < X86Info->getTCReturnAddrDelta())
2625 X86Info->setTCReturnAddrDelta(FPDiff);
2628 unsigned NumBytesToPush = NumBytes;
2629 unsigned NumBytesToPop = NumBytes;
2631 // If we have an inalloca argument, all stack space has already been allocated
2632 // for us and be right at the top of the stack. We don't support multiple
2633 // arguments passed in memory when using inalloca.
2634 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2636 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2637 "an inalloca argument must be the only memory argument");
2641 Chain = DAG.getCALLSEQ_START(
2642 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2644 SDValue RetAddrFrIdx;
2645 // Load return address for tail calls.
2646 if (isTailCall && FPDiff)
2647 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2648 Is64Bit, FPDiff, dl);
2650 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2651 SmallVector<SDValue, 8> MemOpChains;
2654 // Walk the register/memloc assignments, inserting copies/loads. In the case
2655 // of tail call optimization arguments are handle later.
2656 const X86RegisterInfo *RegInfo =
2657 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2658 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2659 // Skip inalloca arguments, they have already been written.
2660 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2661 if (Flags.isInAlloca())
2664 CCValAssign &VA = ArgLocs[i];
2665 EVT RegVT = VA.getLocVT();
2666 SDValue Arg = OutVals[i];
2667 bool isByVal = Flags.isByVal();
2669 // Promote the value if needed.
2670 switch (VA.getLocInfo()) {
2671 default: llvm_unreachable("Unknown loc info!");
2672 case CCValAssign::Full: break;
2673 case CCValAssign::SExt:
2674 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2676 case CCValAssign::ZExt:
2677 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2679 case CCValAssign::AExt:
2680 if (RegVT.is128BitVector()) {
2681 // Special case: passing MMX values in XMM registers.
2682 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2683 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2684 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2686 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2688 case CCValAssign::BCvt:
2689 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2691 case CCValAssign::Indirect: {
2692 // Store the argument.
2693 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2694 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2695 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2696 MachinePointerInfo::getFixedStack(FI),
2703 if (VA.isRegLoc()) {
2704 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2705 if (isVarArg && IsWin64) {
2706 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2707 // shadow reg if callee is a varargs function.
2708 unsigned ShadowReg = 0;
2709 switch (VA.getLocReg()) {
2710 case X86::XMM0: ShadowReg = X86::RCX; break;
2711 case X86::XMM1: ShadowReg = X86::RDX; break;
2712 case X86::XMM2: ShadowReg = X86::R8; break;
2713 case X86::XMM3: ShadowReg = X86::R9; break;
2716 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2718 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2719 assert(VA.isMemLoc());
2720 if (!StackPtr.getNode())
2721 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2723 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2724 dl, DAG, VA, Flags));
2728 if (!MemOpChains.empty())
2729 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2731 if (Subtarget->isPICStyleGOT()) {
2732 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2735 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2736 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2738 // If we are tail calling and generating PIC/GOT style code load the
2739 // address of the callee into ECX. The value in ecx is used as target of
2740 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2741 // for tail calls on PIC/GOT architectures. Normally we would just put the
2742 // address of GOT into ebx and then call target@PLT. But for tail calls
2743 // ebx would be restored (since ebx is callee saved) before jumping to the
2746 // Note: The actual moving to ECX is done further down.
2747 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2748 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2749 !G->getGlobal()->hasProtectedVisibility())
2750 Callee = LowerGlobalAddress(Callee, DAG);
2751 else if (isa<ExternalSymbolSDNode>(Callee))
2752 Callee = LowerExternalSymbol(Callee, DAG);
2756 if (Is64Bit && isVarArg && !IsWin64) {
2757 // From AMD64 ABI document:
2758 // For calls that may call functions that use varargs or stdargs
2759 // (prototype-less calls or calls to functions containing ellipsis (...) in
2760 // the declaration) %al is used as hidden argument to specify the number
2761 // of SSE registers used. The contents of %al do not need to match exactly
2762 // the number of registers, but must be an ubound on the number of SSE
2763 // registers used and is in the range 0 - 8 inclusive.
2765 // Count the number of XMM registers allocated.
2766 static const MCPhysReg XMMArgRegs[] = {
2767 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2768 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2770 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2771 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2772 && "SSE registers cannot be used when SSE is disabled");
2774 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2775 DAG.getConstant(NumXMMRegs, MVT::i8)));
2778 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2779 // don't need this because the eligibility check rejects calls that require
2780 // shuffling arguments passed in memory.
2781 if (!IsSibcall && isTailCall) {
2782 // Force all the incoming stack arguments to be loaded from the stack
2783 // before any new outgoing arguments are stored to the stack, because the
2784 // outgoing stack slots may alias the incoming argument stack slots, and
2785 // the alias isn't otherwise explicit. This is slightly more conservative
2786 // than necessary, because it means that each store effectively depends
2787 // on every argument instead of just those arguments it would clobber.
2788 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2790 SmallVector<SDValue, 8> MemOpChains2;
2793 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2794 CCValAssign &VA = ArgLocs[i];
2797 assert(VA.isMemLoc());
2798 SDValue Arg = OutVals[i];
2799 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2800 // Skip inalloca arguments. They don't require any work.
2801 if (Flags.isInAlloca())
2803 // Create frame index.
2804 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2805 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2806 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2807 FIN = DAG.getFrameIndex(FI, getPointerTy());
2809 if (Flags.isByVal()) {
2810 // Copy relative to framepointer.
2811 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2812 if (!StackPtr.getNode())
2813 StackPtr = DAG.getCopyFromReg(Chain, dl,
2814 RegInfo->getStackRegister(),
2816 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2818 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2822 // Store relative to framepointer.
2823 MemOpChains2.push_back(
2824 DAG.getStore(ArgChain, dl, Arg, FIN,
2825 MachinePointerInfo::getFixedStack(FI),
2830 if (!MemOpChains2.empty())
2831 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2833 // Store the return address to the appropriate stack slot.
2834 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2835 getPointerTy(), RegInfo->getSlotSize(),
2839 // Build a sequence of copy-to-reg nodes chained together with token chain
2840 // and flag operands which copy the outgoing args into registers.
2842 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2843 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2844 RegsToPass[i].second, InFlag);
2845 InFlag = Chain.getValue(1);
2848 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2849 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2850 // In the 64-bit large code model, we have to make all calls
2851 // through a register, since the call instruction's 32-bit
2852 // pc-relative offset may not be large enough to hold the whole
2854 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2855 // If the callee is a GlobalAddress node (quite common, every direct call
2856 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2859 // We should use extra load for direct calls to dllimported functions in
2861 const GlobalValue *GV = G->getGlobal();
2862 if (!GV->hasDLLImportStorageClass()) {
2863 unsigned char OpFlags = 0;
2864 bool ExtraLoad = false;
2865 unsigned WrapperKind = ISD::DELETED_NODE;
2867 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2868 // external symbols most go through the PLT in PIC mode. If the symbol
2869 // has hidden or protected visibility, or if it is static or local, then
2870 // we don't need to use the PLT - we can directly call it.
2871 if (Subtarget->isTargetELF() &&
2872 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2873 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2874 OpFlags = X86II::MO_PLT;
2875 } else if (Subtarget->isPICStyleStubAny() &&
2876 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2877 (!Subtarget->getTargetTriple().isMacOSX() ||
2878 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2879 // PC-relative references to external symbols should go through $stub,
2880 // unless we're building with the leopard linker or later, which
2881 // automatically synthesizes these stubs.
2882 OpFlags = X86II::MO_DARWIN_STUB;
2883 } else if (Subtarget->isPICStyleRIPRel() &&
2884 isa<Function>(GV) &&
2885 cast<Function>(GV)->getAttributes().
2886 hasAttribute(AttributeSet::FunctionIndex,
2887 Attribute::NonLazyBind)) {
2888 // If the function is marked as non-lazy, generate an indirect call
2889 // which loads from the GOT directly. This avoids runtime overhead
2890 // at the cost of eager binding (and one extra byte of encoding).
2891 OpFlags = X86II::MO_GOTPCREL;
2892 WrapperKind = X86ISD::WrapperRIP;
2896 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2897 G->getOffset(), OpFlags);
2899 // Add a wrapper if needed.
2900 if (WrapperKind != ISD::DELETED_NODE)
2901 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2902 // Add extra indirection if needed.
2904 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2905 MachinePointerInfo::getGOT(),
2906 false, false, false, 0);
2908 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2909 unsigned char OpFlags = 0;
2911 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2912 // external symbols should go through the PLT.
2913 if (Subtarget->isTargetELF() &&
2914 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2915 OpFlags = X86II::MO_PLT;
2916 } else if (Subtarget->isPICStyleStubAny() &&
2917 (!Subtarget->getTargetTriple().isMacOSX() ||
2918 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2919 // PC-relative references to external symbols should go through $stub,
2920 // unless we're building with the leopard linker or later, which
2921 // automatically synthesizes these stubs.
2922 OpFlags = X86II::MO_DARWIN_STUB;
2925 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2929 // Returns a chain & a flag for retval copy to use.
2930 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2931 SmallVector<SDValue, 8> Ops;
2933 if (!IsSibcall && isTailCall) {
2934 Chain = DAG.getCALLSEQ_END(Chain,
2935 DAG.getIntPtrConstant(NumBytesToPop, true),
2936 DAG.getIntPtrConstant(0, true), InFlag, dl);
2937 InFlag = Chain.getValue(1);
2940 Ops.push_back(Chain);
2941 Ops.push_back(Callee);
2944 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2946 // Add argument registers to the end of the list so that they are known live
2948 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2949 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2950 RegsToPass[i].second.getValueType()));
2952 // Add a register mask operand representing the call-preserved registers.
2953 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2954 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2955 assert(Mask && "Missing call preserved mask for calling convention");
2956 Ops.push_back(DAG.getRegisterMask(Mask));
2958 if (InFlag.getNode())
2959 Ops.push_back(InFlag);
2963 //// If this is the first return lowered for this function, add the regs
2964 //// to the liveout set for the function.
2965 // This isn't right, although it's probably harmless on x86; liveouts
2966 // should be computed from returns not tail calls. Consider a void
2967 // function making a tail call to a function returning int.
2968 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2971 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2972 InFlag = Chain.getValue(1);
2974 // Create the CALLSEQ_END node.
2975 unsigned NumBytesForCalleeToPop;
2976 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2977 getTargetMachine().Options.GuaranteedTailCallOpt))
2978 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2979 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2980 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2981 SR == StackStructReturn)
2982 // If this is a call to a struct-return function, the callee
2983 // pops the hidden struct pointer, so we have to push it back.
2984 // This is common for Darwin/X86, Linux & Mingw32 targets.
2985 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2986 NumBytesForCalleeToPop = 4;
2988 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2990 // Returns a flag for retval copy to use.
2992 Chain = DAG.getCALLSEQ_END(Chain,
2993 DAG.getIntPtrConstant(NumBytesToPop, true),
2994 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2997 InFlag = Chain.getValue(1);
3000 // Handle result values, copying them out of physregs into vregs that we
3002 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3003 Ins, dl, DAG, InVals);
3006 //===----------------------------------------------------------------------===//
3007 // Fast Calling Convention (tail call) implementation
3008 //===----------------------------------------------------------------------===//
3010 // Like std call, callee cleans arguments, convention except that ECX is
3011 // reserved for storing the tail called function address. Only 2 registers are
3012 // free for argument passing (inreg). Tail call optimization is performed
3014 // * tailcallopt is enabled
3015 // * caller/callee are fastcc
3016 // On X86_64 architecture with GOT-style position independent code only local
3017 // (within module) calls are supported at the moment.
3018 // To keep the stack aligned according to platform abi the function
3019 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3020 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3021 // If a tail called function callee has more arguments than the caller the
3022 // caller needs to make sure that there is room to move the RETADDR to. This is
3023 // achieved by reserving an area the size of the argument delta right after the
3024 // original REtADDR, but before the saved framepointer or the spilled registers
3025 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3037 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3038 /// for a 16 byte align requirement.
3040 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3041 SelectionDAG& DAG) const {
3042 MachineFunction &MF = DAG.getMachineFunction();
3043 const TargetMachine &TM = MF.getTarget();
3044 const X86RegisterInfo *RegInfo =
3045 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3046 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3047 unsigned StackAlignment = TFI.getStackAlignment();
3048 uint64_t AlignMask = StackAlignment - 1;
3049 int64_t Offset = StackSize;
3050 unsigned SlotSize = RegInfo->getSlotSize();
3051 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3052 // Number smaller than 12 so just add the difference.
3053 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3055 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3056 Offset = ((~AlignMask) & Offset) + StackAlignment +
3057 (StackAlignment-SlotSize);
3062 /// MatchingStackOffset - Return true if the given stack call argument is
3063 /// already available in the same position (relatively) of the caller's
3064 /// incoming argument stack.
3066 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3067 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3068 const X86InstrInfo *TII) {
3069 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3071 if (Arg.getOpcode() == ISD::CopyFromReg) {
3072 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3073 if (!TargetRegisterInfo::isVirtualRegister(VR))
3075 MachineInstr *Def = MRI->getVRegDef(VR);
3078 if (!Flags.isByVal()) {
3079 if (!TII->isLoadFromStackSlot(Def, FI))
3082 unsigned Opcode = Def->getOpcode();
3083 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3084 Def->getOperand(1).isFI()) {
3085 FI = Def->getOperand(1).getIndex();
3086 Bytes = Flags.getByValSize();
3090 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3091 if (Flags.isByVal())
3092 // ByVal argument is passed in as a pointer but it's now being
3093 // dereferenced. e.g.
3094 // define @foo(%struct.X* %A) {
3095 // tail call @bar(%struct.X* byval %A)
3098 SDValue Ptr = Ld->getBasePtr();
3099 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3102 FI = FINode->getIndex();
3103 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3104 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3105 FI = FINode->getIndex();
3106 Bytes = Flags.getByValSize();
3110 assert(FI != INT_MAX);
3111 if (!MFI->isFixedObjectIndex(FI))
3113 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3116 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3117 /// for tail call optimization. Targets which want to do tail call
3118 /// optimization should implement this function.
3120 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3121 CallingConv::ID CalleeCC,
3123 bool isCalleeStructRet,
3124 bool isCallerStructRet,
3126 const SmallVectorImpl<ISD::OutputArg> &Outs,
3127 const SmallVectorImpl<SDValue> &OutVals,
3128 const SmallVectorImpl<ISD::InputArg> &Ins,
3129 SelectionDAG &DAG) const {
3130 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3133 // If -tailcallopt is specified, make fastcc functions tail-callable.
3134 const MachineFunction &MF = DAG.getMachineFunction();
3135 const Function *CallerF = MF.getFunction();
3137 // If the function return type is x86_fp80 and the callee return type is not,
3138 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3139 // perform a tailcall optimization here.
3140 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3143 CallingConv::ID CallerCC = CallerF->getCallingConv();
3144 bool CCMatch = CallerCC == CalleeCC;
3145 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3146 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3148 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3149 if (IsTailCallConvention(CalleeCC) && CCMatch)
3154 // Look for obvious safe cases to perform tail call optimization that do not
3155 // require ABI changes. This is what gcc calls sibcall.
3157 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3158 // emit a special epilogue.
3159 const X86RegisterInfo *RegInfo =
3160 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3161 if (RegInfo->needsStackRealignment(MF))
3164 // Also avoid sibcall optimization if either caller or callee uses struct
3165 // return semantics.
3166 if (isCalleeStructRet || isCallerStructRet)
3169 // An stdcall/thiscall caller is expected to clean up its arguments; the
3170 // callee isn't going to do that.
3171 // FIXME: this is more restrictive than needed. We could produce a tailcall
3172 // when the stack adjustment matches. For example, with a thiscall that takes
3173 // only one argument.
3174 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3175 CallerCC == CallingConv::X86_ThisCall))
3178 // Do not sibcall optimize vararg calls unless all arguments are passed via
3180 if (isVarArg && !Outs.empty()) {
3182 // Optimizing for varargs on Win64 is unlikely to be safe without
3183 // additional testing.
3184 if (IsCalleeWin64 || IsCallerWin64)
3187 SmallVector<CCValAssign, 16> ArgLocs;
3188 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3189 getTargetMachine(), ArgLocs, *DAG.getContext());
3191 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3192 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3193 if (!ArgLocs[i].isRegLoc())
3197 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3198 // stack. Therefore, if it's not used by the call it is not safe to optimize
3199 // this into a sibcall.
3200 bool Unused = false;
3201 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3208 SmallVector<CCValAssign, 16> RVLocs;
3209 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3210 getTargetMachine(), RVLocs, *DAG.getContext());
3211 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3212 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3213 CCValAssign &VA = RVLocs[i];
3214 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3219 // If the calling conventions do not match, then we'd better make sure the
3220 // results are returned in the same way as what the caller expects.
3222 SmallVector<CCValAssign, 16> RVLocs1;
3223 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3224 getTargetMachine(), RVLocs1, *DAG.getContext());
3225 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3227 SmallVector<CCValAssign, 16> RVLocs2;
3228 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3229 getTargetMachine(), RVLocs2, *DAG.getContext());
3230 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3232 if (RVLocs1.size() != RVLocs2.size())
3234 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3235 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3237 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3239 if (RVLocs1[i].isRegLoc()) {
3240 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3243 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3249 // If the callee takes no arguments then go on to check the results of the
3251 if (!Outs.empty()) {
3252 // Check if stack adjustment is needed. For now, do not do this if any
3253 // argument is passed on the stack.
3254 SmallVector<CCValAssign, 16> ArgLocs;
3255 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3256 getTargetMachine(), ArgLocs, *DAG.getContext());
3258 // Allocate shadow area for Win64
3260 CCInfo.AllocateStack(32, 8);
3262 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3263 if (CCInfo.getNextStackOffset()) {
3264 MachineFunction &MF = DAG.getMachineFunction();
3265 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3268 // Check if the arguments are already laid out in the right way as
3269 // the caller's fixed stack objects.
3270 MachineFrameInfo *MFI = MF.getFrameInfo();
3271 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3272 const X86InstrInfo *TII =
3273 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3274 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3275 CCValAssign &VA = ArgLocs[i];
3276 SDValue Arg = OutVals[i];
3277 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3278 if (VA.getLocInfo() == CCValAssign::Indirect)
3280 if (!VA.isRegLoc()) {
3281 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3288 // If the tailcall address may be in a register, then make sure it's
3289 // possible to register allocate for it. In 32-bit, the call address can
3290 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3291 // callee-saved registers are restored. These happen to be the same
3292 // registers used to pass 'inreg' arguments so watch out for those.
3293 if (!Subtarget->is64Bit() &&
3294 ((!isa<GlobalAddressSDNode>(Callee) &&
3295 !isa<ExternalSymbolSDNode>(Callee)) ||
3296 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3297 unsigned NumInRegs = 0;
3298 // In PIC we need an extra register to formulate the address computation
3300 unsigned MaxInRegs =
3301 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3303 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3304 CCValAssign &VA = ArgLocs[i];
3307 unsigned Reg = VA.getLocReg();
3310 case X86::EAX: case X86::EDX: case X86::ECX:
3311 if (++NumInRegs == MaxInRegs)
3323 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3324 const TargetLibraryInfo *libInfo) const {
3325 return X86::createFastISel(funcInfo, libInfo);
3328 //===----------------------------------------------------------------------===//
3329 // Other Lowering Hooks
3330 //===----------------------------------------------------------------------===//
3332 static bool MayFoldLoad(SDValue Op) {
3333 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3336 static bool MayFoldIntoStore(SDValue Op) {
3337 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3340 static bool isTargetShuffle(unsigned Opcode) {
3342 default: return false;
3343 case X86ISD::PSHUFD:
3344 case X86ISD::PSHUFHW:
3345 case X86ISD::PSHUFLW:
3347 case X86ISD::PALIGNR:
3348 case X86ISD::MOVLHPS:
3349 case X86ISD::MOVLHPD:
3350 case X86ISD::MOVHLPS:
3351 case X86ISD::MOVLPS:
3352 case X86ISD::MOVLPD:
3353 case X86ISD::MOVSHDUP:
3354 case X86ISD::MOVSLDUP:
3355 case X86ISD::MOVDDUP:
3358 case X86ISD::UNPCKL:
3359 case X86ISD::UNPCKH:
3360 case X86ISD::VPERMILP:
3361 case X86ISD::VPERM2X128:
3362 case X86ISD::VPERMI:
3367 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3368 SDValue V1, SelectionDAG &DAG) {
3370 default: llvm_unreachable("Unknown x86 shuffle node");
3371 case X86ISD::MOVSHDUP:
3372 case X86ISD::MOVSLDUP:
3373 case X86ISD::MOVDDUP:
3374 return DAG.getNode(Opc, dl, VT, V1);
3378 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3379 SDValue V1, unsigned TargetMask,
3380 SelectionDAG &DAG) {
3382 default: llvm_unreachable("Unknown x86 shuffle node");
3383 case X86ISD::PSHUFD:
3384 case X86ISD::PSHUFHW:
3385 case X86ISD::PSHUFLW:
3386 case X86ISD::VPERMILP:
3387 case X86ISD::VPERMI:
3388 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3392 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3393 SDValue V1, SDValue V2, unsigned TargetMask,
3394 SelectionDAG &DAG) {
3396 default: llvm_unreachable("Unknown x86 shuffle node");
3397 case X86ISD::PALIGNR:
3399 case X86ISD::VPERM2X128:
3400 return DAG.getNode(Opc, dl, VT, V1, V2,
3401 DAG.getConstant(TargetMask, MVT::i8));
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3408 default: llvm_unreachable("Unknown x86 shuffle node");
3409 case X86ISD::MOVLHPS:
3410 case X86ISD::MOVLHPD:
3411 case X86ISD::MOVHLPS:
3412 case X86ISD::MOVLPS:
3413 case X86ISD::MOVLPD:
3416 case X86ISD::UNPCKL:
3417 case X86ISD::UNPCKH:
3418 return DAG.getNode(Opc, dl, VT, V1, V2);
3422 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3423 MachineFunction &MF = DAG.getMachineFunction();
3424 const X86RegisterInfo *RegInfo =
3425 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3426 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3427 int ReturnAddrIndex = FuncInfo->getRAIndex();
3429 if (ReturnAddrIndex == 0) {
3430 // Set up a frame object for the return address.
3431 unsigned SlotSize = RegInfo->getSlotSize();
3432 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3435 FuncInfo->setRAIndex(ReturnAddrIndex);
3438 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3441 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3442 bool hasSymbolicDisplacement) {
3443 // Offset should fit into 32 bit immediate field.
3444 if (!isInt<32>(Offset))
3447 // If we don't have a symbolic displacement - we don't have any extra
3449 if (!hasSymbolicDisplacement)
3452 // FIXME: Some tweaks might be needed for medium code model.
3453 if (M != CodeModel::Small && M != CodeModel::Kernel)
3456 // For small code model we assume that latest object is 16MB before end of 31
3457 // bits boundary. We may also accept pretty large negative constants knowing
3458 // that all objects are in the positive half of address space.
3459 if (M == CodeModel::Small && Offset < 16*1024*1024)
3462 // For kernel code model we know that all object resist in the negative half
3463 // of 32bits address space. We may not accept negative offsets, since they may
3464 // be just off and we may accept pretty large positive ones.
3465 if (M == CodeModel::Kernel && Offset > 0)
3471 /// isCalleePop - Determines whether the callee is required to pop its
3472 /// own arguments. Callee pop is necessary to support tail calls.
3473 bool X86::isCalleePop(CallingConv::ID CallingConv,
3474 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3478 switch (CallingConv) {
3481 case CallingConv::X86_StdCall:
3483 case CallingConv::X86_FastCall:
3485 case CallingConv::X86_ThisCall:
3487 case CallingConv::Fast:
3489 case CallingConv::GHC:
3491 case CallingConv::HiPE:
3496 /// \brief Return true if the condition is an unsigned comparison operation.
3497 static bool isX86CCUnsigned(unsigned X86CC) {
3499 default: llvm_unreachable("Invalid integer condition!");
3500 case X86::COND_E: return true;
3501 case X86::COND_G: return false;
3502 case X86::COND_GE: return false;
3503 case X86::COND_L: return false;
3504 case X86::COND_LE: return false;
3505 case X86::COND_NE: return true;
3506 case X86::COND_B: return true;
3507 case X86::COND_A: return true;
3508 case X86::COND_BE: return true;
3509 case X86::COND_AE: return true;
3511 llvm_unreachable("covered switch fell through?!");
3514 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3515 /// specific condition code, returning the condition code and the LHS/RHS of the
3516 /// comparison to make.
3517 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3518 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3520 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3521 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3522 // X > -1 -> X == 0, jump !sign.
3523 RHS = DAG.getConstant(0, RHS.getValueType());
3524 return X86::COND_NS;
3526 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3527 // X < 0 -> X == 0, jump on sign.
3530 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3532 RHS = DAG.getConstant(0, RHS.getValueType());
3533 return X86::COND_LE;
3537 switch (SetCCOpcode) {
3538 default: llvm_unreachable("Invalid integer condition!");
3539 case ISD::SETEQ: return X86::COND_E;
3540 case ISD::SETGT: return X86::COND_G;
3541 case ISD::SETGE: return X86::COND_GE;
3542 case ISD::SETLT: return X86::COND_L;
3543 case ISD::SETLE: return X86::COND_LE;
3544 case ISD::SETNE: return X86::COND_NE;
3545 case ISD::SETULT: return X86::COND_B;
3546 case ISD::SETUGT: return X86::COND_A;
3547 case ISD::SETULE: return X86::COND_BE;
3548 case ISD::SETUGE: return X86::COND_AE;
3552 // First determine if it is required or is profitable to flip the operands.
3554 // If LHS is a foldable load, but RHS is not, flip the condition.
3555 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3556 !ISD::isNON_EXTLoad(RHS.getNode())) {
3557 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3558 std::swap(LHS, RHS);
3561 switch (SetCCOpcode) {
3567 std::swap(LHS, RHS);
3571 // On a floating point condition, the flags are set as follows:
3573 // 0 | 0 | 0 | X > Y
3574 // 0 | 0 | 1 | X < Y
3575 // 1 | 0 | 0 | X == Y
3576 // 1 | 1 | 1 | unordered
3577 switch (SetCCOpcode) {
3578 default: llvm_unreachable("Condcode should be pre-legalized away");
3580 case ISD::SETEQ: return X86::COND_E;
3581 case ISD::SETOLT: // flipped
3583 case ISD::SETGT: return X86::COND_A;
3584 case ISD::SETOLE: // flipped
3586 case ISD::SETGE: return X86::COND_AE;
3587 case ISD::SETUGT: // flipped
3589 case ISD::SETLT: return X86::COND_B;
3590 case ISD::SETUGE: // flipped
3592 case ISD::SETLE: return X86::COND_BE;
3594 case ISD::SETNE: return X86::COND_NE;
3595 case ISD::SETUO: return X86::COND_P;
3596 case ISD::SETO: return X86::COND_NP;
3598 case ISD::SETUNE: return X86::COND_INVALID;
3602 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3603 /// code. Current x86 isa includes the following FP cmov instructions:
3604 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3605 static bool hasFPCMov(unsigned X86CC) {
3621 /// isFPImmLegal - Returns true if the target can instruction select the
3622 /// specified FP immediate natively. If false, the legalizer will
3623 /// materialize the FP immediate as a load from a constant pool.
3624 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3625 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3626 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3632 /// \brief Returns true if it is beneficial to convert a load of a constant
3633 /// to just the constant itself.
3634 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3636 assert(Ty->isIntegerTy());
3638 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3639 if (BitSize == 0 || BitSize > 64)
3644 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3645 /// the specified range (L, H].
3646 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3647 return (Val < 0) || (Val >= Low && Val < Hi);
3650 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3651 /// specified value.
3652 static bool isUndefOrEqual(int Val, int CmpVal) {
3653 return (Val < 0 || Val == CmpVal);
3656 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3657 /// from position Pos and ending in Pos+Size, falls within the specified
3658 /// sequential range (L, L+Pos]. or is undef.
3659 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3660 unsigned Pos, unsigned Size, int Low) {
3661 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3662 if (!isUndefOrEqual(Mask[i], Low))
3667 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3668 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3669 /// the second operand.
3670 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3671 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3672 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3673 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3674 return (Mask[0] < 2 && Mask[1] < 2);
3678 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3679 /// is suitable for input to PSHUFHW.
3680 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3681 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3684 // Lower quadword copied in order or undef.
3685 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3688 // Upper quadword shuffled.
3689 for (unsigned i = 4; i != 8; ++i)
3690 if (!isUndefOrInRange(Mask[i], 4, 8))
3693 if (VT == MVT::v16i16) {
3694 // Lower quadword copied in order or undef.
3695 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3698 // Upper quadword shuffled.
3699 for (unsigned i = 12; i != 16; ++i)
3700 if (!isUndefOrInRange(Mask[i], 12, 16))
3707 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3708 /// is suitable for input to PSHUFLW.
3709 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3710 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3713 // Upper quadword copied in order.
3714 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3717 // Lower quadword shuffled.
3718 for (unsigned i = 0; i != 4; ++i)
3719 if (!isUndefOrInRange(Mask[i], 0, 4))
3722 if (VT == MVT::v16i16) {
3723 // Upper quadword copied in order.
3724 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3727 // Lower quadword shuffled.
3728 for (unsigned i = 8; i != 12; ++i)
3729 if (!isUndefOrInRange(Mask[i], 8, 12))
3736 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3737 /// is suitable for input to PALIGNR.
3738 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3739 const X86Subtarget *Subtarget) {
3740 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3741 (VT.is256BitVector() && !Subtarget->hasInt256()))
3744 unsigned NumElts = VT.getVectorNumElements();
3745 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3746 unsigned NumLaneElts = NumElts/NumLanes;
3748 // Do not handle 64-bit element shuffles with palignr.
3749 if (NumLaneElts == 2)
3752 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3754 for (i = 0; i != NumLaneElts; ++i) {
3759 // Lane is all undef, go to next lane
3760 if (i == NumLaneElts)
3763 int Start = Mask[i+l];
3765 // Make sure its in this lane in one of the sources
3766 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3767 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3770 // If not lane 0, then we must match lane 0
3771 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3774 // Correct second source to be contiguous with first source
3775 if (Start >= (int)NumElts)
3776 Start -= NumElts - NumLaneElts;
3778 // Make sure we're shifting in the right direction.
3779 if (Start <= (int)(i+l))
3784 // Check the rest of the elements to see if they are consecutive.
3785 for (++i; i != NumLaneElts; ++i) {
3786 int Idx = Mask[i+l];
3788 // Make sure its in this lane
3789 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3790 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3793 // If not lane 0, then we must match lane 0
3794 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3797 if (Idx >= (int)NumElts)
3798 Idx -= NumElts - NumLaneElts;
3800 if (!isUndefOrEqual(Idx, Start+i))
3809 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3810 /// the two vector operands have swapped position.
3811 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3812 unsigned NumElems) {
3813 for (unsigned i = 0; i != NumElems; ++i) {
3817 else if (idx < (int)NumElems)
3818 Mask[i] = idx + NumElems;
3820 Mask[i] = idx - NumElems;
3824 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3825 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3826 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3827 /// reverse of what x86 shuffles want.
3828 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3830 unsigned NumElems = VT.getVectorNumElements();
3831 unsigned NumLanes = VT.getSizeInBits()/128;
3832 unsigned NumLaneElems = NumElems/NumLanes;
3834 if (NumLaneElems != 2 && NumLaneElems != 4)
3837 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3838 bool symetricMaskRequired =
3839 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3841 // VSHUFPSY divides the resulting vector into 4 chunks.
3842 // The sources are also splitted into 4 chunks, and each destination
3843 // chunk must come from a different source chunk.
3845 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3846 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3848 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3849 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3851 // VSHUFPDY divides the resulting vector into 4 chunks.
3852 // The sources are also splitted into 4 chunks, and each destination
3853 // chunk must come from a different source chunk.
3855 // SRC1 => X3 X2 X1 X0
3856 // SRC2 => Y3 Y2 Y1 Y0
3858 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3860 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3861 unsigned HalfLaneElems = NumLaneElems/2;
3862 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3863 for (unsigned i = 0; i != NumLaneElems; ++i) {
3864 int Idx = Mask[i+l];
3865 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3866 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3868 // For VSHUFPSY, the mask of the second half must be the same as the
3869 // first but with the appropriate offsets. This works in the same way as
3870 // VPERMILPS works with masks.
3871 if (!symetricMaskRequired || Idx < 0)
3873 if (MaskVal[i] < 0) {
3874 MaskVal[i] = Idx - l;
3877 if ((signed)(Idx - l) != MaskVal[i])
3885 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3886 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3887 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3888 if (!VT.is128BitVector())
3891 unsigned NumElems = VT.getVectorNumElements();
3896 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3897 return isUndefOrEqual(Mask[0], 6) &&
3898 isUndefOrEqual(Mask[1], 7) &&
3899 isUndefOrEqual(Mask[2], 2) &&
3900 isUndefOrEqual(Mask[3], 3);
3903 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3904 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3906 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3907 if (!VT.is128BitVector())
3910 unsigned NumElems = VT.getVectorNumElements();
3915 return isUndefOrEqual(Mask[0], 2) &&
3916 isUndefOrEqual(Mask[1], 3) &&
3917 isUndefOrEqual(Mask[2], 2) &&
3918 isUndefOrEqual(Mask[3], 3);
3921 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3922 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3923 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3924 if (!VT.is128BitVector())
3927 unsigned NumElems = VT.getVectorNumElements();
3929 if (NumElems != 2 && NumElems != 4)
3932 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3933 if (!isUndefOrEqual(Mask[i], i + NumElems))
3936 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3937 if (!isUndefOrEqual(Mask[i], i))
3943 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3944 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3945 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3946 if (!VT.is128BitVector())
3949 unsigned NumElems = VT.getVectorNumElements();
3951 if (NumElems != 2 && NumElems != 4)
3954 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3955 if (!isUndefOrEqual(Mask[i], i))
3958 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3959 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3965 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3966 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3967 /// i. e: If all but one element come from the same vector.
3968 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3969 // TODO: Deal with AVX's VINSERTPS
3970 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3973 unsigned CorrectPosV1 = 0;
3974 unsigned CorrectPosV2 = 0;
3975 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3976 if (Mask[i] == -1) {
3984 else if (Mask[i] == i + 4)
3988 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3989 // We have 3 elements (undefs count as elements from any vector) from one
3990 // vector, and one from another.
3997 // Some special combinations that can be optimized.
4000 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4001 SelectionDAG &DAG) {
4002 MVT VT = SVOp->getSimpleValueType(0);
4005 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4008 ArrayRef<int> Mask = SVOp->getMask();
4010 // These are the special masks that may be optimized.
4011 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4012 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4013 bool MatchEvenMask = true;
4014 bool MatchOddMask = true;
4015 for (int i=0; i<8; ++i) {
4016 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4017 MatchEvenMask = false;
4018 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4019 MatchOddMask = false;
4022 if (!MatchEvenMask && !MatchOddMask)
4025 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4027 SDValue Op0 = SVOp->getOperand(0);
4028 SDValue Op1 = SVOp->getOperand(1);
4030 if (MatchEvenMask) {
4031 // Shift the second operand right to 32 bits.
4032 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4033 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4035 // Shift the first operand left to 32 bits.
4036 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4037 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4039 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4040 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4043 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4044 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4045 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4046 bool HasInt256, bool V2IsSplat = false) {
4048 assert(VT.getSizeInBits() >= 128 &&
4049 "Unsupported vector type for unpckl");
4051 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4053 unsigned NumOf256BitLanes;
4054 unsigned NumElts = VT.getVectorNumElements();
4055 if (VT.is256BitVector()) {
4056 if (NumElts != 4 && NumElts != 8 &&
4057 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4060 NumOf256BitLanes = 1;
4061 } else if (VT.is512BitVector()) {
4062 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4063 "Unsupported vector type for unpckh");
4065 NumOf256BitLanes = 2;
4068 NumOf256BitLanes = 1;
4071 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4072 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4074 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4075 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4076 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4077 int BitI = Mask[l256*NumEltsInStride+l+i];
4078 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4079 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4081 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4083 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4091 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4092 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4093 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4094 bool HasInt256, bool V2IsSplat = false) {
4095 assert(VT.getSizeInBits() >= 128 &&
4096 "Unsupported vector type for unpckh");
4098 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4100 unsigned NumOf256BitLanes;
4101 unsigned NumElts = VT.getVectorNumElements();
4102 if (VT.is256BitVector()) {
4103 if (NumElts != 4 && NumElts != 8 &&
4104 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4107 NumOf256BitLanes = 1;
4108 } else if (VT.is512BitVector()) {
4109 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4110 "Unsupported vector type for unpckh");
4112 NumOf256BitLanes = 2;
4115 NumOf256BitLanes = 1;
4118 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4119 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4121 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4122 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4123 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4124 int BitI = Mask[l256*NumEltsInStride+l+i];
4125 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4126 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4128 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4130 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4138 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4139 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4141 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4142 unsigned NumElts = VT.getVectorNumElements();
4143 bool Is256BitVec = VT.is256BitVector();
4145 if (VT.is512BitVector())
4147 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4148 "Unsupported vector type for unpckh");
4150 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4151 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4154 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4155 // FIXME: Need a better way to get rid of this, there's no latency difference
4156 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4157 // the former later. We should also remove the "_undef" special mask.
4158 if (NumElts == 4 && Is256BitVec)
4161 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4162 // independently on 128-bit lanes.
4163 unsigned NumLanes = VT.getSizeInBits()/128;
4164 unsigned NumLaneElts = NumElts/NumLanes;
4166 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4167 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4168 int BitI = Mask[l+i];
4169 int BitI1 = Mask[l+i+1];
4171 if (!isUndefOrEqual(BitI, j))
4173 if (!isUndefOrEqual(BitI1, j))
4181 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4182 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4184 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4185 unsigned NumElts = VT.getVectorNumElements();
4187 if (VT.is512BitVector())
4190 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4191 "Unsupported vector type for unpckh");
4193 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4194 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4197 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4198 // independently on 128-bit lanes.
4199 unsigned NumLanes = VT.getSizeInBits()/128;
4200 unsigned NumLaneElts = NumElts/NumLanes;
4202 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4203 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4204 int BitI = Mask[l+i];
4205 int BitI1 = Mask[l+i+1];
4206 if (!isUndefOrEqual(BitI, j))
4208 if (!isUndefOrEqual(BitI1, j))
4215 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4216 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4217 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4218 if (!VT.is512BitVector())
4221 unsigned NumElts = VT.getVectorNumElements();
4222 unsigned HalfSize = NumElts/2;
4223 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4224 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4229 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4230 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4238 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4239 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4240 /// MOVSD, and MOVD, i.e. setting the lowest element.
4241 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4242 if (VT.getVectorElementType().getSizeInBits() < 32)
4244 if (!VT.is128BitVector())
4247 unsigned NumElts = VT.getVectorNumElements();
4249 if (!isUndefOrEqual(Mask[0], NumElts))
4252 for (unsigned i = 1; i != NumElts; ++i)
4253 if (!isUndefOrEqual(Mask[i], i))
4259 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4260 /// as permutations between 128-bit chunks or halves. As an example: this
4262 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4263 /// The first half comes from the second half of V1 and the second half from the
4264 /// the second half of V2.
4265 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4266 if (!HasFp256 || !VT.is256BitVector())
4269 // The shuffle result is divided into half A and half B. In total the two
4270 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4271 // B must come from C, D, E or F.
4272 unsigned HalfSize = VT.getVectorNumElements()/2;
4273 bool MatchA = false, MatchB = false;
4275 // Check if A comes from one of C, D, E, F.
4276 for (unsigned Half = 0; Half != 4; ++Half) {
4277 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4283 // Check if B comes from one of C, D, E, F.
4284 for (unsigned Half = 0; Half != 4; ++Half) {
4285 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4291 return MatchA && MatchB;
4294 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4295 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4296 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4297 MVT VT = SVOp->getSimpleValueType(0);
4299 unsigned HalfSize = VT.getVectorNumElements()/2;
4301 unsigned FstHalf = 0, SndHalf = 0;
4302 for (unsigned i = 0; i < HalfSize; ++i) {
4303 if (SVOp->getMaskElt(i) > 0) {
4304 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4308 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4309 if (SVOp->getMaskElt(i) > 0) {
4310 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4315 return (FstHalf | (SndHalf << 4));
4318 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4319 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4320 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4324 unsigned NumElts = VT.getVectorNumElements();
4326 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4327 for (unsigned i = 0; i != NumElts; ++i) {
4330 Imm8 |= Mask[i] << (i*2);
4335 unsigned LaneSize = 4;
4336 SmallVector<int, 4> MaskVal(LaneSize, -1);
4338 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4339 for (unsigned i = 0; i != LaneSize; ++i) {
4340 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4344 if (MaskVal[i] < 0) {
4345 MaskVal[i] = Mask[i+l] - l;
4346 Imm8 |= MaskVal[i] << (i*2);
4349 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4356 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4357 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4358 /// Note that VPERMIL mask matching is different depending whether theunderlying
4359 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4360 /// to the same elements of the low, but to the higher half of the source.
4361 /// In VPERMILPD the two lanes could be shuffled independently of each other
4362 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4363 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4364 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4365 if (VT.getSizeInBits() < 256 || EltSize < 32)
4367 bool symetricMaskRequired = (EltSize == 32);
4368 unsigned NumElts = VT.getVectorNumElements();
4370 unsigned NumLanes = VT.getSizeInBits()/128;
4371 unsigned LaneSize = NumElts/NumLanes;
4372 // 2 or 4 elements in one lane
4374 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4375 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4376 for (unsigned i = 0; i != LaneSize; ++i) {
4377 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4379 if (symetricMaskRequired) {
4380 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4381 ExpectedMaskVal[i] = Mask[i+l] - l;
4384 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4392 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4393 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4394 /// element of vector 2 and the other elements to come from vector 1 in order.
4395 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4396 bool V2IsSplat = false, bool V2IsUndef = false) {
4397 if (!VT.is128BitVector())
4400 unsigned NumOps = VT.getVectorNumElements();
4401 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4404 if (!isUndefOrEqual(Mask[0], 0))
4407 for (unsigned i = 1; i != NumOps; ++i)
4408 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4409 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4410 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4416 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4417 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4418 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4419 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4420 const X86Subtarget *Subtarget) {
4421 if (!Subtarget->hasSSE3())
4424 unsigned NumElems = VT.getVectorNumElements();
4426 if ((VT.is128BitVector() && NumElems != 4) ||
4427 (VT.is256BitVector() && NumElems != 8) ||
4428 (VT.is512BitVector() && NumElems != 16))
4431 // "i+1" is the value the indexed mask element must have
4432 for (unsigned i = 0; i != NumElems; i += 2)
4433 if (!isUndefOrEqual(Mask[i], i+1) ||
4434 !isUndefOrEqual(Mask[i+1], i+1))
4440 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4441 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4442 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4443 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4444 const X86Subtarget *Subtarget) {
4445 if (!Subtarget->hasSSE3())
4448 unsigned NumElems = VT.getVectorNumElements();
4450 if ((VT.is128BitVector() && NumElems != 4) ||
4451 (VT.is256BitVector() && NumElems != 8) ||
4452 (VT.is512BitVector() && NumElems != 16))
4455 // "i" is the value the indexed mask element must have
4456 for (unsigned i = 0; i != NumElems; i += 2)
4457 if (!isUndefOrEqual(Mask[i], i) ||
4458 !isUndefOrEqual(Mask[i+1], i))
4464 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4465 /// specifies a shuffle of elements that is suitable for input to 256-bit
4466 /// version of MOVDDUP.
4467 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4468 if (!HasFp256 || !VT.is256BitVector())
4471 unsigned NumElts = VT.getVectorNumElements();
4475 for (unsigned i = 0; i != NumElts/2; ++i)
4476 if (!isUndefOrEqual(Mask[i], 0))
4478 for (unsigned i = NumElts/2; i != NumElts; ++i)
4479 if (!isUndefOrEqual(Mask[i], NumElts/2))
4484 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4485 /// specifies a shuffle of elements that is suitable for input to 128-bit
4486 /// version of MOVDDUP.
4487 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4488 if (!VT.is128BitVector())
4491 unsigned e = VT.getVectorNumElements() / 2;
4492 for (unsigned i = 0; i != e; ++i)
4493 if (!isUndefOrEqual(Mask[i], i))
4495 for (unsigned i = 0; i != e; ++i)
4496 if (!isUndefOrEqual(Mask[e+i], i))
4501 /// isVEXTRACTIndex - Return true if the specified
4502 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4503 /// suitable for instruction that extract 128 or 256 bit vectors
4504 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4505 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4506 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4509 // The index should be aligned on a vecWidth-bit boundary.
4511 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4513 MVT VT = N->getSimpleValueType(0);
4514 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4515 bool Result = (Index * ElSize) % vecWidth == 0;
4520 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4521 /// operand specifies a subvector insert that is suitable for input to
4522 /// insertion of 128 or 256-bit subvectors
4523 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4524 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4525 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4527 // The index should be aligned on a vecWidth-bit boundary.
4529 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4531 MVT VT = N->getSimpleValueType(0);
4532 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4533 bool Result = (Index * ElSize) % vecWidth == 0;
4538 bool X86::isVINSERT128Index(SDNode *N) {
4539 return isVINSERTIndex(N, 128);
4542 bool X86::isVINSERT256Index(SDNode *N) {
4543 return isVINSERTIndex(N, 256);
4546 bool X86::isVEXTRACT128Index(SDNode *N) {
4547 return isVEXTRACTIndex(N, 128);
4550 bool X86::isVEXTRACT256Index(SDNode *N) {
4551 return isVEXTRACTIndex(N, 256);
4554 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4555 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4556 /// Handles 128-bit and 256-bit.
4557 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4558 MVT VT = N->getSimpleValueType(0);
4560 assert((VT.getSizeInBits() >= 128) &&
4561 "Unsupported vector type for PSHUF/SHUFP");
4563 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4564 // independently on 128-bit lanes.
4565 unsigned NumElts = VT.getVectorNumElements();
4566 unsigned NumLanes = VT.getSizeInBits()/128;
4567 unsigned NumLaneElts = NumElts/NumLanes;
4569 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4570 "Only supports 2, 4 or 8 elements per lane");
4572 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4574 for (unsigned i = 0; i != NumElts; ++i) {
4575 int Elt = N->getMaskElt(i);
4576 if (Elt < 0) continue;
4577 Elt &= NumLaneElts - 1;
4578 unsigned ShAmt = (i << Shift) % 8;
4579 Mask |= Elt << ShAmt;
4585 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4586 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4587 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4588 MVT VT = N->getSimpleValueType(0);
4590 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4591 "Unsupported vector type for PSHUFHW");
4593 unsigned NumElts = VT.getVectorNumElements();
4596 for (unsigned l = 0; l != NumElts; l += 8) {
4597 // 8 nodes per lane, but we only care about the last 4.
4598 for (unsigned i = 0; i < 4; ++i) {
4599 int Elt = N->getMaskElt(l+i+4);
4600 if (Elt < 0) continue;
4601 Elt &= 0x3; // only 2-bits.
4602 Mask |= Elt << (i * 2);
4609 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4610 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4611 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4612 MVT VT = N->getSimpleValueType(0);
4614 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4615 "Unsupported vector type for PSHUFHW");
4617 unsigned NumElts = VT.getVectorNumElements();
4620 for (unsigned l = 0; l != NumElts; l += 8) {
4621 // 8 nodes per lane, but we only care about the first 4.
4622 for (unsigned i = 0; i < 4; ++i) {
4623 int Elt = N->getMaskElt(l+i);
4624 if (Elt < 0) continue;
4625 Elt &= 0x3; // only 2-bits
4626 Mask |= Elt << (i * 2);
4633 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4634 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4635 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4636 MVT VT = SVOp->getSimpleValueType(0);
4637 unsigned EltSize = VT.is512BitVector() ? 1 :
4638 VT.getVectorElementType().getSizeInBits() >> 3;
4640 unsigned NumElts = VT.getVectorNumElements();
4641 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4642 unsigned NumLaneElts = NumElts/NumLanes;
4646 for (i = 0; i != NumElts; ++i) {
4647 Val = SVOp->getMaskElt(i);
4651 if (Val >= (int)NumElts)
4652 Val -= NumElts - NumLaneElts;
4654 assert(Val - i > 0 && "PALIGNR imm should be positive");
4655 return (Val - i) * EltSize;
4658 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4659 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4660 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4661 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4664 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4666 MVT VecVT = N->getOperand(0).getSimpleValueType();
4667 MVT ElVT = VecVT.getVectorElementType();
4669 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4670 return Index / NumElemsPerChunk;
4673 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4674 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4675 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4676 llvm_unreachable("Illegal insert subvector for VINSERT");
4679 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4681 MVT VecVT = N->getSimpleValueType(0);
4682 MVT ElVT = VecVT.getVectorElementType();
4684 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4685 return Index / NumElemsPerChunk;
4688 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4689 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4690 /// and VINSERTI128 instructions.
4691 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4692 return getExtractVEXTRACTImmediate(N, 128);
4695 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4696 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4697 /// and VINSERTI64x4 instructions.
4698 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4699 return getExtractVEXTRACTImmediate(N, 256);
4702 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4703 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4704 /// and VINSERTI128 instructions.
4705 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4706 return getInsertVINSERTImmediate(N, 128);
4709 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4710 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4711 /// and VINSERTI64x4 instructions.
4712 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4713 return getInsertVINSERTImmediate(N, 256);
4716 /// isZero - Returns true if Elt is a constant integer zero
4717 static bool isZero(SDValue V) {
4718 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4719 return C && C->isNullValue();
4722 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4724 bool X86::isZeroNode(SDValue Elt) {
4727 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4728 return CFP->getValueAPF().isPosZero();
4732 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4733 /// their permute mask.
4734 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4735 SelectionDAG &DAG) {
4736 MVT VT = SVOp->getSimpleValueType(0);
4737 unsigned NumElems = VT.getVectorNumElements();
4738 SmallVector<int, 8> MaskVec;
4740 for (unsigned i = 0; i != NumElems; ++i) {
4741 int Idx = SVOp->getMaskElt(i);
4743 if (Idx < (int)NumElems)
4748 MaskVec.push_back(Idx);
4750 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4751 SVOp->getOperand(0), &MaskVec[0]);
4754 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4755 /// match movhlps. The lower half elements should come from upper half of
4756 /// V1 (and in order), and the upper half elements should come from the upper
4757 /// half of V2 (and in order).
4758 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4759 if (!VT.is128BitVector())
4761 if (VT.getVectorNumElements() != 4)
4763 for (unsigned i = 0, e = 2; i != e; ++i)
4764 if (!isUndefOrEqual(Mask[i], i+2))
4766 for (unsigned i = 2; i != 4; ++i)
4767 if (!isUndefOrEqual(Mask[i], i+4))
4772 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4773 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4775 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4776 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4778 N = N->getOperand(0).getNode();
4779 if (!ISD::isNON_EXTLoad(N))
4782 *LD = cast<LoadSDNode>(N);
4786 // Test whether the given value is a vector value which will be legalized
4788 static bool WillBeConstantPoolLoad(SDNode *N) {
4789 if (N->getOpcode() != ISD::BUILD_VECTOR)
4792 // Check for any non-constant elements.
4793 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4794 switch (N->getOperand(i).getNode()->getOpcode()) {
4796 case ISD::ConstantFP:
4803 // Vectors of all-zeros and all-ones are materialized with special
4804 // instructions rather than being loaded.
4805 return !ISD::isBuildVectorAllZeros(N) &&
4806 !ISD::isBuildVectorAllOnes(N);
4809 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4810 /// match movlp{s|d}. The lower half elements should come from lower half of
4811 /// V1 (and in order), and the upper half elements should come from the upper
4812 /// half of V2 (and in order). And since V1 will become the source of the
4813 /// MOVLP, it must be either a vector load or a scalar load to vector.
4814 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4815 ArrayRef<int> Mask, MVT VT) {
4816 if (!VT.is128BitVector())
4819 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4821 // Is V2 is a vector load, don't do this transformation. We will try to use
4822 // load folding shufps op.
4823 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4826 unsigned NumElems = VT.getVectorNumElements();
4828 if (NumElems != 2 && NumElems != 4)
4830 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4831 if (!isUndefOrEqual(Mask[i], i))
4833 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4834 if (!isUndefOrEqual(Mask[i], i+NumElems))
4839 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4841 static bool isSplatVector(SDNode *N) {
4842 if (N->getOpcode() != ISD::BUILD_VECTOR)
4845 SDValue SplatValue = N->getOperand(0);
4846 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4847 if (N->getOperand(i) != SplatValue)
4852 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4853 /// to an zero vector.
4854 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4855 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4856 SDValue V1 = N->getOperand(0);
4857 SDValue V2 = N->getOperand(1);
4858 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4859 for (unsigned i = 0; i != NumElems; ++i) {
4860 int Idx = N->getMaskElt(i);
4861 if (Idx >= (int)NumElems) {
4862 unsigned Opc = V2.getOpcode();
4863 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4865 if (Opc != ISD::BUILD_VECTOR ||
4866 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4868 } else if (Idx >= 0) {
4869 unsigned Opc = V1.getOpcode();
4870 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4872 if (Opc != ISD::BUILD_VECTOR ||
4873 !X86::isZeroNode(V1.getOperand(Idx)))
4880 /// getZeroVector - Returns a vector of specified type with all zero elements.
4882 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4883 SelectionDAG &DAG, SDLoc dl) {
4884 assert(VT.isVector() && "Expected a vector type");
4886 // Always build SSE zero vectors as <4 x i32> bitcasted
4887 // to their dest type. This ensures they get CSE'd.
4889 if (VT.is128BitVector()) { // SSE
4890 if (Subtarget->hasSSE2()) { // SSE2
4891 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4892 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4894 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4895 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4897 } else if (VT.is256BitVector()) { // AVX
4898 if (Subtarget->hasInt256()) { // AVX2
4899 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4900 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4901 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4903 // 256-bit logic and arithmetic instructions in AVX are all
4904 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4905 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4906 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4907 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4909 } else if (VT.is512BitVector()) { // AVX-512
4910 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4911 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4912 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4913 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4914 } else if (VT.getScalarType() == MVT::i1) {
4915 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4916 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4917 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4918 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4920 llvm_unreachable("Unexpected vector type");
4922 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4925 /// getOnesVector - Returns a vector of specified type with all bits set.
4926 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4927 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4928 /// Then bitcast to their original type, ensuring they get CSE'd.
4929 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4931 assert(VT.isVector() && "Expected a vector type");
4933 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4935 if (VT.is256BitVector()) {
4936 if (HasInt256) { // AVX2
4937 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4938 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4940 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4941 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4943 } else if (VT.is128BitVector()) {
4944 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4946 llvm_unreachable("Unexpected vector type");
4948 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4951 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4952 /// that point to V2 points to its first element.
4953 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4954 for (unsigned i = 0; i != NumElems; ++i) {
4955 if (Mask[i] > (int)NumElems) {
4961 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4962 /// operation of specified width.
4963 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4965 unsigned NumElems = VT.getVectorNumElements();
4966 SmallVector<int, 8> Mask;
4967 Mask.push_back(NumElems);
4968 for (unsigned i = 1; i != NumElems; ++i)
4970 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4973 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4974 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4976 unsigned NumElems = VT.getVectorNumElements();
4977 SmallVector<int, 8> Mask;
4978 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4980 Mask.push_back(i + NumElems);
4982 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4985 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4986 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4988 unsigned NumElems = VT.getVectorNumElements();
4989 SmallVector<int, 8> Mask;
4990 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4991 Mask.push_back(i + Half);
4992 Mask.push_back(i + NumElems + Half);
4994 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4997 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4998 // a generic shuffle instruction because the target has no such instructions.
4999 // Generate shuffles which repeat i16 and i8 several times until they can be
5000 // represented by v4f32 and then be manipulated by target suported shuffles.
5001 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5002 MVT VT = V.getSimpleValueType();
5003 int NumElems = VT.getVectorNumElements();
5006 while (NumElems > 4) {
5007 if (EltNo < NumElems/2) {
5008 V = getUnpackl(DAG, dl, VT, V, V);
5010 V = getUnpackh(DAG, dl, VT, V, V);
5011 EltNo -= NumElems/2;
5018 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5019 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5020 MVT VT = V.getSimpleValueType();
5023 if (VT.is128BitVector()) {
5024 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5025 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5026 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5028 } else if (VT.is256BitVector()) {
5029 // To use VPERMILPS to splat scalars, the second half of indicies must
5030 // refer to the higher part, which is a duplication of the lower one,
5031 // because VPERMILPS can only handle in-lane permutations.
5032 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5033 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5035 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5036 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5039 llvm_unreachable("Vector size not supported");
5041 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5044 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5045 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5046 MVT SrcVT = SV->getSimpleValueType(0);
5047 SDValue V1 = SV->getOperand(0);
5050 int EltNo = SV->getSplatIndex();
5051 int NumElems = SrcVT.getVectorNumElements();
5052 bool Is256BitVec = SrcVT.is256BitVector();
5054 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5055 "Unknown how to promote splat for type");
5057 // Extract the 128-bit part containing the splat element and update
5058 // the splat element index when it refers to the higher register.
5060 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5061 if (EltNo >= NumElems/2)
5062 EltNo -= NumElems/2;
5065 // All i16 and i8 vector types can't be used directly by a generic shuffle
5066 // instruction because the target has no such instruction. Generate shuffles
5067 // which repeat i16 and i8 several times until they fit in i32, and then can
5068 // be manipulated by target suported shuffles.
5069 MVT EltVT = SrcVT.getVectorElementType();
5070 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5071 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5073 // Recreate the 256-bit vector and place the same 128-bit vector
5074 // into the low and high part. This is necessary because we want
5075 // to use VPERM* to shuffle the vectors
5077 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5080 return getLegalSplat(DAG, V1, EltNo);
5083 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5084 /// vector of zero or undef vector. This produces a shuffle where the low
5085 /// element of V2 is swizzled into the zero/undef vector, landing at element
5086 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5087 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5089 const X86Subtarget *Subtarget,
5090 SelectionDAG &DAG) {
5091 MVT VT = V2.getSimpleValueType();
5093 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5094 unsigned NumElems = VT.getVectorNumElements();
5095 SmallVector<int, 16> MaskVec;
5096 for (unsigned i = 0; i != NumElems; ++i)
5097 // If this is the insertion idx, put the low elt of V2 here.
5098 MaskVec.push_back(i == Idx ? NumElems : i);
5099 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5102 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5103 /// target specific opcode. Returns true if the Mask could be calculated.
5104 /// Sets IsUnary to true if only uses one source.
5105 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5106 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5107 unsigned NumElems = VT.getVectorNumElements();
5111 switch(N->getOpcode()) {
5113 ImmN = N->getOperand(N->getNumOperands()-1);
5114 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5116 case X86ISD::UNPCKH:
5117 DecodeUNPCKHMask(VT, Mask);
5119 case X86ISD::UNPCKL:
5120 DecodeUNPCKLMask(VT, Mask);
5122 case X86ISD::MOVHLPS:
5123 DecodeMOVHLPSMask(NumElems, Mask);
5125 case X86ISD::MOVLHPS:
5126 DecodeMOVLHPSMask(NumElems, Mask);
5128 case X86ISD::PALIGNR:
5129 ImmN = N->getOperand(N->getNumOperands()-1);
5130 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5132 case X86ISD::PSHUFD:
5133 case X86ISD::VPERMILP:
5134 ImmN = N->getOperand(N->getNumOperands()-1);
5135 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5138 case X86ISD::PSHUFHW:
5139 ImmN = N->getOperand(N->getNumOperands()-1);
5140 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5143 case X86ISD::PSHUFLW:
5144 ImmN = N->getOperand(N->getNumOperands()-1);
5145 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5148 case X86ISD::VPERMI:
5149 ImmN = N->getOperand(N->getNumOperands()-1);
5150 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154 case X86ISD::MOVSD: {
5155 // The index 0 always comes from the first element of the second source,
5156 // this is why MOVSS and MOVSD are used in the first place. The other
5157 // elements come from the other positions of the first source vector
5158 Mask.push_back(NumElems);
5159 for (unsigned i = 1; i != NumElems; ++i) {
5164 case X86ISD::VPERM2X128:
5165 ImmN = N->getOperand(N->getNumOperands()-1);
5166 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5167 if (Mask.empty()) return false;
5169 case X86ISD::MOVDDUP:
5170 case X86ISD::MOVLHPD:
5171 case X86ISD::MOVLPD:
5172 case X86ISD::MOVLPS:
5173 case X86ISD::MOVSHDUP:
5174 case X86ISD::MOVSLDUP:
5175 // Not yet implemented
5177 default: llvm_unreachable("unknown target shuffle node");
5183 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5184 /// element of the result of the vector shuffle.
5185 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5188 return SDValue(); // Limit search depth.
5190 SDValue V = SDValue(N, 0);
5191 EVT VT = V.getValueType();
5192 unsigned Opcode = V.getOpcode();
5194 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5195 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5196 int Elt = SV->getMaskElt(Index);
5199 return DAG.getUNDEF(VT.getVectorElementType());
5201 unsigned NumElems = VT.getVectorNumElements();
5202 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5203 : SV->getOperand(1);
5204 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5207 // Recurse into target specific vector shuffles to find scalars.
5208 if (isTargetShuffle(Opcode)) {
5209 MVT ShufVT = V.getSimpleValueType();
5210 unsigned NumElems = ShufVT.getVectorNumElements();
5211 SmallVector<int, 16> ShuffleMask;
5214 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5217 int Elt = ShuffleMask[Index];
5219 return DAG.getUNDEF(ShufVT.getVectorElementType());
5221 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5223 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5227 // Actual nodes that may contain scalar elements
5228 if (Opcode == ISD::BITCAST) {
5229 V = V.getOperand(0);
5230 EVT SrcVT = V.getValueType();
5231 unsigned NumElems = VT.getVectorNumElements();
5233 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5237 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5238 return (Index == 0) ? V.getOperand(0)
5239 : DAG.getUNDEF(VT.getVectorElementType());
5241 if (V.getOpcode() == ISD::BUILD_VECTOR)
5242 return V.getOperand(Index);
5247 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5248 /// shuffle operation which come from a consecutively from a zero. The
5249 /// search can start in two different directions, from left or right.
5250 /// We count undefs as zeros until PreferredNum is reached.
5251 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5252 unsigned NumElems, bool ZerosFromLeft,
5254 unsigned PreferredNum = -1U) {
5255 unsigned NumZeros = 0;
5256 for (unsigned i = 0; i != NumElems; ++i) {
5257 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5258 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5262 if (X86::isZeroNode(Elt))
5264 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5265 NumZeros = std::min(NumZeros + 1, PreferredNum);
5273 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5274 /// correspond consecutively to elements from one of the vector operands,
5275 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5277 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5278 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5279 unsigned NumElems, unsigned &OpNum) {
5280 bool SeenV1 = false;
5281 bool SeenV2 = false;
5283 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5284 int Idx = SVOp->getMaskElt(i);
5285 // Ignore undef indicies
5289 if (Idx < (int)NumElems)
5294 // Only accept consecutive elements from the same vector
5295 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5299 OpNum = SeenV1 ? 0 : 1;
5303 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5304 /// logical left shift of a vector.
5305 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5306 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5308 SVOp->getSimpleValueType(0).getVectorNumElements();
5309 unsigned NumZeros = getNumOfConsecutiveZeros(
5310 SVOp, NumElems, false /* check zeros from right */, DAG,
5311 SVOp->getMaskElt(0));
5317 // Considering the elements in the mask that are not consecutive zeros,
5318 // check if they consecutively come from only one of the source vectors.
5320 // V1 = {X, A, B, C} 0
5322 // vector_shuffle V1, V2 <1, 2, 3, X>
5324 if (!isShuffleMaskConsecutive(SVOp,
5325 0, // Mask Start Index
5326 NumElems-NumZeros, // Mask End Index(exclusive)
5327 NumZeros, // Where to start looking in the src vector
5328 NumElems, // Number of elements in vector
5329 OpSrc)) // Which source operand ?
5334 ShVal = SVOp->getOperand(OpSrc);
5338 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5339 /// logical left shift of a vector.
5340 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5341 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5343 SVOp->getSimpleValueType(0).getVectorNumElements();
5344 unsigned NumZeros = getNumOfConsecutiveZeros(
5345 SVOp, NumElems, true /* check zeros from left */, DAG,
5346 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5352 // Considering the elements in the mask that are not consecutive zeros,
5353 // check if they consecutively come from only one of the source vectors.
5355 // 0 { A, B, X, X } = V2
5357 // vector_shuffle V1, V2 <X, X, 4, 5>
5359 if (!isShuffleMaskConsecutive(SVOp,
5360 NumZeros, // Mask Start Index
5361 NumElems, // Mask End Index(exclusive)
5362 0, // Where to start looking in the src vector
5363 NumElems, // Number of elements in vector
5364 OpSrc)) // Which source operand ?
5369 ShVal = SVOp->getOperand(OpSrc);
5373 /// isVectorShift - Returns true if the shuffle can be implemented as a
5374 /// logical left or right shift of a vector.
5375 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5376 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5377 // Although the logic below support any bitwidth size, there are no
5378 // shift instructions which handle more than 128-bit vectors.
5379 if (!SVOp->getSimpleValueType(0).is128BitVector())
5382 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5383 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5389 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5391 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5392 unsigned NumNonZero, unsigned NumZero,
5394 const X86Subtarget* Subtarget,
5395 const TargetLowering &TLI) {
5402 for (unsigned i = 0; i < 16; ++i) {
5403 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5404 if (ThisIsNonZero && First) {
5406 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5408 V = DAG.getUNDEF(MVT::v8i16);
5413 SDValue ThisElt, LastElt;
5414 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5415 if (LastIsNonZero) {
5416 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5417 MVT::i16, Op.getOperand(i-1));
5419 if (ThisIsNonZero) {
5420 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5421 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5422 ThisElt, DAG.getConstant(8, MVT::i8));
5424 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5428 if (ThisElt.getNode())
5429 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5430 DAG.getIntPtrConstant(i/2));
5434 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5437 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5439 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5440 unsigned NumNonZero, unsigned NumZero,
5442 const X86Subtarget* Subtarget,
5443 const TargetLowering &TLI) {
5450 for (unsigned i = 0; i < 8; ++i) {
5451 bool isNonZero = (NonZeros & (1 << i)) != 0;
5455 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5457 V = DAG.getUNDEF(MVT::v8i16);
5460 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5461 MVT::v8i16, V, Op.getOperand(i),
5462 DAG.getIntPtrConstant(i));
5469 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5470 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5471 unsigned NonZeros, unsigned NumNonZero,
5472 unsigned NumZero, SelectionDAG &DAG,
5473 const X86Subtarget *Subtarget,
5474 const TargetLowering &TLI) {
5475 // We know there's at least one non-zero element
5476 unsigned FirstNonZeroIdx = 0;
5477 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5478 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5479 X86::isZeroNode(FirstNonZero)) {
5481 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5484 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5485 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5488 SDValue V = FirstNonZero.getOperand(0);
5489 MVT VVT = V.getSimpleValueType();
5490 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5493 unsigned FirstNonZeroDst =
5494 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5495 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5496 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5497 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5499 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5500 SDValue Elem = Op.getOperand(Idx);
5501 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5504 // TODO: What else can be here? Deal with it.
5505 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5508 // TODO: Some optimizations are still possible here
5509 // ex: Getting one element from a vector, and the rest from another.
5510 if (Elem.getOperand(0) != V)
5513 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5516 else if (IncorrectIdx == -1U) {
5520 // There was already one element with an incorrect index.
5521 // We can't optimize this case to an insertps.
5525 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5527 EVT VT = Op.getSimpleValueType();
5528 unsigned ElementMoveMask = 0;
5529 if (IncorrectIdx == -1U)
5530 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5532 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5534 SDValue InsertpsMask =
5535 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5536 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5542 /// getVShift - Return a vector logical shift node.
5544 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5545 unsigned NumBits, SelectionDAG &DAG,
5546 const TargetLowering &TLI, SDLoc dl) {
5547 assert(VT.is128BitVector() && "Unknown type for VShift");
5548 EVT ShVT = MVT::v2i64;
5549 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5550 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5551 return DAG.getNode(ISD::BITCAST, dl, VT,
5552 DAG.getNode(Opc, dl, ShVT, SrcOp,
5553 DAG.getConstant(NumBits,
5554 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5558 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5560 // Check if the scalar load can be widened into a vector load. And if
5561 // the address is "base + cst" see if the cst can be "absorbed" into
5562 // the shuffle mask.
5563 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5564 SDValue Ptr = LD->getBasePtr();
5565 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5567 EVT PVT = LD->getValueType(0);
5568 if (PVT != MVT::i32 && PVT != MVT::f32)
5573 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5574 FI = FINode->getIndex();
5576 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5577 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5578 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5579 Offset = Ptr.getConstantOperandVal(1);
5580 Ptr = Ptr.getOperand(0);
5585 // FIXME: 256-bit vector instructions don't require a strict alignment,
5586 // improve this code to support it better.
5587 unsigned RequiredAlign = VT.getSizeInBits()/8;
5588 SDValue Chain = LD->getChain();
5589 // Make sure the stack object alignment is at least 16 or 32.
5590 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5591 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5592 if (MFI->isFixedObjectIndex(FI)) {
5593 // Can't change the alignment. FIXME: It's possible to compute
5594 // the exact stack offset and reference FI + adjust offset instead.
5595 // If someone *really* cares about this. That's the way to implement it.
5598 MFI->setObjectAlignment(FI, RequiredAlign);
5602 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5603 // Ptr + (Offset & ~15).
5606 if ((Offset % RequiredAlign) & 3)
5608 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5610 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5611 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5613 int EltNo = (Offset - StartOffset) >> 2;
5614 unsigned NumElems = VT.getVectorNumElements();
5616 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5617 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5618 LD->getPointerInfo().getWithOffset(StartOffset),
5619 false, false, false, 0);
5621 SmallVector<int, 8> Mask;
5622 for (unsigned i = 0; i != NumElems; ++i)
5623 Mask.push_back(EltNo);
5625 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5631 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5632 /// vector of type 'VT', see if the elements can be replaced by a single large
5633 /// load which has the same value as a build_vector whose operands are 'elts'.
5635 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5637 /// FIXME: we'd also like to handle the case where the last elements are zero
5638 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5639 /// There's even a handy isZeroNode for that purpose.
5640 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5641 SDLoc &DL, SelectionDAG &DAG,
5642 bool isAfterLegalize) {
5643 EVT EltVT = VT.getVectorElementType();
5644 unsigned NumElems = Elts.size();
5646 LoadSDNode *LDBase = nullptr;
5647 unsigned LastLoadedElt = -1U;
5649 // For each element in the initializer, see if we've found a load or an undef.
5650 // If we don't find an initial load element, or later load elements are
5651 // non-consecutive, bail out.
5652 for (unsigned i = 0; i < NumElems; ++i) {
5653 SDValue Elt = Elts[i];
5655 if (!Elt.getNode() ||
5656 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5659 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5661 LDBase = cast<LoadSDNode>(Elt.getNode());
5665 if (Elt.getOpcode() == ISD::UNDEF)
5668 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5669 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5674 // If we have found an entire vector of loads and undefs, then return a large
5675 // load of the entire vector width starting at the base pointer. If we found
5676 // consecutive loads for the low half, generate a vzext_load node.
5677 if (LastLoadedElt == NumElems - 1) {
5679 if (isAfterLegalize &&
5680 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5683 SDValue NewLd = SDValue();
5685 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5686 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5687 LDBase->getPointerInfo(),
5688 LDBase->isVolatile(), LDBase->isNonTemporal(),
5689 LDBase->isInvariant(), 0);
5690 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5691 LDBase->getPointerInfo(),
5692 LDBase->isVolatile(), LDBase->isNonTemporal(),
5693 LDBase->isInvariant(), LDBase->getAlignment());
5695 if (LDBase->hasAnyUseOfValue(1)) {
5696 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5698 SDValue(NewLd.getNode(), 1));
5699 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5700 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5701 SDValue(NewLd.getNode(), 1));
5706 if (NumElems == 4 && LastLoadedElt == 1 &&
5707 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5708 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5709 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5711 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5712 LDBase->getPointerInfo(),
5713 LDBase->getAlignment(),
5714 false/*isVolatile*/, true/*ReadMem*/,
5717 // Make sure the newly-created LOAD is in the same position as LDBase in
5718 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5719 // update uses of LDBase's output chain to use the TokenFactor.
5720 if (LDBase->hasAnyUseOfValue(1)) {
5721 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5722 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5723 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5724 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5725 SDValue(ResNode.getNode(), 1));
5728 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5733 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5734 /// to generate a splat value for the following cases:
5735 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5736 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5737 /// a scalar load, or a constant.
5738 /// The VBROADCAST node is returned when a pattern is found,
5739 /// or SDValue() otherwise.
5740 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5741 SelectionDAG &DAG) {
5742 if (!Subtarget->hasFp256())
5745 MVT VT = Op.getSimpleValueType();
5748 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5749 "Unsupported vector type for broadcast.");
5754 switch (Op.getOpcode()) {
5756 // Unknown pattern found.
5759 case ISD::BUILD_VECTOR: {
5760 // The BUILD_VECTOR node must be a splat.
5761 if (!isSplatVector(Op.getNode()))
5764 Ld = Op.getOperand(0);
5765 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5766 Ld.getOpcode() == ISD::ConstantFP);
5768 // The suspected load node has several users. Make sure that all
5769 // of its users are from the BUILD_VECTOR node.
5770 // Constants may have multiple users.
5771 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5776 case ISD::VECTOR_SHUFFLE: {
5777 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5779 // Shuffles must have a splat mask where the first element is
5781 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5784 SDValue Sc = Op.getOperand(0);
5785 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5786 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5788 if (!Subtarget->hasInt256())
5791 // Use the register form of the broadcast instruction available on AVX2.
5792 if (VT.getSizeInBits() >= 256)
5793 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5794 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5797 Ld = Sc.getOperand(0);
5798 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5799 Ld.getOpcode() == ISD::ConstantFP);
5801 // The scalar_to_vector node and the suspected
5802 // load node must have exactly one user.
5803 // Constants may have multiple users.
5805 // AVX-512 has register version of the broadcast
5806 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5807 Ld.getValueType().getSizeInBits() >= 32;
5808 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5815 bool IsGE256 = (VT.getSizeInBits() >= 256);
5817 // Handle the broadcasting a single constant scalar from the constant pool
5818 // into a vector. On Sandybridge it is still better to load a constant vector
5819 // from the constant pool and not to broadcast it from a scalar.
5820 if (ConstSplatVal && Subtarget->hasInt256()) {
5821 EVT CVT = Ld.getValueType();
5822 assert(!CVT.isVector() && "Must not broadcast a vector type");
5823 unsigned ScalarSize = CVT.getSizeInBits();
5825 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5826 const Constant *C = nullptr;
5827 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5828 C = CI->getConstantIntValue();
5829 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5830 C = CF->getConstantFPValue();
5832 assert(C && "Invalid constant type");
5834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5835 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5836 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5837 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5838 MachinePointerInfo::getConstantPool(),
5839 false, false, false, Alignment);
5841 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5845 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5846 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5848 // Handle AVX2 in-register broadcasts.
5849 if (!IsLoad && Subtarget->hasInt256() &&
5850 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5851 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5853 // The scalar source must be a normal load.
5857 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5858 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5860 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5861 // double since there is no vbroadcastsd xmm
5862 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5863 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5864 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5867 // Unsupported broadcast.
5871 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5872 /// underlying vector and index.
5874 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5876 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5878 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5879 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5882 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5884 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5886 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5887 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5890 // In this case the vector is the extract_subvector expression and the index
5891 // is 2, as specified by the shuffle.
5892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5893 SDValue ShuffleVec = SVOp->getOperand(0);
5894 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5895 assert(ShuffleVecVT.getVectorElementType() ==
5896 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5898 int ShuffleIdx = SVOp->getMaskElt(Idx);
5899 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5900 ExtractedFromVec = ShuffleVec;
5906 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5907 MVT VT = Op.getSimpleValueType();
5909 // Skip if insert_vec_elt is not supported.
5910 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5911 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5915 unsigned NumElems = Op.getNumOperands();
5919 SmallVector<unsigned, 4> InsertIndices;
5920 SmallVector<int, 8> Mask(NumElems, -1);
5922 for (unsigned i = 0; i != NumElems; ++i) {
5923 unsigned Opc = Op.getOperand(i).getOpcode();
5925 if (Opc == ISD::UNDEF)
5928 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5929 // Quit if more than 1 elements need inserting.
5930 if (InsertIndices.size() > 1)
5933 InsertIndices.push_back(i);
5937 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5938 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5939 // Quit if non-constant index.
5940 if (!isa<ConstantSDNode>(ExtIdx))
5942 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5944 // Quit if extracted from vector of different type.
5945 if (ExtractedFromVec.getValueType() != VT)
5948 if (!VecIn1.getNode())
5949 VecIn1 = ExtractedFromVec;
5950 else if (VecIn1 != ExtractedFromVec) {
5951 if (!VecIn2.getNode())
5952 VecIn2 = ExtractedFromVec;
5953 else if (VecIn2 != ExtractedFromVec)
5954 // Quit if more than 2 vectors to shuffle
5958 if (ExtractedFromVec == VecIn1)
5960 else if (ExtractedFromVec == VecIn2)
5961 Mask[i] = Idx + NumElems;
5964 if (!VecIn1.getNode())
5967 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5968 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5969 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5970 unsigned Idx = InsertIndices[i];
5971 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5972 DAG.getIntPtrConstant(Idx));
5978 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5980 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5982 MVT VT = Op.getSimpleValueType();
5983 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5984 "Unexpected type in LowerBUILD_VECTORvXi1!");
5987 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5988 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5989 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5990 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5993 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5994 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5995 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5996 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5999 bool AllContants = true;
6000 uint64_t Immediate = 0;
6001 int NonConstIdx = -1;
6002 bool IsSplat = true;
6003 unsigned NumNonConsts = 0;
6004 unsigned NumConsts = 0;
6005 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6006 SDValue In = Op.getOperand(idx);
6007 if (In.getOpcode() == ISD::UNDEF)
6009 if (!isa<ConstantSDNode>(In)) {
6010 AllContants = false;
6016 if (cast<ConstantSDNode>(In)->getZExtValue())
6017 Immediate |= (1ULL << idx);
6019 if (In != Op.getOperand(0))
6024 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6025 DAG.getConstant(Immediate, MVT::i16));
6026 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6027 DAG.getIntPtrConstant(0));
6030 if (NumNonConsts == 1 && NonConstIdx != 0) {
6033 SDValue VecAsImm = DAG.getConstant(Immediate,
6034 MVT::getIntegerVT(VT.getSizeInBits()));
6035 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6038 DstVec = DAG.getUNDEF(VT);
6039 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6040 Op.getOperand(NonConstIdx),
6041 DAG.getIntPtrConstant(NonConstIdx));
6043 if (!IsSplat && (NonConstIdx != 0))
6044 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6045 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6048 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6049 DAG.getConstant(-1, SelectVT),
6050 DAG.getConstant(0, SelectVT));
6052 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6053 DAG.getConstant((Immediate | 1), SelectVT),
6054 DAG.getConstant(Immediate, SelectVT));
6055 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6058 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6059 const X86Subtarget *Subtarget) {
6060 EVT VT = N->getValueType(0);
6062 // Try to match a horizontal ADD or SUB.
6063 if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) ||
6064 ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget->hasAVX()) ||
6065 ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) ||
6066 ((VT == MVT::v8i32 || VT == MVT::v16i16) && Subtarget->hasAVX2())) {
6067 unsigned NumOperands = N->getNumOperands();
6068 unsigned Opcode = N->getOperand(0)->getOpcode();
6069 bool isCommutable = false;
6070 bool CanFold = false;
6075 isCommutable = true;
6082 // Verify that operands have the same opcode; also, the opcode can only
6083 // be either of: ADD, FADD, SUB, FSUB.
6084 SDValue InVec0, InVec1;
6085 for (unsigned i = 0, e = NumOperands; i != e && CanFold; ++i) {
6086 SDValue Op = N->getOperand(i);
6087 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6092 SDValue Op0 = Op.getOperand(0);
6093 SDValue Op1 = Op.getOperand(1);
6095 // Try to match the following pattern:
6096 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6097 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6098 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6099 Op0.getOperand(0) == Op1.getOperand(0) &&
6100 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6101 isa<ConstantSDNode>(Op1.getOperand(1)));
6105 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6106 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6107 unsigned ExpectedIndex = (i * 2) % NumOperands;
6110 InVec0 = Op0.getOperand(0);
6111 else if (i * 2 == NumOperands)
6112 InVec1 = Op0.getOperand(0);
6114 SDValue Expected = (i * 2 < NumOperands) ? InVec0 : InVec1;
6115 if (I0 == ExpectedIndex)
6116 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6117 else if (isCommutable && I1 == ExpectedIndex) {
6118 // Try to see if we can match the following dag sequence:
6119 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6120 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6127 default : llvm_unreachable("Unexpected opcode found!");
6128 case ISD::ADD : NewOpcode = X86ISD::HADD; break;
6129 case ISD::FADD : NewOpcode = X86ISD::FHADD; break;
6130 case ISD::SUB : NewOpcode = X86ISD::HSUB; break;
6131 case ISD::FSUB : NewOpcode = X86ISD::FHSUB; break;
6134 return DAG.getNode(NewOpcode, SDLoc(N), VT, InVec0, InVec1);
6142 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6145 MVT VT = Op.getSimpleValueType();
6146 MVT ExtVT = VT.getVectorElementType();
6147 unsigned NumElems = Op.getNumOperands();
6149 // Generate vectors for predicate vectors.
6150 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6151 return LowerBUILD_VECTORvXi1(Op, DAG);
6153 // Vectors containing all zeros can be matched by pxor and xorps later
6154 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6155 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6156 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6157 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6160 return getZeroVector(VT, Subtarget, DAG, dl);
6163 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6164 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6165 // vpcmpeqd on 256-bit vectors.
6166 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6167 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6170 if (!VT.is512BitVector())
6171 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6174 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6175 if (Broadcast.getNode())
6178 unsigned EVTBits = ExtVT.getSizeInBits();
6180 unsigned NumZero = 0;
6181 unsigned NumNonZero = 0;
6182 unsigned NonZeros = 0;
6183 bool IsAllConstants = true;
6184 SmallSet<SDValue, 8> Values;
6185 for (unsigned i = 0; i < NumElems; ++i) {
6186 SDValue Elt = Op.getOperand(i);
6187 if (Elt.getOpcode() == ISD::UNDEF)
6190 if (Elt.getOpcode() != ISD::Constant &&
6191 Elt.getOpcode() != ISD::ConstantFP)
6192 IsAllConstants = false;
6193 if (X86::isZeroNode(Elt))
6196 NonZeros |= (1 << i);
6201 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6202 if (NumNonZero == 0)
6203 return DAG.getUNDEF(VT);
6205 // Special case for single non-zero, non-undef, element.
6206 if (NumNonZero == 1) {
6207 unsigned Idx = countTrailingZeros(NonZeros);
6208 SDValue Item = Op.getOperand(Idx);
6210 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6211 // the value are obviously zero, truncate the value to i32 and do the
6212 // insertion that way. Only do this if the value is non-constant or if the
6213 // value is a constant being inserted into element 0. It is cheaper to do
6214 // a constant pool load than it is to do a movd + shuffle.
6215 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6216 (!IsAllConstants || Idx == 0)) {
6217 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6219 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6220 EVT VecVT = MVT::v4i32;
6221 unsigned VecElts = 4;
6223 // Truncate the value (which may itself be a constant) to i32, and
6224 // convert it to a vector with movd (S2V+shuffle to zero extend).
6225 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6226 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6227 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6229 // Now we have our 32-bit value zero extended in the low element of
6230 // a vector. If Idx != 0, swizzle it into place.
6232 SmallVector<int, 4> Mask;
6233 Mask.push_back(Idx);
6234 for (unsigned i = 1; i != VecElts; ++i)
6236 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6239 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6243 // If we have a constant or non-constant insertion into the low element of
6244 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6245 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6246 // depending on what the source datatype is.
6249 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6251 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6252 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6253 if (VT.is256BitVector() || VT.is512BitVector()) {
6254 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6255 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6256 Item, DAG.getIntPtrConstant(0));
6258 assert(VT.is128BitVector() && "Expected an SSE value type!");
6259 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6260 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6261 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6264 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6265 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6266 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6267 if (VT.is256BitVector()) {
6268 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6269 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6271 assert(VT.is128BitVector() && "Expected an SSE value type!");
6272 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6274 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6278 // Is it a vector logical left shift?
6279 if (NumElems == 2 && Idx == 1 &&
6280 X86::isZeroNode(Op.getOperand(0)) &&
6281 !X86::isZeroNode(Op.getOperand(1))) {
6282 unsigned NumBits = VT.getSizeInBits();
6283 return getVShift(true, VT,
6284 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6285 VT, Op.getOperand(1)),
6286 NumBits/2, DAG, *this, dl);
6289 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6292 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6293 // is a non-constant being inserted into an element other than the low one,
6294 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6295 // movd/movss) to move this into the low element, then shuffle it into
6297 if (EVTBits == 32) {
6298 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6300 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6301 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6302 SmallVector<int, 8> MaskVec;
6303 for (unsigned i = 0; i != NumElems; ++i)
6304 MaskVec.push_back(i == Idx ? 0 : 1);
6305 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6309 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6310 if (Values.size() == 1) {
6311 if (EVTBits == 32) {
6312 // Instead of a shuffle like this:
6313 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6314 // Check if it's possible to issue this instead.
6315 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6316 unsigned Idx = countTrailingZeros(NonZeros);
6317 SDValue Item = Op.getOperand(Idx);
6318 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6319 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6324 // A vector full of immediates; various special cases are already
6325 // handled, so this is best done with a single constant-pool load.
6329 // For AVX-length vectors, build the individual 128-bit pieces and use
6330 // shuffles to put them in place.
6331 if (VT.is256BitVector() || VT.is512BitVector()) {
6332 SmallVector<SDValue, 64> V;
6333 for (unsigned i = 0; i != NumElems; ++i)
6334 V.push_back(Op.getOperand(i));
6336 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6338 // Build both the lower and upper subvector.
6339 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6340 makeArrayRef(&V[0], NumElems/2));
6341 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6342 makeArrayRef(&V[NumElems / 2], NumElems/2));
6344 // Recreate the wider vector with the lower and upper part.
6345 if (VT.is256BitVector())
6346 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6347 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6350 // Let legalizer expand 2-wide build_vectors.
6351 if (EVTBits == 64) {
6352 if (NumNonZero == 1) {
6353 // One half is zero or undef.
6354 unsigned Idx = countTrailingZeros(NonZeros);
6355 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6356 Op.getOperand(Idx));
6357 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6362 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6363 if (EVTBits == 8 && NumElems == 16) {
6364 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6366 if (V.getNode()) return V;
6369 if (EVTBits == 16 && NumElems == 8) {
6370 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6372 if (V.getNode()) return V;
6375 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6376 if (EVTBits == 32 && NumElems == 4) {
6377 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6378 NumZero, DAG, Subtarget, *this);
6383 // If element VT is == 32 bits, turn it into a number of shuffles.
6384 SmallVector<SDValue, 8> V(NumElems);
6385 if (NumElems == 4 && NumZero > 0) {
6386 for (unsigned i = 0; i < 4; ++i) {
6387 bool isZero = !(NonZeros & (1 << i));
6389 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6391 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6394 for (unsigned i = 0; i < 2; ++i) {
6395 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6398 V[i] = V[i*2]; // Must be a zero vector.
6401 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6404 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6407 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6412 bool Reverse1 = (NonZeros & 0x3) == 2;
6413 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6417 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6418 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6420 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6423 if (Values.size() > 1 && VT.is128BitVector()) {
6424 // Check for a build vector of consecutive loads.
6425 for (unsigned i = 0; i < NumElems; ++i)
6426 V[i] = Op.getOperand(i);
6428 // Check for elements which are consecutive loads.
6429 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6433 // Check for a build vector from mostly shuffle plus few inserting.
6434 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6438 // For SSE 4.1, use insertps to put the high elements into the low element.
6439 if (getSubtarget()->hasSSE41()) {
6441 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6442 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6444 Result = DAG.getUNDEF(VT);
6446 for (unsigned i = 1; i < NumElems; ++i) {
6447 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6448 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6449 Op.getOperand(i), DAG.getIntPtrConstant(i));
6454 // Otherwise, expand into a number of unpckl*, start by extending each of
6455 // our (non-undef) elements to the full vector width with the element in the
6456 // bottom slot of the vector (which generates no code for SSE).
6457 for (unsigned i = 0; i < NumElems; ++i) {
6458 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6459 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6461 V[i] = DAG.getUNDEF(VT);
6464 // Next, we iteratively mix elements, e.g. for v4f32:
6465 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6466 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6467 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6468 unsigned EltStride = NumElems >> 1;
6469 while (EltStride != 0) {
6470 for (unsigned i = 0; i < EltStride; ++i) {
6471 // If V[i+EltStride] is undef and this is the first round of mixing,
6472 // then it is safe to just drop this shuffle: V[i] is already in the
6473 // right place, the one element (since it's the first round) being
6474 // inserted as undef can be dropped. This isn't safe for successive
6475 // rounds because they will permute elements within both vectors.
6476 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6477 EltStride == NumElems/2)
6480 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6489 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6490 // to create 256-bit vectors from two other 128-bit ones.
6491 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6493 MVT ResVT = Op.getSimpleValueType();
6495 assert((ResVT.is256BitVector() ||
6496 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6498 SDValue V1 = Op.getOperand(0);
6499 SDValue V2 = Op.getOperand(1);
6500 unsigned NumElems = ResVT.getVectorNumElements();
6501 if(ResVT.is256BitVector())
6502 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6504 if (Op.getNumOperands() == 4) {
6505 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6506 ResVT.getVectorNumElements()/2);
6507 SDValue V3 = Op.getOperand(2);
6508 SDValue V4 = Op.getOperand(3);
6509 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6510 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6512 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6515 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6516 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6517 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6518 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6519 Op.getNumOperands() == 4)));
6521 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6522 // from two other 128-bit ones.
6524 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6525 return LowerAVXCONCAT_VECTORS(Op, DAG);
6528 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6529 bool hasInt256, unsigned *MaskOut = nullptr) {
6530 MVT EltVT = VT.getVectorElementType();
6532 // There is no blend with immediate in AVX-512.
6533 if (VT.is512BitVector())
6536 if (!hasSSE41 || EltVT == MVT::i8)
6538 if (!hasInt256 && VT == MVT::v16i16)
6541 unsigned MaskValue = 0;
6542 unsigned NumElems = VT.getVectorNumElements();
6543 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6544 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6545 unsigned NumElemsInLane = NumElems / NumLanes;
6547 // Blend for v16i16 should be symetric for the both lanes.
6548 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6550 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6551 int EltIdx = MaskVals[i];
6553 if ((EltIdx < 0 || EltIdx == (int)i) &&
6554 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6557 if (((unsigned)EltIdx == (i + NumElems)) &&
6558 (SndLaneEltIdx < 0 ||
6559 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6560 MaskValue |= (1 << i);
6566 *MaskOut = MaskValue;
6570 // Try to lower a shuffle node into a simple blend instruction.
6571 // This function assumes isBlendMask returns true for this
6572 // SuffleVectorSDNode
6573 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6575 const X86Subtarget *Subtarget,
6576 SelectionDAG &DAG) {
6577 MVT VT = SVOp->getSimpleValueType(0);
6578 MVT EltVT = VT.getVectorElementType();
6579 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6580 Subtarget->hasInt256() && "Trying to lower a "
6581 "VECTOR_SHUFFLE to a Blend but "
6582 "with the wrong mask"));
6583 SDValue V1 = SVOp->getOperand(0);
6584 SDValue V2 = SVOp->getOperand(1);
6586 unsigned NumElems = VT.getVectorNumElements();
6588 // Convert i32 vectors to floating point if it is not AVX2.
6589 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6591 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6592 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6594 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6595 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6598 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6599 DAG.getConstant(MaskValue, MVT::i32));
6600 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6603 /// In vector type \p VT, return true if the element at index \p InputIdx
6604 /// falls on a different 128-bit lane than \p OutputIdx.
6605 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6606 unsigned OutputIdx) {
6607 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6608 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6611 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6612 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6613 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6614 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6616 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6617 SelectionDAG &DAG) {
6618 MVT VT = V1.getSimpleValueType();
6619 assert(VT.is128BitVector() || VT.is256BitVector());
6621 MVT EltVT = VT.getVectorElementType();
6622 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6623 unsigned NumElts = VT.getVectorNumElements();
6625 SmallVector<SDValue, 32> PshufbMask;
6626 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6627 int InputIdx = MaskVals[OutputIdx];
6628 unsigned InputByteIdx;
6630 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6631 InputByteIdx = 0x80;
6633 // Cross lane is not allowed.
6634 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6636 InputByteIdx = InputIdx * EltSizeInBytes;
6637 // Index is an byte offset within the 128-bit lane.
6638 InputByteIdx &= 0xf;
6641 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6642 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6643 if (InputByteIdx != 0x80)
6648 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6650 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6651 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6652 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6655 // v8i16 shuffles - Prefer shuffles in the following order:
6656 // 1. [all] pshuflw, pshufhw, optional move
6657 // 2. [ssse3] 1 x pshufb
6658 // 3. [ssse3] 2 x pshufb + 1 x por
6659 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6661 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6662 SelectionDAG &DAG) {
6663 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6664 SDValue V1 = SVOp->getOperand(0);
6665 SDValue V2 = SVOp->getOperand(1);
6667 SmallVector<int, 8> MaskVals;
6669 // Determine if more than 1 of the words in each of the low and high quadwords
6670 // of the result come from the same quadword of one of the two inputs. Undef
6671 // mask values count as coming from any quadword, for better codegen.
6673 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6674 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6675 unsigned LoQuad[] = { 0, 0, 0, 0 };
6676 unsigned HiQuad[] = { 0, 0, 0, 0 };
6677 // Indices of quads used.
6678 std::bitset<4> InputQuads;
6679 for (unsigned i = 0; i < 8; ++i) {
6680 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6681 int EltIdx = SVOp->getMaskElt(i);
6682 MaskVals.push_back(EltIdx);
6691 InputQuads.set(EltIdx / 4);
6694 int BestLoQuad = -1;
6695 unsigned MaxQuad = 1;
6696 for (unsigned i = 0; i < 4; ++i) {
6697 if (LoQuad[i] > MaxQuad) {
6699 MaxQuad = LoQuad[i];
6703 int BestHiQuad = -1;
6705 for (unsigned i = 0; i < 4; ++i) {
6706 if (HiQuad[i] > MaxQuad) {
6708 MaxQuad = HiQuad[i];
6712 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6713 // of the two input vectors, shuffle them into one input vector so only a
6714 // single pshufb instruction is necessary. If there are more than 2 input
6715 // quads, disable the next transformation since it does not help SSSE3.
6716 bool V1Used = InputQuads[0] || InputQuads[1];
6717 bool V2Used = InputQuads[2] || InputQuads[3];
6718 if (Subtarget->hasSSSE3()) {
6719 if (InputQuads.count() == 2 && V1Used && V2Used) {
6720 BestLoQuad = InputQuads[0] ? 0 : 1;
6721 BestHiQuad = InputQuads[2] ? 2 : 3;
6723 if (InputQuads.count() > 2) {
6729 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6730 // the shuffle mask. If a quad is scored as -1, that means that it contains
6731 // words from all 4 input quadwords.
6733 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6735 BestLoQuad < 0 ? 0 : BestLoQuad,
6736 BestHiQuad < 0 ? 1 : BestHiQuad
6738 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6739 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6740 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6741 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6743 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6744 // source words for the shuffle, to aid later transformations.
6745 bool AllWordsInNewV = true;
6746 bool InOrder[2] = { true, true };
6747 for (unsigned i = 0; i != 8; ++i) {
6748 int idx = MaskVals[i];
6750 InOrder[i/4] = false;
6751 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6753 AllWordsInNewV = false;
6757 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6758 if (AllWordsInNewV) {
6759 for (int i = 0; i != 8; ++i) {
6760 int idx = MaskVals[i];
6763 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6764 if ((idx != i) && idx < 4)
6766 if ((idx != i) && idx > 3)
6775 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6776 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6777 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6778 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6779 unsigned TargetMask = 0;
6780 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6781 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6782 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6783 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6784 getShufflePSHUFLWImmediate(SVOp);
6785 V1 = NewV.getOperand(0);
6786 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6790 // Promote splats to a larger type which usually leads to more efficient code.
6791 // FIXME: Is this true if pshufb is available?
6792 if (SVOp->isSplat())
6793 return PromoteSplat(SVOp, DAG);
6795 // If we have SSSE3, and all words of the result are from 1 input vector,
6796 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6797 // is present, fall back to case 4.
6798 if (Subtarget->hasSSSE3()) {
6799 SmallVector<SDValue,16> pshufbMask;
6801 // If we have elements from both input vectors, set the high bit of the
6802 // shuffle mask element to zero out elements that come from V2 in the V1
6803 // mask, and elements that come from V1 in the V2 mask, so that the two
6804 // results can be OR'd together.
6805 bool TwoInputs = V1Used && V2Used;
6806 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6808 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6810 // Calculate the shuffle mask for the second input, shuffle it, and
6811 // OR it with the first shuffled input.
6812 CommuteVectorShuffleMask(MaskVals, 8);
6813 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6814 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6815 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6818 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6819 // and update MaskVals with new element order.
6820 std::bitset<8> InOrder;
6821 if (BestLoQuad >= 0) {
6822 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6823 for (int i = 0; i != 4; ++i) {
6824 int idx = MaskVals[i];
6827 } else if ((idx / 4) == BestLoQuad) {
6832 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6835 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6836 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6837 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6839 getShufflePSHUFLWImmediate(SVOp), DAG);
6843 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6844 // and update MaskVals with the new element order.
6845 if (BestHiQuad >= 0) {
6846 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6847 for (unsigned i = 4; i != 8; ++i) {
6848 int idx = MaskVals[i];
6851 } else if ((idx / 4) == BestHiQuad) {
6852 MaskV[i] = (idx & 3) + 4;
6856 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6859 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6860 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6861 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6863 getShufflePSHUFHWImmediate(SVOp), DAG);
6867 // In case BestHi & BestLo were both -1, which means each quadword has a word
6868 // from each of the four input quadwords, calculate the InOrder bitvector now
6869 // before falling through to the insert/extract cleanup.
6870 if (BestLoQuad == -1 && BestHiQuad == -1) {
6872 for (int i = 0; i != 8; ++i)
6873 if (MaskVals[i] < 0 || MaskVals[i] == i)
6877 // The other elements are put in the right place using pextrw and pinsrw.
6878 for (unsigned i = 0; i != 8; ++i) {
6881 int EltIdx = MaskVals[i];
6884 SDValue ExtOp = (EltIdx < 8) ?
6885 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6886 DAG.getIntPtrConstant(EltIdx)) :
6887 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6888 DAG.getIntPtrConstant(EltIdx - 8));
6889 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6890 DAG.getIntPtrConstant(i));
6895 /// \brief v16i16 shuffles
6897 /// FIXME: We only support generation of a single pshufb currently. We can
6898 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6899 /// well (e.g 2 x pshufb + 1 x por).
6901 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6902 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6903 SDValue V1 = SVOp->getOperand(0);
6904 SDValue V2 = SVOp->getOperand(1);
6907 if (V2.getOpcode() != ISD::UNDEF)
6910 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6911 return getPSHUFB(MaskVals, V1, dl, DAG);
6914 // v16i8 shuffles - Prefer shuffles in the following order:
6915 // 1. [ssse3] 1 x pshufb
6916 // 2. [ssse3] 2 x pshufb + 1 x por
6917 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6918 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6919 const X86Subtarget* Subtarget,
6920 SelectionDAG &DAG) {
6921 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6922 SDValue V1 = SVOp->getOperand(0);
6923 SDValue V2 = SVOp->getOperand(1);
6925 ArrayRef<int> MaskVals = SVOp->getMask();
6927 // Promote splats to a larger type which usually leads to more efficient code.
6928 // FIXME: Is this true if pshufb is available?
6929 if (SVOp->isSplat())
6930 return PromoteSplat(SVOp, DAG);
6932 // If we have SSSE3, case 1 is generated when all result bytes come from
6933 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6934 // present, fall back to case 3.
6936 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6937 if (Subtarget->hasSSSE3()) {
6938 SmallVector<SDValue,16> pshufbMask;
6940 // If all result elements are from one input vector, then only translate
6941 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6943 // Otherwise, we have elements from both input vectors, and must zero out
6944 // elements that come from V2 in the first mask, and V1 in the second mask
6945 // so that we can OR them together.
6946 for (unsigned i = 0; i != 16; ++i) {
6947 int EltIdx = MaskVals[i];
6948 if (EltIdx < 0 || EltIdx >= 16)
6950 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6952 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6953 DAG.getNode(ISD::BUILD_VECTOR, dl,
6954 MVT::v16i8, pshufbMask));
6956 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6957 // the 2nd operand if it's undefined or zero.
6958 if (V2.getOpcode() == ISD::UNDEF ||
6959 ISD::isBuildVectorAllZeros(V2.getNode()))
6962 // Calculate the shuffle mask for the second input, shuffle it, and
6963 // OR it with the first shuffled input.
6965 for (unsigned i = 0; i != 16; ++i) {
6966 int EltIdx = MaskVals[i];
6967 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6968 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6970 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6971 DAG.getNode(ISD::BUILD_VECTOR, dl,
6972 MVT::v16i8, pshufbMask));
6973 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6976 // No SSSE3 - Calculate in place words and then fix all out of place words
6977 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6978 // the 16 different words that comprise the two doublequadword input vectors.
6979 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6980 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6982 for (int i = 0; i != 8; ++i) {
6983 int Elt0 = MaskVals[i*2];
6984 int Elt1 = MaskVals[i*2+1];
6986 // This word of the result is all undef, skip it.
6987 if (Elt0 < 0 && Elt1 < 0)
6990 // This word of the result is already in the correct place, skip it.
6991 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6994 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6995 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6998 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6999 // using a single extract together, load it and store it.
7000 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7001 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7002 DAG.getIntPtrConstant(Elt1 / 2));
7003 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7004 DAG.getIntPtrConstant(i));
7008 // If Elt1 is defined, extract it from the appropriate source. If the
7009 // source byte is not also odd, shift the extracted word left 8 bits
7010 // otherwise clear the bottom 8 bits if we need to do an or.
7012 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7013 DAG.getIntPtrConstant(Elt1 / 2));
7014 if ((Elt1 & 1) == 0)
7015 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7017 TLI.getShiftAmountTy(InsElt.getValueType())));
7019 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7020 DAG.getConstant(0xFF00, MVT::i16));
7022 // If Elt0 is defined, extract it from the appropriate source. If the
7023 // source byte is not also even, shift the extracted word right 8 bits. If
7024 // Elt1 was also defined, OR the extracted values together before
7025 // inserting them in the result.
7027 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7028 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7029 if ((Elt0 & 1) != 0)
7030 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7032 TLI.getShiftAmountTy(InsElt0.getValueType())));
7034 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7035 DAG.getConstant(0x00FF, MVT::i16));
7036 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7039 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7040 DAG.getIntPtrConstant(i));
7042 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7045 // v32i8 shuffles - Translate to VPSHUFB if possible.
7047 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7048 const X86Subtarget *Subtarget,
7049 SelectionDAG &DAG) {
7050 MVT VT = SVOp->getSimpleValueType(0);
7051 SDValue V1 = SVOp->getOperand(0);
7052 SDValue V2 = SVOp->getOperand(1);
7054 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7056 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7057 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7058 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7060 // VPSHUFB may be generated if
7061 // (1) one of input vector is undefined or zeroinitializer.
7062 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7063 // And (2) the mask indexes don't cross the 128-bit lane.
7064 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7065 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7068 if (V1IsAllZero && !V2IsAllZero) {
7069 CommuteVectorShuffleMask(MaskVals, 32);
7072 return getPSHUFB(MaskVals, V1, dl, DAG);
7075 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7076 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7077 /// done when every pair / quad of shuffle mask elements point to elements in
7078 /// the right sequence. e.g.
7079 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7081 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7082 SelectionDAG &DAG) {
7083 MVT VT = SVOp->getSimpleValueType(0);
7085 unsigned NumElems = VT.getVectorNumElements();
7088 switch (VT.SimpleTy) {
7089 default: llvm_unreachable("Unexpected!");
7092 return SDValue(SVOp, 0);
7093 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7094 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7095 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7096 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7097 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7098 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7101 SmallVector<int, 8> MaskVec;
7102 for (unsigned i = 0; i != NumElems; i += Scale) {
7104 for (unsigned j = 0; j != Scale; ++j) {
7105 int EltIdx = SVOp->getMaskElt(i+j);
7109 StartIdx = (EltIdx / Scale);
7110 if (EltIdx != (int)(StartIdx*Scale + j))
7113 MaskVec.push_back(StartIdx);
7116 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7117 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7118 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7121 /// getVZextMovL - Return a zero-extending vector move low node.
7123 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7124 SDValue SrcOp, SelectionDAG &DAG,
7125 const X86Subtarget *Subtarget, SDLoc dl) {
7126 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7127 LoadSDNode *LD = nullptr;
7128 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7129 LD = dyn_cast<LoadSDNode>(SrcOp);
7131 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7133 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7134 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7135 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7136 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7137 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7139 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7140 return DAG.getNode(ISD::BITCAST, dl, VT,
7141 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7142 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7150 return DAG.getNode(ISD::BITCAST, dl, VT,
7151 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7152 DAG.getNode(ISD::BITCAST, dl,
7156 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7157 /// which could not be matched by any known target speficic shuffle
7159 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7161 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7162 if (NewOp.getNode())
7165 MVT VT = SVOp->getSimpleValueType(0);
7167 unsigned NumElems = VT.getVectorNumElements();
7168 unsigned NumLaneElems = NumElems / 2;
7171 MVT EltVT = VT.getVectorElementType();
7172 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7175 SmallVector<int, 16> Mask;
7176 for (unsigned l = 0; l < 2; ++l) {
7177 // Build a shuffle mask for the output, discovering on the fly which
7178 // input vectors to use as shuffle operands (recorded in InputUsed).
7179 // If building a suitable shuffle vector proves too hard, then bail
7180 // out with UseBuildVector set.
7181 bool UseBuildVector = false;
7182 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7183 unsigned LaneStart = l * NumLaneElems;
7184 for (unsigned i = 0; i != NumLaneElems; ++i) {
7185 // The mask element. This indexes into the input.
7186 int Idx = SVOp->getMaskElt(i+LaneStart);
7188 // the mask element does not index into any input vector.
7193 // The input vector this mask element indexes into.
7194 int Input = Idx / NumLaneElems;
7196 // Turn the index into an offset from the start of the input vector.
7197 Idx -= Input * NumLaneElems;
7199 // Find or create a shuffle vector operand to hold this input.
7201 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7202 if (InputUsed[OpNo] == Input)
7203 // This input vector is already an operand.
7205 if (InputUsed[OpNo] < 0) {
7206 // Create a new operand for this input vector.
7207 InputUsed[OpNo] = Input;
7212 if (OpNo >= array_lengthof(InputUsed)) {
7213 // More than two input vectors used! Give up on trying to create a
7214 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7215 UseBuildVector = true;
7219 // Add the mask index for the new shuffle vector.
7220 Mask.push_back(Idx + OpNo * NumLaneElems);
7223 if (UseBuildVector) {
7224 SmallVector<SDValue, 16> SVOps;
7225 for (unsigned i = 0; i != NumLaneElems; ++i) {
7226 // The mask element. This indexes into the input.
7227 int Idx = SVOp->getMaskElt(i+LaneStart);
7229 SVOps.push_back(DAG.getUNDEF(EltVT));
7233 // The input vector this mask element indexes into.
7234 int Input = Idx / NumElems;
7236 // Turn the index into an offset from the start of the input vector.
7237 Idx -= Input * NumElems;
7239 // Extract the vector element by hand.
7240 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7241 SVOp->getOperand(Input),
7242 DAG.getIntPtrConstant(Idx)));
7245 // Construct the output using a BUILD_VECTOR.
7246 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7247 } else if (InputUsed[0] < 0) {
7248 // No input vectors were used! The result is undefined.
7249 Output[l] = DAG.getUNDEF(NVT);
7251 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7252 (InputUsed[0] % 2) * NumLaneElems,
7254 // If only one input was used, use an undefined vector for the other.
7255 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7256 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7257 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7258 // At least one input vector was used. Create a new shuffle vector.
7259 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7265 // Concatenate the result back
7266 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7269 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7270 /// 4 elements, and match them with several different shuffle types.
7272 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7273 SDValue V1 = SVOp->getOperand(0);
7274 SDValue V2 = SVOp->getOperand(1);
7276 MVT VT = SVOp->getSimpleValueType(0);
7278 assert(VT.is128BitVector() && "Unsupported vector size");
7280 std::pair<int, int> Locs[4];
7281 int Mask1[] = { -1, -1, -1, -1 };
7282 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7286 for (unsigned i = 0; i != 4; ++i) {
7287 int Idx = PermMask[i];
7289 Locs[i] = std::make_pair(-1, -1);
7291 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7293 Locs[i] = std::make_pair(0, NumLo);
7297 Locs[i] = std::make_pair(1, NumHi);
7299 Mask1[2+NumHi] = Idx;
7305 if (NumLo <= 2 && NumHi <= 2) {
7306 // If no more than two elements come from either vector. This can be
7307 // implemented with two shuffles. First shuffle gather the elements.
7308 // The second shuffle, which takes the first shuffle as both of its
7309 // vector operands, put the elements into the right order.
7310 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7312 int Mask2[] = { -1, -1, -1, -1 };
7314 for (unsigned i = 0; i != 4; ++i)
7315 if (Locs[i].first != -1) {
7316 unsigned Idx = (i < 2) ? 0 : 4;
7317 Idx += Locs[i].first * 2 + Locs[i].second;
7321 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7324 if (NumLo == 3 || NumHi == 3) {
7325 // Otherwise, we must have three elements from one vector, call it X, and
7326 // one element from the other, call it Y. First, use a shufps to build an
7327 // intermediate vector with the one element from Y and the element from X
7328 // that will be in the same half in the final destination (the indexes don't
7329 // matter). Then, use a shufps to build the final vector, taking the half
7330 // containing the element from Y from the intermediate, and the other half
7333 // Normalize it so the 3 elements come from V1.
7334 CommuteVectorShuffleMask(PermMask, 4);
7338 // Find the element from V2.
7340 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7341 int Val = PermMask[HiIndex];
7348 Mask1[0] = PermMask[HiIndex];
7350 Mask1[2] = PermMask[HiIndex^1];
7352 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7355 Mask1[0] = PermMask[0];
7356 Mask1[1] = PermMask[1];
7357 Mask1[2] = HiIndex & 1 ? 6 : 4;
7358 Mask1[3] = HiIndex & 1 ? 4 : 6;
7359 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7362 Mask1[0] = HiIndex & 1 ? 2 : 0;
7363 Mask1[1] = HiIndex & 1 ? 0 : 2;
7364 Mask1[2] = PermMask[2];
7365 Mask1[3] = PermMask[3];
7370 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7373 // Break it into (shuffle shuffle_hi, shuffle_lo).
7374 int LoMask[] = { -1, -1, -1, -1 };
7375 int HiMask[] = { -1, -1, -1, -1 };
7377 int *MaskPtr = LoMask;
7378 unsigned MaskIdx = 0;
7381 for (unsigned i = 0; i != 4; ++i) {
7388 int Idx = PermMask[i];
7390 Locs[i] = std::make_pair(-1, -1);
7391 } else if (Idx < 4) {
7392 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7393 MaskPtr[LoIdx] = Idx;
7396 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7397 MaskPtr[HiIdx] = Idx;
7402 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7403 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7404 int MaskOps[] = { -1, -1, -1, -1 };
7405 for (unsigned i = 0; i != 4; ++i)
7406 if (Locs[i].first != -1)
7407 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7408 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7411 static bool MayFoldVectorLoad(SDValue V) {
7412 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7413 V = V.getOperand(0);
7415 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7416 V = V.getOperand(0);
7417 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7418 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7419 // BUILD_VECTOR (load), undef
7420 V = V.getOperand(0);
7422 return MayFoldLoad(V);
7426 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7427 MVT VT = Op.getSimpleValueType();
7429 // Canonizalize to v2f64.
7430 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7431 return DAG.getNode(ISD::BITCAST, dl, VT,
7432 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7437 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7439 SDValue V1 = Op.getOperand(0);
7440 SDValue V2 = Op.getOperand(1);
7441 MVT VT = Op.getSimpleValueType();
7443 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7445 if (HasSSE2 && VT == MVT::v2f64)
7446 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7448 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7449 return DAG.getNode(ISD::BITCAST, dl, VT,
7450 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7451 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7452 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7456 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7457 SDValue V1 = Op.getOperand(0);
7458 SDValue V2 = Op.getOperand(1);
7459 MVT VT = Op.getSimpleValueType();
7461 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7462 "unsupported shuffle type");
7464 if (V2.getOpcode() == ISD::UNDEF)
7468 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7472 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7473 SDValue V1 = Op.getOperand(0);
7474 SDValue V2 = Op.getOperand(1);
7475 MVT VT = Op.getSimpleValueType();
7476 unsigned NumElems = VT.getVectorNumElements();
7478 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7479 // operand of these instructions is only memory, so check if there's a
7480 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7482 bool CanFoldLoad = false;
7484 // Trivial case, when V2 comes from a load.
7485 if (MayFoldVectorLoad(V2))
7488 // When V1 is a load, it can be folded later into a store in isel, example:
7489 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7491 // (MOVLPSmr addr:$src1, VR128:$src2)
7492 // So, recognize this potential and also use MOVLPS or MOVLPD
7493 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7496 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7498 if (HasSSE2 && NumElems == 2)
7499 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7502 // If we don't care about the second element, proceed to use movss.
7503 if (SVOp->getMaskElt(1) != -1)
7504 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7507 // movl and movlp will both match v2i64, but v2i64 is never matched by
7508 // movl earlier because we make it strict to avoid messing with the movlp load
7509 // folding logic (see the code above getMOVLP call). Match it here then,
7510 // this is horrible, but will stay like this until we move all shuffle
7511 // matching to x86 specific nodes. Note that for the 1st condition all
7512 // types are matched with movsd.
7514 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7515 // as to remove this logic from here, as much as possible
7516 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7517 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7518 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7521 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7523 // Invert the operand order and use SHUFPS to match it.
7524 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7525 getShuffleSHUFImmediate(SVOp), DAG);
7528 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7529 SelectionDAG &DAG) {
7531 MVT VT = Load->getSimpleValueType(0);
7532 MVT EVT = VT.getVectorElementType();
7533 SDValue Addr = Load->getOperand(1);
7534 SDValue NewAddr = DAG.getNode(
7535 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7536 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7539 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7540 DAG.getMachineFunction().getMachineMemOperand(
7541 Load->getMemOperand(), 0, EVT.getStoreSize()));
7545 // It is only safe to call this function if isINSERTPSMask is true for
7546 // this shufflevector mask.
7547 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7548 SelectionDAG &DAG) {
7549 // Generate an insertps instruction when inserting an f32 from memory onto a
7550 // v4f32 or when copying a member from one v4f32 to another.
7551 // We also use it for transferring i32 from one register to another,
7552 // since it simply copies the same bits.
7553 // If we're transferring an i32 from memory to a specific element in a
7554 // register, we output a generic DAG that will match the PINSRD
7556 MVT VT = SVOp->getSimpleValueType(0);
7557 MVT EVT = VT.getVectorElementType();
7558 SDValue V1 = SVOp->getOperand(0);
7559 SDValue V2 = SVOp->getOperand(1);
7560 auto Mask = SVOp->getMask();
7561 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7562 "unsupported vector type for insertps/pinsrd");
7564 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7565 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7566 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7574 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7577 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7578 "More than one element from V1 and from V2, or no elements from one "
7579 "of the vectors. This case should not have returned true from "
7584 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7587 if (MayFoldLoad(From)) {
7588 // Trivial case, when From comes from a load and is only used by the
7589 // shuffle. Make it use insertps from the vector that we need from that
7592 NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7593 if (!NewLoad.getNode())
7596 if (EVT == MVT::f32) {
7597 // Create this as a scalar to vector to match the instruction pattern.
7598 SDValue LoadScalarToVector =
7599 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7600 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7601 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7603 } else { // EVT == MVT::i32
7604 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7605 // instruction, to match the PINSRD instruction, which loads an i32 to a
7606 // certain vector element.
7607 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7608 DAG.getConstant(DestIndex, MVT::i32));
7612 // Vector-element-to-vector
7613 unsigned SrcIndex = Mask[DestIndex] % 4;
7614 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7615 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7618 // Reduce a vector shuffle to zext.
7619 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7620 SelectionDAG &DAG) {
7621 // PMOVZX is only available from SSE41.
7622 if (!Subtarget->hasSSE41())
7625 MVT VT = Op.getSimpleValueType();
7627 // Only AVX2 support 256-bit vector integer extending.
7628 if (!Subtarget->hasInt256() && VT.is256BitVector())
7631 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7633 SDValue V1 = Op.getOperand(0);
7634 SDValue V2 = Op.getOperand(1);
7635 unsigned NumElems = VT.getVectorNumElements();
7637 // Extending is an unary operation and the element type of the source vector
7638 // won't be equal to or larger than i64.
7639 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7640 VT.getVectorElementType() == MVT::i64)
7643 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7644 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7645 while ((1U << Shift) < NumElems) {
7646 if (SVOp->getMaskElt(1U << Shift) == 1)
7649 // The maximal ratio is 8, i.e. from i8 to i64.
7654 // Check the shuffle mask.
7655 unsigned Mask = (1U << Shift) - 1;
7656 for (unsigned i = 0; i != NumElems; ++i) {
7657 int EltIdx = SVOp->getMaskElt(i);
7658 if ((i & Mask) != 0 && EltIdx != -1)
7660 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7664 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7665 MVT NeVT = MVT::getIntegerVT(NBits);
7666 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7668 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7671 // Simplify the operand as it's prepared to be fed into shuffle.
7672 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7673 if (V1.getOpcode() == ISD::BITCAST &&
7674 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7675 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7676 V1.getOperand(0).getOperand(0)
7677 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7678 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7679 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7680 ConstantSDNode *CIdx =
7681 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7682 // If it's foldable, i.e. normal load with single use, we will let code
7683 // selection to fold it. Otherwise, we will short the conversion sequence.
7684 if (CIdx && CIdx->getZExtValue() == 0 &&
7685 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7686 MVT FullVT = V.getSimpleValueType();
7687 MVT V1VT = V1.getSimpleValueType();
7688 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7689 // The "ext_vec_elt" node is wider than the result node.
7690 // In this case we should extract subvector from V.
7691 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7692 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7693 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7694 FullVT.getVectorNumElements()/Ratio);
7695 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7696 DAG.getIntPtrConstant(0));
7698 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7702 return DAG.getNode(ISD::BITCAST, DL, VT,
7703 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7706 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7707 SelectionDAG &DAG) {
7708 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7709 MVT VT = Op.getSimpleValueType();
7711 SDValue V1 = Op.getOperand(0);
7712 SDValue V2 = Op.getOperand(1);
7714 if (isZeroShuffle(SVOp))
7715 return getZeroVector(VT, Subtarget, DAG, dl);
7717 // Handle splat operations
7718 if (SVOp->isSplat()) {
7719 // Use vbroadcast whenever the splat comes from a foldable load
7720 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7721 if (Broadcast.getNode())
7725 // Check integer expanding shuffles.
7726 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7727 if (NewOp.getNode())
7730 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7732 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7734 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7735 if (NewOp.getNode())
7736 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7737 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7738 // FIXME: Figure out a cleaner way to do this.
7739 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7740 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7741 if (NewOp.getNode()) {
7742 MVT NewVT = NewOp.getSimpleValueType();
7743 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7744 NewVT, true, false))
7745 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7748 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7749 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7750 if (NewOp.getNode()) {
7751 MVT NewVT = NewOp.getSimpleValueType();
7752 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7753 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7762 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7763 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7764 SDValue V1 = Op.getOperand(0);
7765 SDValue V2 = Op.getOperand(1);
7766 MVT VT = Op.getSimpleValueType();
7768 unsigned NumElems = VT.getVectorNumElements();
7769 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7770 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7771 bool V1IsSplat = false;
7772 bool V2IsSplat = false;
7773 bool HasSSE2 = Subtarget->hasSSE2();
7774 bool HasFp256 = Subtarget->hasFp256();
7775 bool HasInt256 = Subtarget->hasInt256();
7776 MachineFunction &MF = DAG.getMachineFunction();
7777 bool OptForSize = MF.getFunction()->getAttributes().
7778 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7780 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7782 if (V1IsUndef && V2IsUndef)
7783 return DAG.getUNDEF(VT);
7785 // When we create a shuffle node we put the UNDEF node to second operand,
7786 // but in some cases the first operand may be transformed to UNDEF.
7787 // In this case we should just commute the node.
7789 return CommuteVectorShuffle(SVOp, DAG);
7791 // Vector shuffle lowering takes 3 steps:
7793 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7794 // narrowing and commutation of operands should be handled.
7795 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7797 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7798 // so the shuffle can be broken into other shuffles and the legalizer can
7799 // try the lowering again.
7801 // The general idea is that no vector_shuffle operation should be left to
7802 // be matched during isel, all of them must be converted to a target specific
7805 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7806 // narrowing and commutation of operands should be handled. The actual code
7807 // doesn't include all of those, work in progress...
7808 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7809 if (NewOp.getNode())
7812 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7814 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7815 // unpckh_undef). Only use pshufd if speed is more important than size.
7816 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7817 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7818 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7819 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7821 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7822 V2IsUndef && MayFoldVectorLoad(V1))
7823 return getMOVDDup(Op, dl, V1, DAG);
7825 if (isMOVHLPS_v_undef_Mask(M, VT))
7826 return getMOVHighToLow(Op, dl, DAG);
7828 // Use to match splats
7829 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7830 (VT == MVT::v2f64 || VT == MVT::v2i64))
7831 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7833 if (isPSHUFDMask(M, VT)) {
7834 // The actual implementation will match the mask in the if above and then
7835 // during isel it can match several different instructions, not only pshufd
7836 // as its name says, sad but true, emulate the behavior for now...
7837 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7838 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7840 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7842 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7843 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7845 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7846 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7849 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7853 if (isPALIGNRMask(M, VT, Subtarget))
7854 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7855 getShufflePALIGNRImmediate(SVOp),
7858 // Check if this can be converted into a logical shift.
7859 bool isLeft = false;
7862 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7863 if (isShift && ShVal.hasOneUse()) {
7864 // If the shifted value has multiple uses, it may be cheaper to use
7865 // v_set0 + movlhps or movhlps, etc.
7866 MVT EltVT = VT.getVectorElementType();
7867 ShAmt *= EltVT.getSizeInBits();
7868 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7871 if (isMOVLMask(M, VT)) {
7872 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7873 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7874 if (!isMOVLPMask(M, VT)) {
7875 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7876 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7878 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7879 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7883 // FIXME: fold these into legal mask.
7884 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7885 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7887 if (isMOVHLPSMask(M, VT))
7888 return getMOVHighToLow(Op, dl, DAG);
7890 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7891 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7893 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7894 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7896 if (isMOVLPMask(M, VT))
7897 return getMOVLP(Op, dl, DAG, HasSSE2);
7899 if (ShouldXformToMOVHLPS(M, VT) ||
7900 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7901 return CommuteVectorShuffle(SVOp, DAG);
7904 // No better options. Use a vshldq / vsrldq.
7905 MVT EltVT = VT.getVectorElementType();
7906 ShAmt *= EltVT.getSizeInBits();
7907 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7910 bool Commuted = false;
7911 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7912 // 1,1,1,1 -> v8i16 though.
7913 V1IsSplat = isSplatVector(V1.getNode());
7914 V2IsSplat = isSplatVector(V2.getNode());
7916 // Canonicalize the splat or undef, if present, to be on the RHS.
7917 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7918 CommuteVectorShuffleMask(M, NumElems);
7920 std::swap(V1IsSplat, V2IsSplat);
7924 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7925 // Shuffling low element of v1 into undef, just return v1.
7928 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7929 // the instruction selector will not match, so get a canonical MOVL with
7930 // swapped operands to undo the commute.
7931 return getMOVL(DAG, dl, VT, V2, V1);
7934 if (isUNPCKLMask(M, VT, HasInt256))
7935 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7937 if (isUNPCKHMask(M, VT, HasInt256))
7938 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7941 // Normalize mask so all entries that point to V2 points to its first
7942 // element then try to match unpck{h|l} again. If match, return a
7943 // new vector_shuffle with the corrected mask.p
7944 SmallVector<int, 8> NewMask(M.begin(), M.end());
7945 NormalizeMask(NewMask, NumElems);
7946 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7947 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7948 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7949 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7953 // Commute is back and try unpck* again.
7954 // FIXME: this seems wrong.
7955 CommuteVectorShuffleMask(M, NumElems);
7957 std::swap(V1IsSplat, V2IsSplat);
7959 if (isUNPCKLMask(M, VT, HasInt256))
7960 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7962 if (isUNPCKHMask(M, VT, HasInt256))
7963 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7966 // Normalize the node to match x86 shuffle ops if needed
7967 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7968 return CommuteVectorShuffle(SVOp, DAG);
7970 // The checks below are all present in isShuffleMaskLegal, but they are
7971 // inlined here right now to enable us to directly emit target specific
7972 // nodes, and remove one by one until they don't return Op anymore.
7974 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7975 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7976 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7977 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7980 if (isPSHUFHWMask(M, VT, HasInt256))
7981 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7982 getShufflePSHUFHWImmediate(SVOp),
7985 if (isPSHUFLWMask(M, VT, HasInt256))
7986 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7987 getShufflePSHUFLWImmediate(SVOp),
7990 if (isSHUFPMask(M, VT))
7991 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7992 getShuffleSHUFImmediate(SVOp), DAG);
7994 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7995 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7996 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7997 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7999 //===--------------------------------------------------------------------===//
8000 // Generate target specific nodes for 128 or 256-bit shuffles only
8001 // supported in the AVX instruction set.
8004 // Handle VMOVDDUPY permutations
8005 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8006 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8008 // Handle VPERMILPS/D* permutations
8009 if (isVPERMILPMask(M, VT)) {
8010 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8011 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8012 getShuffleSHUFImmediate(SVOp), DAG);
8013 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8014 getShuffleSHUFImmediate(SVOp), DAG);
8018 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8019 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8020 Idx*(NumElems/2), DAG, dl);
8022 // Handle VPERM2F128/VPERM2I128 permutations
8023 if (isVPERM2X128Mask(M, VT, HasFp256))
8024 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8025 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8028 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8030 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8032 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8033 return getINSERTPS(SVOp, dl, DAG);
8036 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8037 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8039 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8040 VT.is512BitVector()) {
8041 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8042 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8043 SmallVector<SDValue, 16> permclMask;
8044 for (unsigned i = 0; i != NumElems; ++i) {
8045 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8048 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8050 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8051 return DAG.getNode(X86ISD::VPERMV, dl, VT,
8052 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8053 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8054 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8057 //===--------------------------------------------------------------------===//
8058 // Since no target specific shuffle was selected for this generic one,
8059 // lower it into other known shuffles. FIXME: this isn't true yet, but
8060 // this is the plan.
8063 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8064 if (VT == MVT::v8i16) {
8065 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8066 if (NewOp.getNode())
8070 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8071 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8072 if (NewOp.getNode())
8076 if (VT == MVT::v16i8) {
8077 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8078 if (NewOp.getNode())
8082 if (VT == MVT::v32i8) {
8083 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8084 if (NewOp.getNode())
8088 // Handle all 128-bit wide vectors with 4 elements, and match them with
8089 // several different shuffle types.
8090 if (NumElems == 4 && VT.is128BitVector())
8091 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8093 // Handle general 256-bit shuffles
8094 if (VT.is256BitVector())
8095 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8100 // This function assumes its argument is a BUILD_VECTOR of constants or
8101 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8103 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8104 unsigned &MaskValue) {
8106 unsigned NumElems = BuildVector->getNumOperands();
8107 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8108 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8109 unsigned NumElemsInLane = NumElems / NumLanes;
8111 // Blend for v16i16 should be symetric for the both lanes.
8112 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8113 SDValue EltCond = BuildVector->getOperand(i);
8114 SDValue SndLaneEltCond =
8115 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8117 int Lane1Cond = -1, Lane2Cond = -1;
8118 if (isa<ConstantSDNode>(EltCond))
8119 Lane1Cond = !isZero(EltCond);
8120 if (isa<ConstantSDNode>(SndLaneEltCond))
8121 Lane2Cond = !isZero(SndLaneEltCond);
8123 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8124 // Lane1Cond != 0, means we want the first argument.
8125 // Lane1Cond == 0, means we want the second argument.
8126 // The encoding of this argument is 0 for the first argument, 1
8127 // for the second. Therefore, invert the condition.
8128 MaskValue |= !Lane1Cond << i;
8129 else if (Lane1Cond < 0)
8130 MaskValue |= !Lane2Cond << i;
8137 // Try to lower a vselect node into a simple blend instruction.
8138 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8139 SelectionDAG &DAG) {
8140 SDValue Cond = Op.getOperand(0);
8141 SDValue LHS = Op.getOperand(1);
8142 SDValue RHS = Op.getOperand(2);
8144 MVT VT = Op.getSimpleValueType();
8145 MVT EltVT = VT.getVectorElementType();
8146 unsigned NumElems = VT.getVectorNumElements();
8148 // There is no blend with immediate in AVX-512.
8149 if (VT.is512BitVector())
8152 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8154 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8157 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8160 // Check the mask for BLEND and build the value.
8161 unsigned MaskValue = 0;
8162 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8165 // Convert i32 vectors to floating point if it is not AVX2.
8166 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8168 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8169 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8171 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8172 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8175 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8176 DAG.getConstant(MaskValue, MVT::i32));
8177 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8180 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8181 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8182 if (BlendOp.getNode())
8185 // Some types for vselect were previously set to Expand, not Legal or
8186 // Custom. Return an empty SDValue so we fall-through to Expand, after
8187 // the Custom lowering phase.
8188 MVT VT = Op.getSimpleValueType();
8189 switch (VT.SimpleTy) {
8197 // We couldn't create a "Blend with immediate" node.
8198 // This node should still be legal, but we'll have to emit a blendv*
8203 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8204 MVT VT = Op.getSimpleValueType();
8207 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8210 if (VT.getSizeInBits() == 8) {
8211 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8212 Op.getOperand(0), Op.getOperand(1));
8213 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8214 DAG.getValueType(VT));
8215 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8218 if (VT.getSizeInBits() == 16) {
8219 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8220 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8222 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8223 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8224 DAG.getNode(ISD::BITCAST, dl,
8228 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8229 Op.getOperand(0), Op.getOperand(1));
8230 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8231 DAG.getValueType(VT));
8232 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8235 if (VT == MVT::f32) {
8236 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8237 // the result back to FR32 register. It's only worth matching if the
8238 // result has a single use which is a store or a bitcast to i32. And in
8239 // the case of a store, it's not worth it if the index is a constant 0,
8240 // because a MOVSSmr can be used instead, which is smaller and faster.
8241 if (!Op.hasOneUse())
8243 SDNode *User = *Op.getNode()->use_begin();
8244 if ((User->getOpcode() != ISD::STORE ||
8245 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8246 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8247 (User->getOpcode() != ISD::BITCAST ||
8248 User->getValueType(0) != MVT::i32))
8250 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8251 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8254 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8257 if (VT == MVT::i32 || VT == MVT::i64) {
8258 // ExtractPS/pextrq works with constant index.
8259 if (isa<ConstantSDNode>(Op.getOperand(1)))
8265 /// Extract one bit from mask vector, like v16i1 or v8i1.
8266 /// AVX-512 feature.
8268 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8269 SDValue Vec = Op.getOperand(0);
8271 MVT VecVT = Vec.getSimpleValueType();
8272 SDValue Idx = Op.getOperand(1);
8273 MVT EltVT = Op.getSimpleValueType();
8275 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8277 // variable index can't be handled in mask registers,
8278 // extend vector to VR512
8279 if (!isa<ConstantSDNode>(Idx)) {
8280 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8281 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8282 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8283 ExtVT.getVectorElementType(), Ext, Idx);
8284 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8287 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8288 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8289 unsigned MaxSift = rc->getSize()*8 - 1;
8290 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8291 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8292 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8293 DAG.getConstant(MaxSift, MVT::i8));
8294 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8295 DAG.getIntPtrConstant(0));
8299 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8300 SelectionDAG &DAG) const {
8302 SDValue Vec = Op.getOperand(0);
8303 MVT VecVT = Vec.getSimpleValueType();
8304 SDValue Idx = Op.getOperand(1);
8306 if (Op.getSimpleValueType() == MVT::i1)
8307 return ExtractBitFromMaskVector(Op, DAG);
8309 if (!isa<ConstantSDNode>(Idx)) {
8310 if (VecVT.is512BitVector() ||
8311 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8312 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8315 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8316 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8317 MaskEltVT.getSizeInBits());
8319 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8320 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8321 getZeroVector(MaskVT, Subtarget, DAG, dl),
8322 Idx, DAG.getConstant(0, getPointerTy()));
8323 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8324 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8325 Perm, DAG.getConstant(0, getPointerTy()));
8330 // If this is a 256-bit vector result, first extract the 128-bit vector and
8331 // then extract the element from the 128-bit vector.
8332 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8334 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8335 // Get the 128-bit vector.
8336 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8337 MVT EltVT = VecVT.getVectorElementType();
8339 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8341 //if (IdxVal >= NumElems/2)
8342 // IdxVal -= NumElems/2;
8343 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8344 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8345 DAG.getConstant(IdxVal, MVT::i32));
8348 assert(VecVT.is128BitVector() && "Unexpected vector length");
8350 if (Subtarget->hasSSE41()) {
8351 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8356 MVT VT = Op.getSimpleValueType();
8357 // TODO: handle v16i8.
8358 if (VT.getSizeInBits() == 16) {
8359 SDValue Vec = Op.getOperand(0);
8360 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8362 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8363 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8364 DAG.getNode(ISD::BITCAST, dl,
8367 // Transform it so it match pextrw which produces a 32-bit result.
8368 MVT EltVT = MVT::i32;
8369 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8370 Op.getOperand(0), Op.getOperand(1));
8371 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8372 DAG.getValueType(VT));
8373 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8376 if (VT.getSizeInBits() == 32) {
8377 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8381 // SHUFPS the element to the lowest double word, then movss.
8382 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8383 MVT VVT = Op.getOperand(0).getSimpleValueType();
8384 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8385 DAG.getUNDEF(VVT), Mask);
8386 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8387 DAG.getIntPtrConstant(0));
8390 if (VT.getSizeInBits() == 64) {
8391 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8392 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8393 // to match extract_elt for f64.
8394 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8398 // UNPCKHPD the element to the lowest double word, then movsd.
8399 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8400 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8401 int Mask[2] = { 1, -1 };
8402 MVT VVT = Op.getOperand(0).getSimpleValueType();
8403 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8404 DAG.getUNDEF(VVT), Mask);
8405 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8406 DAG.getIntPtrConstant(0));
8412 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8413 MVT VT = Op.getSimpleValueType();
8414 MVT EltVT = VT.getVectorElementType();
8417 SDValue N0 = Op.getOperand(0);
8418 SDValue N1 = Op.getOperand(1);
8419 SDValue N2 = Op.getOperand(2);
8421 if (!VT.is128BitVector())
8424 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8425 isa<ConstantSDNode>(N2)) {
8427 if (VT == MVT::v8i16)
8428 Opc = X86ISD::PINSRW;
8429 else if (VT == MVT::v16i8)
8430 Opc = X86ISD::PINSRB;
8432 Opc = X86ISD::PINSRB;
8434 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8436 if (N1.getValueType() != MVT::i32)
8437 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8438 if (N2.getValueType() != MVT::i32)
8439 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8440 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8443 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8444 // Bits [7:6] of the constant are the source select. This will always be
8445 // zero here. The DAG Combiner may combine an extract_elt index into these
8446 // bits. For example (insert (extract, 3), 2) could be matched by putting
8447 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8448 // Bits [5:4] of the constant are the destination select. This is the
8449 // value of the incoming immediate.
8450 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8451 // combine either bitwise AND or insert of float 0.0 to set these bits.
8452 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8453 // Create this as a scalar to vector..
8454 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8455 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8458 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8459 // PINSR* works with constant index.
8465 /// Insert one bit to mask vector, like v16i1 or v8i1.
8466 /// AVX-512 feature.
8468 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8470 SDValue Vec = Op.getOperand(0);
8471 SDValue Elt = Op.getOperand(1);
8472 SDValue Idx = Op.getOperand(2);
8473 MVT VecVT = Vec.getSimpleValueType();
8475 if (!isa<ConstantSDNode>(Idx)) {
8476 // Non constant index. Extend source and destination,
8477 // insert element and then truncate the result.
8478 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8479 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8480 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8481 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8482 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8483 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8486 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8487 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8488 if (Vec.getOpcode() == ISD::UNDEF)
8489 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8490 DAG.getConstant(IdxVal, MVT::i8));
8491 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8492 unsigned MaxSift = rc->getSize()*8 - 1;
8493 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8494 DAG.getConstant(MaxSift, MVT::i8));
8495 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8496 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8497 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8500 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8501 MVT VT = Op.getSimpleValueType();
8502 MVT EltVT = VT.getVectorElementType();
8504 if (EltVT == MVT::i1)
8505 return InsertBitToMaskVector(Op, DAG);
8508 SDValue N0 = Op.getOperand(0);
8509 SDValue N1 = Op.getOperand(1);
8510 SDValue N2 = Op.getOperand(2);
8512 // If this is a 256-bit vector result, first extract the 128-bit vector,
8513 // insert the element into the extracted half and then place it back.
8514 if (VT.is256BitVector() || VT.is512BitVector()) {
8515 if (!isa<ConstantSDNode>(N2))
8518 // Get the desired 128-bit vector half.
8519 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8520 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8522 // Insert the element into the desired half.
8523 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8524 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8526 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8527 DAG.getConstant(IdxIn128, MVT::i32));
8529 // Insert the changed part back to the 256-bit vector
8530 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8533 if (Subtarget->hasSSE41())
8534 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8536 if (EltVT == MVT::i8)
8539 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8540 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8541 // as its second argument.
8542 if (N1.getValueType() != MVT::i32)
8543 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8544 if (N2.getValueType() != MVT::i32)
8545 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8546 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8551 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8553 MVT OpVT = Op.getSimpleValueType();
8555 // If this is a 256-bit vector result, first insert into a 128-bit
8556 // vector and then insert into the 256-bit vector.
8557 if (!OpVT.is128BitVector()) {
8558 // Insert into a 128-bit vector.
8559 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8560 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8561 OpVT.getVectorNumElements() / SizeFactor);
8563 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8565 // Insert the 128-bit vector.
8566 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8569 if (OpVT == MVT::v1i64 &&
8570 Op.getOperand(0).getValueType() == MVT::i64)
8571 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8573 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8574 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8575 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8576 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8579 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8580 // a simple subregister reference or explicit instructions to grab
8581 // upper bits of a vector.
8582 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8583 SelectionDAG &DAG) {
8585 SDValue In = Op.getOperand(0);
8586 SDValue Idx = Op.getOperand(1);
8587 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8588 MVT ResVT = Op.getSimpleValueType();
8589 MVT InVT = In.getSimpleValueType();
8591 if (Subtarget->hasFp256()) {
8592 if (ResVT.is128BitVector() &&
8593 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8594 isa<ConstantSDNode>(Idx)) {
8595 return Extract128BitVector(In, IdxVal, DAG, dl);
8597 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8598 isa<ConstantSDNode>(Idx)) {
8599 return Extract256BitVector(In, IdxVal, DAG, dl);
8605 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8606 // simple superregister reference or explicit instructions to insert
8607 // the upper bits of a vector.
8608 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8609 SelectionDAG &DAG) {
8610 if (Subtarget->hasFp256()) {
8611 SDLoc dl(Op.getNode());
8612 SDValue Vec = Op.getNode()->getOperand(0);
8613 SDValue SubVec = Op.getNode()->getOperand(1);
8614 SDValue Idx = Op.getNode()->getOperand(2);
8616 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8617 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8618 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8619 isa<ConstantSDNode>(Idx)) {
8620 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8621 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8624 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8625 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8626 isa<ConstantSDNode>(Idx)) {
8627 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8628 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8634 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8635 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8636 // one of the above mentioned nodes. It has to be wrapped because otherwise
8637 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8638 // be used to form addressing mode. These wrapped nodes will be selected
8641 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8642 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8644 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8646 unsigned char OpFlag = 0;
8647 unsigned WrapperKind = X86ISD::Wrapper;
8648 CodeModel::Model M = getTargetMachine().getCodeModel();
8650 if (Subtarget->isPICStyleRIPRel() &&
8651 (M == CodeModel::Small || M == CodeModel::Kernel))
8652 WrapperKind = X86ISD::WrapperRIP;
8653 else if (Subtarget->isPICStyleGOT())
8654 OpFlag = X86II::MO_GOTOFF;
8655 else if (Subtarget->isPICStyleStubPIC())
8656 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8658 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8660 CP->getOffset(), OpFlag);
8662 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8663 // With PIC, the address is actually $g + Offset.
8665 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8666 DAG.getNode(X86ISD::GlobalBaseReg,
8667 SDLoc(), getPointerTy()),
8674 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8675 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8677 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8679 unsigned char OpFlag = 0;
8680 unsigned WrapperKind = X86ISD::Wrapper;
8681 CodeModel::Model M = getTargetMachine().getCodeModel();
8683 if (Subtarget->isPICStyleRIPRel() &&
8684 (M == CodeModel::Small || M == CodeModel::Kernel))
8685 WrapperKind = X86ISD::WrapperRIP;
8686 else if (Subtarget->isPICStyleGOT())
8687 OpFlag = X86II::MO_GOTOFF;
8688 else if (Subtarget->isPICStyleStubPIC())
8689 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8691 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8694 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8696 // With PIC, the address is actually $g + Offset.
8698 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8699 DAG.getNode(X86ISD::GlobalBaseReg,
8700 SDLoc(), getPointerTy()),
8707 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8708 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8710 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8712 unsigned char OpFlag = 0;
8713 unsigned WrapperKind = X86ISD::Wrapper;
8714 CodeModel::Model M = getTargetMachine().getCodeModel();
8716 if (Subtarget->isPICStyleRIPRel() &&
8717 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8718 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8719 OpFlag = X86II::MO_GOTPCREL;
8720 WrapperKind = X86ISD::WrapperRIP;
8721 } else if (Subtarget->isPICStyleGOT()) {
8722 OpFlag = X86II::MO_GOT;
8723 } else if (Subtarget->isPICStyleStubPIC()) {
8724 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8725 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8726 OpFlag = X86II::MO_DARWIN_NONLAZY;
8729 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8732 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8734 // With PIC, the address is actually $g + Offset.
8735 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8736 !Subtarget->is64Bit()) {
8737 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8738 DAG.getNode(X86ISD::GlobalBaseReg,
8739 SDLoc(), getPointerTy()),
8743 // For symbols that require a load from a stub to get the address, emit the
8745 if (isGlobalStubReference(OpFlag))
8746 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8747 MachinePointerInfo::getGOT(), false, false, false, 0);
8753 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8754 // Create the TargetBlockAddressAddress node.
8755 unsigned char OpFlags =
8756 Subtarget->ClassifyBlockAddressReference();
8757 CodeModel::Model M = getTargetMachine().getCodeModel();
8758 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8759 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8761 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8764 if (Subtarget->isPICStyleRIPRel() &&
8765 (M == CodeModel::Small || M == CodeModel::Kernel))
8766 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8768 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8770 // With PIC, the address is actually $g + Offset.
8771 if (isGlobalRelativeToPICBase(OpFlags)) {
8772 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8773 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8781 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8782 int64_t Offset, SelectionDAG &DAG) const {
8783 // Create the TargetGlobalAddress node, folding in the constant
8784 // offset if it is legal.
8785 unsigned char OpFlags =
8786 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8787 CodeModel::Model M = getTargetMachine().getCodeModel();
8789 if (OpFlags == X86II::MO_NO_FLAG &&
8790 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8791 // A direct static reference to a global.
8792 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8795 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8798 if (Subtarget->isPICStyleRIPRel() &&
8799 (M == CodeModel::Small || M == CodeModel::Kernel))
8800 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8802 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8804 // With PIC, the address is actually $g + Offset.
8805 if (isGlobalRelativeToPICBase(OpFlags)) {
8806 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8807 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8811 // For globals that require a load from a stub to get the address, emit the
8813 if (isGlobalStubReference(OpFlags))
8814 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8815 MachinePointerInfo::getGOT(), false, false, false, 0);
8817 // If there was a non-zero offset that we didn't fold, create an explicit
8820 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8821 DAG.getConstant(Offset, getPointerTy()));
8827 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8828 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8829 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8830 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8834 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8835 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8836 unsigned char OperandFlags, bool LocalDynamic = false) {
8837 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8838 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8840 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8841 GA->getValueType(0),
8845 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8849 SDValue Ops[] = { Chain, TGA, *InFlag };
8850 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8852 SDValue Ops[] = { Chain, TGA };
8853 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8856 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8857 MFI->setAdjustsStack(true);
8859 SDValue Flag = Chain.getValue(1);
8860 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8863 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8865 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8868 SDLoc dl(GA); // ? function entry point might be better
8869 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8870 DAG.getNode(X86ISD::GlobalBaseReg,
8871 SDLoc(), PtrVT), InFlag);
8872 InFlag = Chain.getValue(1);
8874 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8877 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8879 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8881 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8882 X86::RAX, X86II::MO_TLSGD);
8885 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8891 // Get the start address of the TLS block for this module.
8892 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8893 .getInfo<X86MachineFunctionInfo>();
8894 MFI->incNumLocalDynamicTLSAccesses();
8898 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8899 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8902 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8903 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8904 InFlag = Chain.getValue(1);
8905 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8906 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8909 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8913 unsigned char OperandFlags = X86II::MO_DTPOFF;
8914 unsigned WrapperKind = X86ISD::Wrapper;
8915 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8916 GA->getValueType(0),
8917 GA->getOffset(), OperandFlags);
8918 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8920 // Add x@dtpoff with the base.
8921 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8924 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8925 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8926 const EVT PtrVT, TLSModel::Model model,
8927 bool is64Bit, bool isPIC) {
8930 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8931 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8932 is64Bit ? 257 : 256));
8934 SDValue ThreadPointer =
8935 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8936 MachinePointerInfo(Ptr), false, false, false, 0);
8938 unsigned char OperandFlags = 0;
8939 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8941 unsigned WrapperKind = X86ISD::Wrapper;
8942 if (model == TLSModel::LocalExec) {
8943 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8944 } else if (model == TLSModel::InitialExec) {
8946 OperandFlags = X86II::MO_GOTTPOFF;
8947 WrapperKind = X86ISD::WrapperRIP;
8949 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8952 llvm_unreachable("Unexpected model");
8955 // emit "addl x@ntpoff,%eax" (local exec)
8956 // or "addl x@indntpoff,%eax" (initial exec)
8957 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8959 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8960 GA->getOffset(), OperandFlags);
8961 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8963 if (model == TLSModel::InitialExec) {
8964 if (isPIC && !is64Bit) {
8965 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8966 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8970 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8971 MachinePointerInfo::getGOT(), false, false, false, 0);
8974 // The address of the thread local variable is the add of the thread
8975 // pointer with the offset of the variable.
8976 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8980 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8982 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8983 const GlobalValue *GV = GA->getGlobal();
8985 if (Subtarget->isTargetELF()) {
8986 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8989 case TLSModel::GeneralDynamic:
8990 if (Subtarget->is64Bit())
8991 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8992 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8993 case TLSModel::LocalDynamic:
8994 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8995 Subtarget->is64Bit());
8996 case TLSModel::InitialExec:
8997 case TLSModel::LocalExec:
8998 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8999 Subtarget->is64Bit(),
9000 getTargetMachine().getRelocationModel() == Reloc::PIC_);
9002 llvm_unreachable("Unknown TLS model.");
9005 if (Subtarget->isTargetDarwin()) {
9006 // Darwin only has one model of TLS. Lower to that.
9007 unsigned char OpFlag = 0;
9008 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9009 X86ISD::WrapperRIP : X86ISD::Wrapper;
9011 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9013 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
9014 !Subtarget->is64Bit();
9016 OpFlag = X86II::MO_TLVP_PIC_BASE;
9018 OpFlag = X86II::MO_TLVP;
9020 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9021 GA->getValueType(0),
9022 GA->getOffset(), OpFlag);
9023 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9025 // With PIC32, the address is actually $g + Offset.
9027 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9028 DAG.getNode(X86ISD::GlobalBaseReg,
9029 SDLoc(), getPointerTy()),
9032 // Lowering the machine isd will make sure everything is in the right
9034 SDValue Chain = DAG.getEntryNode();
9035 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9036 SDValue Args[] = { Chain, Offset };
9037 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9039 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9040 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9041 MFI->setAdjustsStack(true);
9043 // And our return value (tls address) is in the standard call return value
9045 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9046 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9050 if (Subtarget->isTargetKnownWindowsMSVC() ||
9051 Subtarget->isTargetWindowsGNU()) {
9052 // Just use the implicit TLS architecture
9053 // Need to generate someting similar to:
9054 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9056 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
9057 // mov rcx, qword [rdx+rcx*8]
9058 // mov eax, .tls$:tlsvar
9059 // [rax+rcx] contains the address
9060 // Windows 64bit: gs:0x58
9061 // Windows 32bit: fs:__tls_array
9064 SDValue Chain = DAG.getEntryNode();
9066 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9067 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9068 // use its literal value of 0x2C.
9069 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9070 ? Type::getInt8PtrTy(*DAG.getContext(),
9072 : Type::getInt32PtrTy(*DAG.getContext(),
9076 Subtarget->is64Bit()
9077 ? DAG.getIntPtrConstant(0x58)
9078 : (Subtarget->isTargetWindowsGNU()
9079 ? DAG.getIntPtrConstant(0x2C)
9080 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9082 SDValue ThreadPointer =
9083 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9084 MachinePointerInfo(Ptr), false, false, false, 0);
9086 // Load the _tls_index variable
9087 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9088 if (Subtarget->is64Bit())
9089 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9090 IDX, MachinePointerInfo(), MVT::i32,
9093 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9094 false, false, false, 0);
9096 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9098 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9100 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9101 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9102 false, false, false, 0);
9104 // Get the offset of start of .tls section
9105 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9106 GA->getValueType(0),
9107 GA->getOffset(), X86II::MO_SECREL);
9108 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9110 // The address of the thread local variable is the add of the thread
9111 // pointer with the offset of the variable.
9112 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9115 llvm_unreachable("TLS not implemented for this target.");
9118 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9119 /// and take a 2 x i32 value to shift plus a shift amount.
9120 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9121 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9122 MVT VT = Op.getSimpleValueType();
9123 unsigned VTBits = VT.getSizeInBits();
9125 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9126 SDValue ShOpLo = Op.getOperand(0);
9127 SDValue ShOpHi = Op.getOperand(1);
9128 SDValue ShAmt = Op.getOperand(2);
9129 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9130 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9132 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9133 DAG.getConstant(VTBits - 1, MVT::i8));
9134 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9135 DAG.getConstant(VTBits - 1, MVT::i8))
9136 : DAG.getConstant(0, VT);
9139 if (Op.getOpcode() == ISD::SHL_PARTS) {
9140 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9141 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9143 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9144 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9147 // If the shift amount is larger or equal than the width of a part we can't
9148 // rely on the results of shld/shrd. Insert a test and select the appropriate
9149 // values for large shift amounts.
9150 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9151 DAG.getConstant(VTBits, MVT::i8));
9152 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9153 AndNode, DAG.getConstant(0, MVT::i8));
9156 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9157 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9158 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9160 if (Op.getOpcode() == ISD::SHL_PARTS) {
9161 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9162 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9164 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9165 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9168 SDValue Ops[2] = { Lo, Hi };
9169 return DAG.getMergeValues(Ops, dl);
9172 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9173 SelectionDAG &DAG) const {
9174 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9176 if (SrcVT.isVector())
9179 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9180 "Unknown SINT_TO_FP to lower!");
9182 // These are really Legal; return the operand so the caller accepts it as
9184 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9186 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9187 Subtarget->is64Bit()) {
9192 unsigned Size = SrcVT.getSizeInBits()/8;
9193 MachineFunction &MF = DAG.getMachineFunction();
9194 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9195 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9196 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9198 MachinePointerInfo::getFixedStack(SSFI),
9200 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9203 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9205 SelectionDAG &DAG) const {
9209 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9211 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9213 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9215 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9217 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9218 MachineMemOperand *MMO;
9220 int SSFI = FI->getIndex();
9222 DAG.getMachineFunction()
9223 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9224 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9226 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9227 StackSlot = StackSlot.getOperand(1);
9229 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9230 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9232 Tys, Ops, SrcVT, MMO);
9235 Chain = Result.getValue(1);
9236 SDValue InFlag = Result.getValue(2);
9238 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9239 // shouldn't be necessary except that RFP cannot be live across
9240 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9241 MachineFunction &MF = DAG.getMachineFunction();
9242 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9243 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9244 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9245 Tys = DAG.getVTList(MVT::Other);
9247 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9249 MachineMemOperand *MMO =
9250 DAG.getMachineFunction()
9251 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9252 MachineMemOperand::MOStore, SSFISize, SSFISize);
9254 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9255 Ops, Op.getValueType(), MMO);
9256 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9257 MachinePointerInfo::getFixedStack(SSFI),
9258 false, false, false, 0);
9264 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9265 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9266 SelectionDAG &DAG) const {
9267 // This algorithm is not obvious. Here it is what we're trying to output:
9270 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9271 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9275 pshufd $0x4e, %xmm0, %xmm1
9281 LLVMContext *Context = DAG.getContext();
9283 // Build some magic constants.
9284 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9285 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9286 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9288 SmallVector<Constant*,2> CV1;
9290 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9291 APInt(64, 0x4330000000000000ULL))));
9293 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9294 APInt(64, 0x4530000000000000ULL))));
9295 Constant *C1 = ConstantVector::get(CV1);
9296 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9298 // Load the 64-bit value into an XMM register.
9299 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9301 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9302 MachinePointerInfo::getConstantPool(),
9303 false, false, false, 16);
9304 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9305 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9308 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9309 MachinePointerInfo::getConstantPool(),
9310 false, false, false, 16);
9311 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9312 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9315 if (Subtarget->hasSSE3()) {
9316 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9317 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9319 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9320 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9322 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9323 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9327 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9328 DAG.getIntPtrConstant(0));
9331 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9332 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9333 SelectionDAG &DAG) const {
9335 // FP constant to bias correct the final result.
9336 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9339 // Load the 32-bit value into an XMM register.
9340 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9343 // Zero out the upper parts of the register.
9344 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9346 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9347 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9348 DAG.getIntPtrConstant(0));
9350 // Or the load with the bias.
9351 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9352 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9353 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9355 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9356 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9357 MVT::v2f64, Bias)));
9358 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9359 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9360 DAG.getIntPtrConstant(0));
9362 // Subtract the bias.
9363 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9365 // Handle final rounding.
9366 EVT DestVT = Op.getValueType();
9368 if (DestVT.bitsLT(MVT::f64))
9369 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9370 DAG.getIntPtrConstant(0));
9371 if (DestVT.bitsGT(MVT::f64))
9372 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9374 // Handle final rounding.
9378 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9379 SelectionDAG &DAG) const {
9380 SDValue N0 = Op.getOperand(0);
9381 MVT SVT = N0.getSimpleValueType();
9384 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9385 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9386 "Custom UINT_TO_FP is not supported!");
9388 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9389 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9390 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9393 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9394 SelectionDAG &DAG) const {
9395 SDValue N0 = Op.getOperand(0);
9398 if (Op.getValueType().isVector())
9399 return lowerUINT_TO_FP_vec(Op, DAG);
9401 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9402 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9403 // the optimization here.
9404 if (DAG.SignBitIsZero(N0))
9405 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9407 MVT SrcVT = N0.getSimpleValueType();
9408 MVT DstVT = Op.getSimpleValueType();
9409 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9410 return LowerUINT_TO_FP_i64(Op, DAG);
9411 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9412 return LowerUINT_TO_FP_i32(Op, DAG);
9413 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9416 // Make a 64-bit buffer, and use it to build an FILD.
9417 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9418 if (SrcVT == MVT::i32) {
9419 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9420 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9421 getPointerTy(), StackSlot, WordOff);
9422 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9423 StackSlot, MachinePointerInfo(),
9425 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9426 OffsetSlot, MachinePointerInfo(),
9428 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9432 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9433 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9434 StackSlot, MachinePointerInfo(),
9436 // For i64 source, we need to add the appropriate power of 2 if the input
9437 // was negative. This is the same as the optimization in
9438 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9439 // we must be careful to do the computation in x87 extended precision, not
9440 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9441 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9442 MachineMemOperand *MMO =
9443 DAG.getMachineFunction()
9444 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9445 MachineMemOperand::MOLoad, 8, 8);
9447 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9448 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9449 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9452 APInt FF(32, 0x5F800000ULL);
9454 // Check whether the sign bit is set.
9455 SDValue SignSet = DAG.getSetCC(dl,
9456 getSetCCResultType(*DAG.getContext(), MVT::i64),
9457 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9460 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9461 SDValue FudgePtr = DAG.getConstantPool(
9462 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9465 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9466 SDValue Zero = DAG.getIntPtrConstant(0);
9467 SDValue Four = DAG.getIntPtrConstant(4);
9468 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9470 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9472 // Load the value out, extending it from f32 to f80.
9473 // FIXME: Avoid the extend by constructing the right constant pool?
9474 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9475 FudgePtr, MachinePointerInfo::getConstantPool(),
9476 MVT::f32, false, false, 4);
9477 // Extend everything to 80 bits to force it to be done on x87.
9478 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9479 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9482 std::pair<SDValue,SDValue>
9483 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9484 bool IsSigned, bool IsReplace) const {
9487 EVT DstTy = Op.getValueType();
9489 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9490 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9494 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9495 DstTy.getSimpleVT() >= MVT::i16 &&
9496 "Unknown FP_TO_INT to lower!");
9498 // These are really Legal.
9499 if (DstTy == MVT::i32 &&
9500 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9501 return std::make_pair(SDValue(), SDValue());
9502 if (Subtarget->is64Bit() &&
9503 DstTy == MVT::i64 &&
9504 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9505 return std::make_pair(SDValue(), SDValue());
9507 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9508 // stack slot, or into the FTOL runtime function.
9509 MachineFunction &MF = DAG.getMachineFunction();
9510 unsigned MemSize = DstTy.getSizeInBits()/8;
9511 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9512 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9515 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9516 Opc = X86ISD::WIN_FTOL;
9518 switch (DstTy.getSimpleVT().SimpleTy) {
9519 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9520 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9521 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9522 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9525 SDValue Chain = DAG.getEntryNode();
9526 SDValue Value = Op.getOperand(0);
9527 EVT TheVT = Op.getOperand(0).getValueType();
9528 // FIXME This causes a redundant load/store if the SSE-class value is already
9529 // in memory, such as if it is on the callstack.
9530 if (isScalarFPTypeInSSEReg(TheVT)) {
9531 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9532 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9533 MachinePointerInfo::getFixedStack(SSFI),
9535 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9537 Chain, StackSlot, DAG.getValueType(TheVT)
9540 MachineMemOperand *MMO =
9541 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9542 MachineMemOperand::MOLoad, MemSize, MemSize);
9543 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9544 Chain = Value.getValue(1);
9545 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9546 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9549 MachineMemOperand *MMO =
9550 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9551 MachineMemOperand::MOStore, MemSize, MemSize);
9553 if (Opc != X86ISD::WIN_FTOL) {
9554 // Build the FP_TO_INT*_IN_MEM
9555 SDValue Ops[] = { Chain, Value, StackSlot };
9556 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9558 return std::make_pair(FIST, StackSlot);
9560 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9561 DAG.getVTList(MVT::Other, MVT::Glue),
9563 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9564 MVT::i32, ftol.getValue(1));
9565 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9566 MVT::i32, eax.getValue(2));
9567 SDValue Ops[] = { eax, edx };
9568 SDValue pair = IsReplace
9569 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9570 : DAG.getMergeValues(Ops, DL);
9571 return std::make_pair(pair, SDValue());
9575 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9576 const X86Subtarget *Subtarget) {
9577 MVT VT = Op->getSimpleValueType(0);
9578 SDValue In = Op->getOperand(0);
9579 MVT InVT = In.getSimpleValueType();
9582 // Optimize vectors in AVX mode:
9585 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9586 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9587 // Concat upper and lower parts.
9590 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9591 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9592 // Concat upper and lower parts.
9595 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9596 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9597 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9600 if (Subtarget->hasInt256())
9601 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9603 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9604 SDValue Undef = DAG.getUNDEF(InVT);
9605 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9606 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9607 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9609 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9610 VT.getVectorNumElements()/2);
9612 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9613 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9615 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9618 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9619 SelectionDAG &DAG) {
9620 MVT VT = Op->getSimpleValueType(0);
9621 SDValue In = Op->getOperand(0);
9622 MVT InVT = In.getSimpleValueType();
9624 unsigned int NumElts = VT.getVectorNumElements();
9625 if (NumElts != 8 && NumElts != 16)
9628 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9629 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9631 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9632 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9633 // Now we have only mask extension
9634 assert(InVT.getVectorElementType() == MVT::i1);
9635 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9636 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9637 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9638 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9639 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9640 MachinePointerInfo::getConstantPool(),
9641 false, false, false, Alignment);
9643 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9644 if (VT.is512BitVector())
9646 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9649 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9650 SelectionDAG &DAG) {
9651 if (Subtarget->hasFp256()) {
9652 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9660 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9661 SelectionDAG &DAG) {
9663 MVT VT = Op.getSimpleValueType();
9664 SDValue In = Op.getOperand(0);
9665 MVT SVT = In.getSimpleValueType();
9667 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9668 return LowerZERO_EXTEND_AVX512(Op, DAG);
9670 if (Subtarget->hasFp256()) {
9671 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9676 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9677 VT.getVectorNumElements() != SVT.getVectorNumElements());
9681 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9683 MVT VT = Op.getSimpleValueType();
9684 SDValue In = Op.getOperand(0);
9685 MVT InVT = In.getSimpleValueType();
9687 if (VT == MVT::i1) {
9688 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9689 "Invalid scalar TRUNCATE operation");
9690 if (InVT == MVT::i32)
9692 if (InVT.getSizeInBits() == 64)
9693 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9694 else if (InVT.getSizeInBits() < 32)
9695 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9696 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9698 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9699 "Invalid TRUNCATE operation");
9701 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9702 if (VT.getVectorElementType().getSizeInBits() >=8)
9703 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9705 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9706 unsigned NumElts = InVT.getVectorNumElements();
9707 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9708 if (InVT.getSizeInBits() < 512) {
9709 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9710 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9714 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9715 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9716 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9717 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9718 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9719 MachinePointerInfo::getConstantPool(),
9720 false, false, false, Alignment);
9721 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9722 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9723 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9726 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9727 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9728 if (Subtarget->hasInt256()) {
9729 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9730 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9731 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9733 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9734 DAG.getIntPtrConstant(0));
9737 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9738 DAG.getIntPtrConstant(0));
9739 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9740 DAG.getIntPtrConstant(2));
9741 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9742 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9743 static const int ShufMask[] = {0, 2, 4, 6};
9744 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9747 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9748 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9749 if (Subtarget->hasInt256()) {
9750 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9752 SmallVector<SDValue,32> pshufbMask;
9753 for (unsigned i = 0; i < 2; ++i) {
9754 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9755 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9756 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9757 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9758 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9759 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9760 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9761 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9762 for (unsigned j = 0; j < 8; ++j)
9763 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9765 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9766 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9767 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9769 static const int ShufMask[] = {0, 2, -1, -1};
9770 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9772 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9773 DAG.getIntPtrConstant(0));
9774 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9777 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9778 DAG.getIntPtrConstant(0));
9780 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9781 DAG.getIntPtrConstant(4));
9783 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9784 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9787 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9788 -1, -1, -1, -1, -1, -1, -1, -1};
9790 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9791 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9792 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9794 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9795 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9797 // The MOVLHPS Mask:
9798 static const int ShufMask2[] = {0, 1, 4, 5};
9799 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9800 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9803 // Handle truncation of V256 to V128 using shuffles.
9804 if (!VT.is128BitVector() || !InVT.is256BitVector())
9807 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9809 unsigned NumElems = VT.getVectorNumElements();
9810 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9812 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9813 // Prepare truncation shuffle mask
9814 for (unsigned i = 0; i != NumElems; ++i)
9816 SDValue V = DAG.getVectorShuffle(NVT, DL,
9817 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9818 DAG.getUNDEF(NVT), &MaskVec[0]);
9819 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9820 DAG.getIntPtrConstant(0));
9823 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9824 SelectionDAG &DAG) const {
9825 assert(!Op.getSimpleValueType().isVector());
9827 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9828 /*IsSigned=*/ true, /*IsReplace=*/ false);
9829 SDValue FIST = Vals.first, StackSlot = Vals.second;
9830 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9831 if (!FIST.getNode()) return Op;
9833 if (StackSlot.getNode())
9835 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9836 FIST, StackSlot, MachinePointerInfo(),
9837 false, false, false, 0);
9839 // The node is the result.
9843 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9844 SelectionDAG &DAG) const {
9845 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9846 /*IsSigned=*/ false, /*IsReplace=*/ false);
9847 SDValue FIST = Vals.first, StackSlot = Vals.second;
9848 assert(FIST.getNode() && "Unexpected failure");
9850 if (StackSlot.getNode())
9852 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9853 FIST, StackSlot, MachinePointerInfo(),
9854 false, false, false, 0);
9856 // The node is the result.
9860 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9862 MVT VT = Op.getSimpleValueType();
9863 SDValue In = Op.getOperand(0);
9864 MVT SVT = In.getSimpleValueType();
9866 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9868 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9869 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9870 In, DAG.getUNDEF(SVT)));
9873 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9874 LLVMContext *Context = DAG.getContext();
9876 MVT VT = Op.getSimpleValueType();
9878 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9879 if (VT.isVector()) {
9880 EltVT = VT.getVectorElementType();
9881 NumElts = VT.getVectorNumElements();
9884 if (EltVT == MVT::f64)
9885 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9886 APInt(64, ~(1ULL << 63))));
9888 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9889 APInt(32, ~(1U << 31))));
9890 C = ConstantVector::getSplat(NumElts, C);
9891 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9892 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9893 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9894 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9895 MachinePointerInfo::getConstantPool(),
9896 false, false, false, Alignment);
9897 if (VT.isVector()) {
9898 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9899 return DAG.getNode(ISD::BITCAST, dl, VT,
9900 DAG.getNode(ISD::AND, dl, ANDVT,
9901 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9903 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9905 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9908 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9909 LLVMContext *Context = DAG.getContext();
9911 MVT VT = Op.getSimpleValueType();
9913 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9914 if (VT.isVector()) {
9915 EltVT = VT.getVectorElementType();
9916 NumElts = VT.getVectorNumElements();
9919 if (EltVT == MVT::f64)
9920 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9921 APInt(64, 1ULL << 63)));
9923 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9924 APInt(32, 1U << 31)));
9925 C = ConstantVector::getSplat(NumElts, C);
9926 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9927 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9928 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9929 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9930 MachinePointerInfo::getConstantPool(),
9931 false, false, false, Alignment);
9932 if (VT.isVector()) {
9933 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9934 return DAG.getNode(ISD::BITCAST, dl, VT,
9935 DAG.getNode(ISD::XOR, dl, XORVT,
9936 DAG.getNode(ISD::BITCAST, dl, XORVT,
9938 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9941 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9944 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9945 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9946 LLVMContext *Context = DAG.getContext();
9947 SDValue Op0 = Op.getOperand(0);
9948 SDValue Op1 = Op.getOperand(1);
9950 MVT VT = Op.getSimpleValueType();
9951 MVT SrcVT = Op1.getSimpleValueType();
9953 // If second operand is smaller, extend it first.
9954 if (SrcVT.bitsLT(VT)) {
9955 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9958 // And if it is bigger, shrink it first.
9959 if (SrcVT.bitsGT(VT)) {
9960 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9964 // At this point the operands and the result should have the same
9965 // type, and that won't be f80 since that is not custom lowered.
9967 // First get the sign bit of second operand.
9968 SmallVector<Constant*,4> CV;
9969 if (SrcVT == MVT::f64) {
9970 const fltSemantics &Sem = APFloat::IEEEdouble;
9971 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9972 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9974 const fltSemantics &Sem = APFloat::IEEEsingle;
9975 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9976 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9977 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9978 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9980 Constant *C = ConstantVector::get(CV);
9981 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9982 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9983 MachinePointerInfo::getConstantPool(),
9984 false, false, false, 16);
9985 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9987 // Shift sign bit right or left if the two operands have different types.
9988 if (SrcVT.bitsGT(VT)) {
9989 // Op0 is MVT::f32, Op1 is MVT::f64.
9990 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9991 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9992 DAG.getConstant(32, MVT::i32));
9993 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9994 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9995 DAG.getIntPtrConstant(0));
9998 // Clear first operand sign bit.
10000 if (VT == MVT::f64) {
10001 const fltSemantics &Sem = APFloat::IEEEdouble;
10002 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10003 APInt(64, ~(1ULL << 63)))));
10004 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10006 const fltSemantics &Sem = APFloat::IEEEsingle;
10007 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10008 APInt(32, ~(1U << 31)))));
10009 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10010 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10011 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10013 C = ConstantVector::get(CV);
10014 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10015 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10016 MachinePointerInfo::getConstantPool(),
10017 false, false, false, 16);
10018 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10020 // Or the value with the sign bit.
10021 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10024 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10025 SDValue N0 = Op.getOperand(0);
10027 MVT VT = Op.getSimpleValueType();
10029 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10030 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10031 DAG.getConstant(1, VT));
10032 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10035 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10037 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10038 SelectionDAG &DAG) {
10039 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10041 if (!Subtarget->hasSSE41())
10044 if (!Op->hasOneUse())
10047 SDNode *N = Op.getNode();
10050 SmallVector<SDValue, 8> Opnds;
10051 DenseMap<SDValue, unsigned> VecInMap;
10052 SmallVector<SDValue, 8> VecIns;
10053 EVT VT = MVT::Other;
10055 // Recognize a special case where a vector is casted into wide integer to
10057 Opnds.push_back(N->getOperand(0));
10058 Opnds.push_back(N->getOperand(1));
10060 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10061 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10062 // BFS traverse all OR'd operands.
10063 if (I->getOpcode() == ISD::OR) {
10064 Opnds.push_back(I->getOperand(0));
10065 Opnds.push_back(I->getOperand(1));
10066 // Re-evaluate the number of nodes to be traversed.
10067 e += 2; // 2 more nodes (LHS and RHS) are pushed.
10071 // Quit if a non-EXTRACT_VECTOR_ELT
10072 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10075 // Quit if without a constant index.
10076 SDValue Idx = I->getOperand(1);
10077 if (!isa<ConstantSDNode>(Idx))
10080 SDValue ExtractedFromVec = I->getOperand(0);
10081 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10082 if (M == VecInMap.end()) {
10083 VT = ExtractedFromVec.getValueType();
10084 // Quit if not 128/256-bit vector.
10085 if (!VT.is128BitVector() && !VT.is256BitVector())
10087 // Quit if not the same type.
10088 if (VecInMap.begin() != VecInMap.end() &&
10089 VT != VecInMap.begin()->first.getValueType())
10091 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10092 VecIns.push_back(ExtractedFromVec);
10094 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10097 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10098 "Not extracted from 128-/256-bit vector.");
10100 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10102 for (DenseMap<SDValue, unsigned>::const_iterator
10103 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10104 // Quit if not all elements are used.
10105 if (I->second != FullMask)
10109 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10111 // Cast all vectors into TestVT for PTEST.
10112 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10113 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10115 // If more than one full vectors are evaluated, OR them first before PTEST.
10116 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10117 // Each iteration will OR 2 nodes and append the result until there is only
10118 // 1 node left, i.e. the final OR'd value of all vectors.
10119 SDValue LHS = VecIns[Slot];
10120 SDValue RHS = VecIns[Slot + 1];
10121 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10124 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10125 VecIns.back(), VecIns.back());
10128 /// \brief return true if \c Op has a use that doesn't just read flags.
10129 static bool hasNonFlagsUse(SDValue Op) {
10130 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10132 SDNode *User = *UI;
10133 unsigned UOpNo = UI.getOperandNo();
10134 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10135 // Look pass truncate.
10136 UOpNo = User->use_begin().getOperandNo();
10137 User = *User->use_begin();
10140 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10141 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10147 /// Emit nodes that will be selected as "test Op0,Op0", or something
10149 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10150 SelectionDAG &DAG) const {
10151 if (Op.getValueType() == MVT::i1)
10152 // KORTEST instruction should be selected
10153 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10154 DAG.getConstant(0, Op.getValueType()));
10156 // CF and OF aren't always set the way we want. Determine which
10157 // of these we need.
10158 bool NeedCF = false;
10159 bool NeedOF = false;
10162 case X86::COND_A: case X86::COND_AE:
10163 case X86::COND_B: case X86::COND_BE:
10166 case X86::COND_G: case X86::COND_GE:
10167 case X86::COND_L: case X86::COND_LE:
10168 case X86::COND_O: case X86::COND_NO: {
10169 // Check if we really need to set the
10170 // Overflow flag. If NoSignedWrap is present
10171 // that is not actually needed.
10172 switch (Op->getOpcode()) {
10177 const BinaryWithFlagsSDNode *BinNode =
10178 cast<BinaryWithFlagsSDNode>(Op.getNode());
10179 if (BinNode->hasNoSignedWrap())
10189 // See if we can use the EFLAGS value from the operand instead of
10190 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10191 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10192 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10193 // Emit a CMP with 0, which is the TEST pattern.
10194 //if (Op.getValueType() == MVT::i1)
10195 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10196 // DAG.getConstant(0, MVT::i1));
10197 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10198 DAG.getConstant(0, Op.getValueType()));
10200 unsigned Opcode = 0;
10201 unsigned NumOperands = 0;
10203 // Truncate operations may prevent the merge of the SETCC instruction
10204 // and the arithmetic instruction before it. Attempt to truncate the operands
10205 // of the arithmetic instruction and use a reduced bit-width instruction.
10206 bool NeedTruncation = false;
10207 SDValue ArithOp = Op;
10208 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10209 SDValue Arith = Op->getOperand(0);
10210 // Both the trunc and the arithmetic op need to have one user each.
10211 if (Arith->hasOneUse())
10212 switch (Arith.getOpcode()) {
10219 NeedTruncation = true;
10225 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10226 // which may be the result of a CAST. We use the variable 'Op', which is the
10227 // non-casted variable when we check for possible users.
10228 switch (ArithOp.getOpcode()) {
10230 // Due to an isel shortcoming, be conservative if this add is likely to be
10231 // selected as part of a load-modify-store instruction. When the root node
10232 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10233 // uses of other nodes in the match, such as the ADD in this case. This
10234 // leads to the ADD being left around and reselected, with the result being
10235 // two adds in the output. Alas, even if none our users are stores, that
10236 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10237 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10238 // climbing the DAG back to the root, and it doesn't seem to be worth the
10240 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10241 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10242 if (UI->getOpcode() != ISD::CopyToReg &&
10243 UI->getOpcode() != ISD::SETCC &&
10244 UI->getOpcode() != ISD::STORE)
10247 if (ConstantSDNode *C =
10248 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10249 // An add of one will be selected as an INC.
10250 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10251 Opcode = X86ISD::INC;
10256 // An add of negative one (subtract of one) will be selected as a DEC.
10257 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10258 Opcode = X86ISD::DEC;
10264 // Otherwise use a regular EFLAGS-setting add.
10265 Opcode = X86ISD::ADD;
10270 // If we have a constant logical shift that's only used in a comparison
10271 // against zero turn it into an equivalent AND. This allows turning it into
10272 // a TEST instruction later.
10273 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10274 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10275 EVT VT = Op.getValueType();
10276 unsigned BitWidth = VT.getSizeInBits();
10277 unsigned ShAmt = Op->getConstantOperandVal(1);
10278 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10280 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10281 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10282 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10283 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10285 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10286 DAG.getConstant(Mask, VT));
10287 DAG.ReplaceAllUsesWith(Op, New);
10293 // If the primary and result isn't used, don't bother using X86ISD::AND,
10294 // because a TEST instruction will be better.
10295 if (!hasNonFlagsUse(Op))
10301 // Due to the ISEL shortcoming noted above, be conservative if this op is
10302 // likely to be selected as part of a load-modify-store instruction.
10303 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10304 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10305 if (UI->getOpcode() == ISD::STORE)
10308 // Otherwise use a regular EFLAGS-setting instruction.
10309 switch (ArithOp.getOpcode()) {
10310 default: llvm_unreachable("unexpected operator!");
10311 case ISD::SUB: Opcode = X86ISD::SUB; break;
10312 case ISD::XOR: Opcode = X86ISD::XOR; break;
10313 case ISD::AND: Opcode = X86ISD::AND; break;
10315 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10316 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10317 if (EFLAGS.getNode())
10320 Opcode = X86ISD::OR;
10334 return SDValue(Op.getNode(), 1);
10340 // If we found that truncation is beneficial, perform the truncation and
10342 if (NeedTruncation) {
10343 EVT VT = Op.getValueType();
10344 SDValue WideVal = Op->getOperand(0);
10345 EVT WideVT = WideVal.getValueType();
10346 unsigned ConvertedOp = 0;
10347 // Use a target machine opcode to prevent further DAGCombine
10348 // optimizations that may separate the arithmetic operations
10349 // from the setcc node.
10350 switch (WideVal.getOpcode()) {
10352 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10353 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10354 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10355 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10356 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10361 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10362 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10363 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10364 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10370 // Emit a CMP with 0, which is the TEST pattern.
10371 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10372 DAG.getConstant(0, Op.getValueType()));
10374 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10375 SmallVector<SDValue, 4> Ops;
10376 for (unsigned i = 0; i != NumOperands; ++i)
10377 Ops.push_back(Op.getOperand(i));
10379 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10380 DAG.ReplaceAllUsesWith(Op, New);
10381 return SDValue(New.getNode(), 1);
10384 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10386 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10387 SDLoc dl, SelectionDAG &DAG) const {
10388 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10389 if (C->getAPIntValue() == 0)
10390 return EmitTest(Op0, X86CC, dl, DAG);
10392 if (Op0.getValueType() == MVT::i1)
10393 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10396 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10397 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10398 // Do the comparison at i32 if it's smaller, besides the Atom case.
10399 // This avoids subregister aliasing issues. Keep the smaller reference
10400 // if we're optimizing for size, however, as that'll allow better folding
10401 // of memory operations.
10402 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10403 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10404 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10405 !Subtarget->isAtom()) {
10406 unsigned ExtendOp =
10407 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10408 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10409 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10411 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10412 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10413 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10415 return SDValue(Sub.getNode(), 1);
10417 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10420 /// Convert a comparison if required by the subtarget.
10421 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10422 SelectionDAG &DAG) const {
10423 // If the subtarget does not support the FUCOMI instruction, floating-point
10424 // comparisons have to be converted.
10425 if (Subtarget->hasCMov() ||
10426 Cmp.getOpcode() != X86ISD::CMP ||
10427 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10428 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10431 // The instruction selector will select an FUCOM instruction instead of
10432 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10433 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10434 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10436 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10437 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10438 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10439 DAG.getConstant(8, MVT::i8));
10440 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10441 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10444 static bool isAllOnes(SDValue V) {
10445 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10446 return C && C->isAllOnesValue();
10449 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10450 /// if it's possible.
10451 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10452 SDLoc dl, SelectionDAG &DAG) const {
10453 SDValue Op0 = And.getOperand(0);
10454 SDValue Op1 = And.getOperand(1);
10455 if (Op0.getOpcode() == ISD::TRUNCATE)
10456 Op0 = Op0.getOperand(0);
10457 if (Op1.getOpcode() == ISD::TRUNCATE)
10458 Op1 = Op1.getOperand(0);
10461 if (Op1.getOpcode() == ISD::SHL)
10462 std::swap(Op0, Op1);
10463 if (Op0.getOpcode() == ISD::SHL) {
10464 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10465 if (And00C->getZExtValue() == 1) {
10466 // If we looked past a truncate, check that it's only truncating away
10468 unsigned BitWidth = Op0.getValueSizeInBits();
10469 unsigned AndBitWidth = And.getValueSizeInBits();
10470 if (BitWidth > AndBitWidth) {
10472 DAG.computeKnownBits(Op0, Zeros, Ones);
10473 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10477 RHS = Op0.getOperand(1);
10479 } else if (Op1.getOpcode() == ISD::Constant) {
10480 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10481 uint64_t AndRHSVal = AndRHS->getZExtValue();
10482 SDValue AndLHS = Op0;
10484 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10485 LHS = AndLHS.getOperand(0);
10486 RHS = AndLHS.getOperand(1);
10489 // Use BT if the immediate can't be encoded in a TEST instruction.
10490 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10492 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10496 if (LHS.getNode()) {
10497 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10498 // instruction. Since the shift amount is in-range-or-undefined, we know
10499 // that doing a bittest on the i32 value is ok. We extend to i32 because
10500 // the encoding for the i16 version is larger than the i32 version.
10501 // Also promote i16 to i32 for performance / code size reason.
10502 if (LHS.getValueType() == MVT::i8 ||
10503 LHS.getValueType() == MVT::i16)
10504 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10506 // If the operand types disagree, extend the shift amount to match. Since
10507 // BT ignores high bits (like shifts) we can use anyextend.
10508 if (LHS.getValueType() != RHS.getValueType())
10509 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10511 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10512 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10513 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10514 DAG.getConstant(Cond, MVT::i8), BT);
10520 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10522 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10527 // SSE Condition code mapping:
10536 switch (SetCCOpcode) {
10537 default: llvm_unreachable("Unexpected SETCC condition");
10539 case ISD::SETEQ: SSECC = 0; break;
10541 case ISD::SETGT: Swap = true; // Fallthrough
10543 case ISD::SETOLT: SSECC = 1; break;
10545 case ISD::SETGE: Swap = true; // Fallthrough
10547 case ISD::SETOLE: SSECC = 2; break;
10548 case ISD::SETUO: SSECC = 3; break;
10550 case ISD::SETNE: SSECC = 4; break;
10551 case ISD::SETULE: Swap = true; // Fallthrough
10552 case ISD::SETUGE: SSECC = 5; break;
10553 case ISD::SETULT: Swap = true; // Fallthrough
10554 case ISD::SETUGT: SSECC = 6; break;
10555 case ISD::SETO: SSECC = 7; break;
10557 case ISD::SETONE: SSECC = 8; break;
10560 std::swap(Op0, Op1);
10565 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10566 // ones, and then concatenate the result back.
10567 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10568 MVT VT = Op.getSimpleValueType();
10570 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10571 "Unsupported value type for operation");
10573 unsigned NumElems = VT.getVectorNumElements();
10575 SDValue CC = Op.getOperand(2);
10577 // Extract the LHS vectors
10578 SDValue LHS = Op.getOperand(0);
10579 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10580 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10582 // Extract the RHS vectors
10583 SDValue RHS = Op.getOperand(1);
10584 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10585 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10587 // Issue the operation on the smaller types and concatenate the result back
10588 MVT EltVT = VT.getVectorElementType();
10589 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10590 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10591 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10592 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10595 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10596 const X86Subtarget *Subtarget) {
10597 SDValue Op0 = Op.getOperand(0);
10598 SDValue Op1 = Op.getOperand(1);
10599 SDValue CC = Op.getOperand(2);
10600 MVT VT = Op.getSimpleValueType();
10603 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10604 Op.getValueType().getScalarType() == MVT::i1 &&
10605 "Cannot set masked compare for this operation");
10607 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10609 bool Unsigned = false;
10612 switch (SetCCOpcode) {
10613 default: llvm_unreachable("Unexpected SETCC condition");
10614 case ISD::SETNE: SSECC = 4; break;
10615 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10616 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10617 case ISD::SETLT: Swap = true; //fall-through
10618 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10619 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10620 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10621 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10622 case ISD::SETULE: Unsigned = true; //fall-through
10623 case ISD::SETLE: SSECC = 2; break;
10627 std::swap(Op0, Op1);
10629 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10630 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10631 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10632 DAG.getConstant(SSECC, MVT::i8));
10635 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10636 /// operand \p Op1. If non-trivial (for example because it's not constant)
10637 /// return an empty value.
10638 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10640 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10644 MVT VT = Op1.getSimpleValueType();
10645 MVT EVT = VT.getVectorElementType();
10646 unsigned n = VT.getVectorNumElements();
10647 SmallVector<SDValue, 8> ULTOp1;
10649 for (unsigned i = 0; i < n; ++i) {
10650 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10651 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10654 // Avoid underflow.
10655 APInt Val = Elt->getAPIntValue();
10659 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10662 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10665 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10666 SelectionDAG &DAG) {
10667 SDValue Op0 = Op.getOperand(0);
10668 SDValue Op1 = Op.getOperand(1);
10669 SDValue CC = Op.getOperand(2);
10670 MVT VT = Op.getSimpleValueType();
10671 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10672 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10677 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10678 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10681 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10682 unsigned Opc = X86ISD::CMPP;
10683 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10684 assert(VT.getVectorNumElements() <= 16);
10685 Opc = X86ISD::CMPM;
10687 // In the two special cases we can't handle, emit two comparisons.
10690 unsigned CombineOpc;
10691 if (SetCCOpcode == ISD::SETUEQ) {
10692 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10694 assert(SetCCOpcode == ISD::SETONE);
10695 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10698 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10699 DAG.getConstant(CC0, MVT::i8));
10700 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10701 DAG.getConstant(CC1, MVT::i8));
10702 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10704 // Handle all other FP comparisons here.
10705 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10706 DAG.getConstant(SSECC, MVT::i8));
10709 // Break 256-bit integer vector compare into smaller ones.
10710 if (VT.is256BitVector() && !Subtarget->hasInt256())
10711 return Lower256IntVSETCC(Op, DAG);
10713 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10714 EVT OpVT = Op1.getValueType();
10715 if (Subtarget->hasAVX512()) {
10716 if (Op1.getValueType().is512BitVector() ||
10717 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10718 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10720 // In AVX-512 architecture setcc returns mask with i1 elements,
10721 // But there is no compare instruction for i8 and i16 elements.
10722 // We are not talking about 512-bit operands in this case, these
10723 // types are illegal.
10725 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10726 OpVT.getVectorElementType().getSizeInBits() >= 8))
10727 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10728 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10731 // We are handling one of the integer comparisons here. Since SSE only has
10732 // GT and EQ comparisons for integer, swapping operands and multiple
10733 // operations may be required for some comparisons.
10735 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10736 bool Subus = false;
10738 switch (SetCCOpcode) {
10739 default: llvm_unreachable("Unexpected SETCC condition");
10740 case ISD::SETNE: Invert = true;
10741 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10742 case ISD::SETLT: Swap = true;
10743 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10744 case ISD::SETGE: Swap = true;
10745 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10746 Invert = true; break;
10747 case ISD::SETULT: Swap = true;
10748 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10749 FlipSigns = true; break;
10750 case ISD::SETUGE: Swap = true;
10751 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10752 FlipSigns = true; Invert = true; break;
10755 // Special case: Use min/max operations for SETULE/SETUGE
10756 MVT VET = VT.getVectorElementType();
10758 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10759 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10762 switch (SetCCOpcode) {
10764 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10765 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10768 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10771 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10772 if (!MinMax && hasSubus) {
10773 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10775 // t = psubus Op0, Op1
10776 // pcmpeq t, <0..0>
10777 switch (SetCCOpcode) {
10779 case ISD::SETULT: {
10780 // If the comparison is against a constant we can turn this into a
10781 // setule. With psubus, setule does not require a swap. This is
10782 // beneficial because the constant in the register is no longer
10783 // destructed as the destination so it can be hoisted out of a loop.
10784 // Only do this pre-AVX since vpcmp* is no longer destructive.
10785 if (Subtarget->hasAVX())
10787 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10788 if (ULEOp1.getNode()) {
10790 Subus = true; Invert = false; Swap = false;
10794 // Psubus is better than flip-sign because it requires no inversion.
10795 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10796 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10800 Opc = X86ISD::SUBUS;
10806 std::swap(Op0, Op1);
10808 // Check that the operation in question is available (most are plain SSE2,
10809 // but PCMPGTQ and PCMPEQQ have different requirements).
10810 if (VT == MVT::v2i64) {
10811 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10812 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10814 // First cast everything to the right type.
10815 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10816 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10818 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10819 // bits of the inputs before performing those operations. The lower
10820 // compare is always unsigned.
10823 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10825 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10826 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10827 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10828 Sign, Zero, Sign, Zero);
10830 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10831 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10833 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10834 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10835 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10837 // Create masks for only the low parts/high parts of the 64 bit integers.
10838 static const int MaskHi[] = { 1, 1, 3, 3 };
10839 static const int MaskLo[] = { 0, 0, 2, 2 };
10840 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10841 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10842 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10844 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10845 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10848 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10850 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10853 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10854 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10855 // pcmpeqd + pshufd + pand.
10856 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10858 // First cast everything to the right type.
10859 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10860 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10863 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10865 // Make sure the lower and upper halves are both all-ones.
10866 static const int Mask[] = { 1, 0, 3, 2 };
10867 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10868 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10871 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10873 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10877 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10878 // bits of the inputs before performing those operations.
10880 EVT EltVT = VT.getVectorElementType();
10881 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10882 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10883 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10886 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10888 // If the logical-not of the result is required, perform that now.
10890 Result = DAG.getNOT(dl, Result, VT);
10893 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10896 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10897 getZeroVector(VT, Subtarget, DAG, dl));
10902 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10904 MVT VT = Op.getSimpleValueType();
10906 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10908 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10909 && "SetCC type must be 8-bit or 1-bit integer");
10910 SDValue Op0 = Op.getOperand(0);
10911 SDValue Op1 = Op.getOperand(1);
10913 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10915 // Optimize to BT if possible.
10916 // Lower (X & (1 << N)) == 0 to BT(X, N).
10917 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10918 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10919 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10920 Op1.getOpcode() == ISD::Constant &&
10921 cast<ConstantSDNode>(Op1)->isNullValue() &&
10922 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10923 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10924 if (NewSetCC.getNode())
10928 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10930 if (Op1.getOpcode() == ISD::Constant &&
10931 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10932 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10933 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10935 // If the input is a setcc, then reuse the input setcc or use a new one with
10936 // the inverted condition.
10937 if (Op0.getOpcode() == X86ISD::SETCC) {
10938 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10939 bool Invert = (CC == ISD::SETNE) ^
10940 cast<ConstantSDNode>(Op1)->isNullValue();
10944 CCode = X86::GetOppositeBranchCondition(CCode);
10945 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10946 DAG.getConstant(CCode, MVT::i8),
10947 Op0.getOperand(1));
10949 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10953 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10954 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10955 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10957 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10958 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10961 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10962 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10963 if (X86CC == X86::COND_INVALID)
10966 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10967 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10968 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10969 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10971 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10975 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10976 static bool isX86LogicalCmp(SDValue Op) {
10977 unsigned Opc = Op.getNode()->getOpcode();
10978 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10979 Opc == X86ISD::SAHF)
10981 if (Op.getResNo() == 1 &&
10982 (Opc == X86ISD::ADD ||
10983 Opc == X86ISD::SUB ||
10984 Opc == X86ISD::ADC ||
10985 Opc == X86ISD::SBB ||
10986 Opc == X86ISD::SMUL ||
10987 Opc == X86ISD::UMUL ||
10988 Opc == X86ISD::INC ||
10989 Opc == X86ISD::DEC ||
10990 Opc == X86ISD::OR ||
10991 Opc == X86ISD::XOR ||
10992 Opc == X86ISD::AND))
10995 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11001 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11002 if (V.getOpcode() != ISD::TRUNCATE)
11005 SDValue VOp0 = V.getOperand(0);
11006 unsigned InBits = VOp0.getValueSizeInBits();
11007 unsigned Bits = V.getValueSizeInBits();
11008 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11011 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11012 bool addTest = true;
11013 SDValue Cond = Op.getOperand(0);
11014 SDValue Op1 = Op.getOperand(1);
11015 SDValue Op2 = Op.getOperand(2);
11017 EVT VT = Op1.getValueType();
11020 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11021 // are available. Otherwise fp cmovs get lowered into a less efficient branch
11022 // sequence later on.
11023 if (Cond.getOpcode() == ISD::SETCC &&
11024 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11025 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11026 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11027 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11028 int SSECC = translateX86FSETCC(
11029 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11032 if (Subtarget->hasAVX512()) {
11033 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11034 DAG.getConstant(SSECC, MVT::i8));
11035 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11037 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11038 DAG.getConstant(SSECC, MVT::i8));
11039 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11040 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11041 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11045 if (Cond.getOpcode() == ISD::SETCC) {
11046 SDValue NewCond = LowerSETCC(Cond, DAG);
11047 if (NewCond.getNode())
11051 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11052 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11053 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11054 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11055 if (Cond.getOpcode() == X86ISD::SETCC &&
11056 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11057 isZero(Cond.getOperand(1).getOperand(1))) {
11058 SDValue Cmp = Cond.getOperand(1);
11060 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11062 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11063 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11064 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11066 SDValue CmpOp0 = Cmp.getOperand(0);
11067 // Apply further optimizations for special cases
11068 // (select (x != 0), -1, 0) -> neg & sbb
11069 // (select (x == 0), 0, -1) -> neg & sbb
11070 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11071 if (YC->isNullValue() &&
11072 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11073 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11074 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11075 DAG.getConstant(0, CmpOp0.getValueType()),
11077 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11078 DAG.getConstant(X86::COND_B, MVT::i8),
11079 SDValue(Neg.getNode(), 1));
11083 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11084 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11085 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11087 SDValue Res = // Res = 0 or -1.
11088 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11089 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11091 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11092 Res = DAG.getNOT(DL, Res, Res.getValueType());
11094 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11095 if (!N2C || !N2C->isNullValue())
11096 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11101 // Look past (and (setcc_carry (cmp ...)), 1).
11102 if (Cond.getOpcode() == ISD::AND &&
11103 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11104 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11105 if (C && C->getAPIntValue() == 1)
11106 Cond = Cond.getOperand(0);
11109 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11110 // setting operand in place of the X86ISD::SETCC.
11111 unsigned CondOpcode = Cond.getOpcode();
11112 if (CondOpcode == X86ISD::SETCC ||
11113 CondOpcode == X86ISD::SETCC_CARRY) {
11114 CC = Cond.getOperand(0);
11116 SDValue Cmp = Cond.getOperand(1);
11117 unsigned Opc = Cmp.getOpcode();
11118 MVT VT = Op.getSimpleValueType();
11120 bool IllegalFPCMov = false;
11121 if (VT.isFloatingPoint() && !VT.isVector() &&
11122 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11123 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11125 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11126 Opc == X86ISD::BT) { // FIXME
11130 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11131 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11132 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11133 Cond.getOperand(0).getValueType() != MVT::i8)) {
11134 SDValue LHS = Cond.getOperand(0);
11135 SDValue RHS = Cond.getOperand(1);
11136 unsigned X86Opcode;
11139 switch (CondOpcode) {
11140 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11141 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11142 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11143 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11144 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11145 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11146 default: llvm_unreachable("unexpected overflowing operator");
11148 if (CondOpcode == ISD::UMULO)
11149 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11152 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11154 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11156 if (CondOpcode == ISD::UMULO)
11157 Cond = X86Op.getValue(2);
11159 Cond = X86Op.getValue(1);
11161 CC = DAG.getConstant(X86Cond, MVT::i8);
11166 // Look pass the truncate if the high bits are known zero.
11167 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11168 Cond = Cond.getOperand(0);
11170 // We know the result of AND is compared against zero. Try to match
11172 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11173 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11174 if (NewSetCC.getNode()) {
11175 CC = NewSetCC.getOperand(0);
11176 Cond = NewSetCC.getOperand(1);
11183 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11184 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11187 // a < b ? -1 : 0 -> RES = ~setcc_carry
11188 // a < b ? 0 : -1 -> RES = setcc_carry
11189 // a >= b ? -1 : 0 -> RES = setcc_carry
11190 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11191 if (Cond.getOpcode() == X86ISD::SUB) {
11192 Cond = ConvertCmpIfNecessary(Cond, DAG);
11193 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11195 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11196 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11197 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11198 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11199 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11200 return DAG.getNOT(DL, Res, Res.getValueType());
11205 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11206 // widen the cmov and push the truncate through. This avoids introducing a new
11207 // branch during isel and doesn't add any extensions.
11208 if (Op.getValueType() == MVT::i8 &&
11209 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11210 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11211 if (T1.getValueType() == T2.getValueType() &&
11212 // Blacklist CopyFromReg to avoid partial register stalls.
11213 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11214 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11215 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11216 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11220 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11221 // condition is true.
11222 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11223 SDValue Ops[] = { Op2, Op1, CC, Cond };
11224 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11227 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11228 MVT VT = Op->getSimpleValueType(0);
11229 SDValue In = Op->getOperand(0);
11230 MVT InVT = In.getSimpleValueType();
11233 unsigned int NumElts = VT.getVectorNumElements();
11234 if (NumElts != 8 && NumElts != 16)
11237 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11238 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11240 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11241 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11243 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11244 Constant *C = ConstantInt::get(*DAG.getContext(),
11245 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11247 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11248 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11249 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11250 MachinePointerInfo::getConstantPool(),
11251 false, false, false, Alignment);
11252 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11253 if (VT.is512BitVector())
11255 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11258 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11259 SelectionDAG &DAG) {
11260 MVT VT = Op->getSimpleValueType(0);
11261 SDValue In = Op->getOperand(0);
11262 MVT InVT = In.getSimpleValueType();
11265 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11266 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11268 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11269 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11270 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11273 if (Subtarget->hasInt256())
11274 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11276 // Optimize vectors in AVX mode
11277 // Sign extend v8i16 to v8i32 and
11280 // Divide input vector into two parts
11281 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11282 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11283 // concat the vectors to original VT
11285 unsigned NumElems = InVT.getVectorNumElements();
11286 SDValue Undef = DAG.getUNDEF(InVT);
11288 SmallVector<int,8> ShufMask1(NumElems, -1);
11289 for (unsigned i = 0; i != NumElems/2; ++i)
11292 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11294 SmallVector<int,8> ShufMask2(NumElems, -1);
11295 for (unsigned i = 0; i != NumElems/2; ++i)
11296 ShufMask2[i] = i + NumElems/2;
11298 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11300 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11301 VT.getVectorNumElements()/2);
11303 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11304 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11306 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11309 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11310 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11311 // from the AND / OR.
11312 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11313 Opc = Op.getOpcode();
11314 if (Opc != ISD::OR && Opc != ISD::AND)
11316 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11317 Op.getOperand(0).hasOneUse() &&
11318 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11319 Op.getOperand(1).hasOneUse());
11322 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11323 // 1 and that the SETCC node has a single use.
11324 static bool isXor1OfSetCC(SDValue Op) {
11325 if (Op.getOpcode() != ISD::XOR)
11327 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11328 if (N1C && N1C->getAPIntValue() == 1) {
11329 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11330 Op.getOperand(0).hasOneUse();
11335 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11336 bool addTest = true;
11337 SDValue Chain = Op.getOperand(0);
11338 SDValue Cond = Op.getOperand(1);
11339 SDValue Dest = Op.getOperand(2);
11342 bool Inverted = false;
11344 if (Cond.getOpcode() == ISD::SETCC) {
11345 // Check for setcc([su]{add,sub,mul}o == 0).
11346 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11347 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11348 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11349 Cond.getOperand(0).getResNo() == 1 &&
11350 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11351 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11352 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11353 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11354 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11355 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11357 Cond = Cond.getOperand(0);
11359 SDValue NewCond = LowerSETCC(Cond, DAG);
11360 if (NewCond.getNode())
11365 // FIXME: LowerXALUO doesn't handle these!!
11366 else if (Cond.getOpcode() == X86ISD::ADD ||
11367 Cond.getOpcode() == X86ISD::SUB ||
11368 Cond.getOpcode() == X86ISD::SMUL ||
11369 Cond.getOpcode() == X86ISD::UMUL)
11370 Cond = LowerXALUO(Cond, DAG);
11373 // Look pass (and (setcc_carry (cmp ...)), 1).
11374 if (Cond.getOpcode() == ISD::AND &&
11375 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11376 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11377 if (C && C->getAPIntValue() == 1)
11378 Cond = Cond.getOperand(0);
11381 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11382 // setting operand in place of the X86ISD::SETCC.
11383 unsigned CondOpcode = Cond.getOpcode();
11384 if (CondOpcode == X86ISD::SETCC ||
11385 CondOpcode == X86ISD::SETCC_CARRY) {
11386 CC = Cond.getOperand(0);
11388 SDValue Cmp = Cond.getOperand(1);
11389 unsigned Opc = Cmp.getOpcode();
11390 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11391 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11395 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11399 // These can only come from an arithmetic instruction with overflow,
11400 // e.g. SADDO, UADDO.
11401 Cond = Cond.getNode()->getOperand(1);
11407 CondOpcode = Cond.getOpcode();
11408 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11409 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11410 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11411 Cond.getOperand(0).getValueType() != MVT::i8)) {
11412 SDValue LHS = Cond.getOperand(0);
11413 SDValue RHS = Cond.getOperand(1);
11414 unsigned X86Opcode;
11417 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11418 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11420 switch (CondOpcode) {
11421 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11423 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11425 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11428 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11429 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11431 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11433 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11436 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11437 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11438 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11439 default: llvm_unreachable("unexpected overflowing operator");
11442 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11443 if (CondOpcode == ISD::UMULO)
11444 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11447 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11449 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11451 if (CondOpcode == ISD::UMULO)
11452 Cond = X86Op.getValue(2);
11454 Cond = X86Op.getValue(1);
11456 CC = DAG.getConstant(X86Cond, MVT::i8);
11460 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11461 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11462 if (CondOpc == ISD::OR) {
11463 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11464 // two branches instead of an explicit OR instruction with a
11466 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11467 isX86LogicalCmp(Cmp)) {
11468 CC = Cond.getOperand(0).getOperand(0);
11469 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11470 Chain, Dest, CC, Cmp);
11471 CC = Cond.getOperand(1).getOperand(0);
11475 } else { // ISD::AND
11476 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11477 // two branches instead of an explicit AND instruction with a
11478 // separate test. However, we only do this if this block doesn't
11479 // have a fall-through edge, because this requires an explicit
11480 // jmp when the condition is false.
11481 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11482 isX86LogicalCmp(Cmp) &&
11483 Op.getNode()->hasOneUse()) {
11484 X86::CondCode CCode =
11485 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11486 CCode = X86::GetOppositeBranchCondition(CCode);
11487 CC = DAG.getConstant(CCode, MVT::i8);
11488 SDNode *User = *Op.getNode()->use_begin();
11489 // Look for an unconditional branch following this conditional branch.
11490 // We need this because we need to reverse the successors in order
11491 // to implement FCMP_OEQ.
11492 if (User->getOpcode() == ISD::BR) {
11493 SDValue FalseBB = User->getOperand(1);
11495 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11496 assert(NewBR == User);
11500 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11501 Chain, Dest, CC, Cmp);
11502 X86::CondCode CCode =
11503 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11504 CCode = X86::GetOppositeBranchCondition(CCode);
11505 CC = DAG.getConstant(CCode, MVT::i8);
11511 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11512 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11513 // It should be transformed during dag combiner except when the condition
11514 // is set by a arithmetics with overflow node.
11515 X86::CondCode CCode =
11516 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11517 CCode = X86::GetOppositeBranchCondition(CCode);
11518 CC = DAG.getConstant(CCode, MVT::i8);
11519 Cond = Cond.getOperand(0).getOperand(1);
11521 } else if (Cond.getOpcode() == ISD::SETCC &&
11522 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11523 // For FCMP_OEQ, we can emit
11524 // two branches instead of an explicit AND instruction with a
11525 // separate test. However, we only do this if this block doesn't
11526 // have a fall-through edge, because this requires an explicit
11527 // jmp when the condition is false.
11528 if (Op.getNode()->hasOneUse()) {
11529 SDNode *User = *Op.getNode()->use_begin();
11530 // Look for an unconditional branch following this conditional branch.
11531 // We need this because we need to reverse the successors in order
11532 // to implement FCMP_OEQ.
11533 if (User->getOpcode() == ISD::BR) {
11534 SDValue FalseBB = User->getOperand(1);
11536 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11537 assert(NewBR == User);
11541 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11542 Cond.getOperand(0), Cond.getOperand(1));
11543 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11544 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11545 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11546 Chain, Dest, CC, Cmp);
11547 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11552 } else if (Cond.getOpcode() == ISD::SETCC &&
11553 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11554 // For FCMP_UNE, we can emit
11555 // two branches instead of an explicit AND instruction with a
11556 // separate test. However, we only do this if this block doesn't
11557 // have a fall-through edge, because this requires an explicit
11558 // jmp when the condition is false.
11559 if (Op.getNode()->hasOneUse()) {
11560 SDNode *User = *Op.getNode()->use_begin();
11561 // Look for an unconditional branch following this conditional branch.
11562 // We need this because we need to reverse the successors in order
11563 // to implement FCMP_UNE.
11564 if (User->getOpcode() == ISD::BR) {
11565 SDValue FalseBB = User->getOperand(1);
11567 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11568 assert(NewBR == User);
11571 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11572 Cond.getOperand(0), Cond.getOperand(1));
11573 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11574 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11575 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11576 Chain, Dest, CC, Cmp);
11577 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11587 // Look pass the truncate if the high bits are known zero.
11588 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11589 Cond = Cond.getOperand(0);
11591 // We know the result of AND is compared against zero. Try to match
11593 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11594 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11595 if (NewSetCC.getNode()) {
11596 CC = NewSetCC.getOperand(0);
11597 Cond = NewSetCC.getOperand(1);
11604 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11605 CC = DAG.getConstant(X86Cond, MVT::i8);
11606 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11608 Cond = ConvertCmpIfNecessary(Cond, DAG);
11609 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11610 Chain, Dest, CC, Cond);
11613 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11614 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11615 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11616 // that the guard pages used by the OS virtual memory manager are allocated in
11617 // correct sequence.
11619 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11620 SelectionDAG &DAG) const {
11621 MachineFunction &MF = DAG.getMachineFunction();
11622 bool SplitStack = MF.shouldSplitStack();
11623 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11628 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11629 SDNode* Node = Op.getNode();
11631 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11632 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11633 " not tell us which reg is the stack pointer!");
11634 EVT VT = Node->getValueType(0);
11635 SDValue Tmp1 = SDValue(Node, 0);
11636 SDValue Tmp2 = SDValue(Node, 1);
11637 SDValue Tmp3 = Node->getOperand(2);
11638 SDValue Chain = Tmp1.getOperand(0);
11640 // Chain the dynamic stack allocation so that it doesn't modify the stack
11641 // pointer when other instructions are using the stack.
11642 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11645 SDValue Size = Tmp2.getOperand(1);
11646 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11647 Chain = SP.getValue(1);
11648 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11649 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11650 unsigned StackAlign = TFI.getStackAlignment();
11651 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11652 if (Align > StackAlign)
11653 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11654 DAG.getConstant(-(uint64_t)Align, VT));
11655 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11657 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11658 DAG.getIntPtrConstant(0, true), SDValue(),
11661 SDValue Ops[2] = { Tmp1, Tmp2 };
11662 return DAG.getMergeValues(Ops, dl);
11666 SDValue Chain = Op.getOperand(0);
11667 SDValue Size = Op.getOperand(1);
11668 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11669 EVT VT = Op.getNode()->getValueType(0);
11671 bool Is64Bit = Subtarget->is64Bit();
11672 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11675 MachineRegisterInfo &MRI = MF.getRegInfo();
11678 // The 64 bit implementation of segmented stacks needs to clobber both r10
11679 // r11. This makes it impossible to use it along with nested parameters.
11680 const Function *F = MF.getFunction();
11682 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11684 if (I->hasNestAttr())
11685 report_fatal_error("Cannot use segmented stacks with functions that "
11686 "have nested arguments.");
11689 const TargetRegisterClass *AddrRegClass =
11690 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11691 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11692 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11693 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11694 DAG.getRegister(Vreg, SPTy));
11695 SDValue Ops1[2] = { Value, Chain };
11696 return DAG.getMergeValues(Ops1, dl);
11699 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11701 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11702 Flag = Chain.getValue(1);
11703 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11705 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11707 const X86RegisterInfo *RegInfo =
11708 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11709 unsigned SPReg = RegInfo->getStackRegister();
11710 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11711 Chain = SP.getValue(1);
11714 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11715 DAG.getConstant(-(uint64_t)Align, VT));
11716 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11719 SDValue Ops1[2] = { SP, Chain };
11720 return DAG.getMergeValues(Ops1, dl);
11724 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11725 MachineFunction &MF = DAG.getMachineFunction();
11726 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11728 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11731 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11732 // vastart just stores the address of the VarArgsFrameIndex slot into the
11733 // memory location argument.
11734 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11736 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11737 MachinePointerInfo(SV), false, false, 0);
11741 // gp_offset (0 - 6 * 8)
11742 // fp_offset (48 - 48 + 8 * 16)
11743 // overflow_arg_area (point to parameters coming in memory).
11745 SmallVector<SDValue, 8> MemOps;
11746 SDValue FIN = Op.getOperand(1);
11748 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11749 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11751 FIN, MachinePointerInfo(SV), false, false, 0);
11752 MemOps.push_back(Store);
11755 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11756 FIN, DAG.getIntPtrConstant(4));
11757 Store = DAG.getStore(Op.getOperand(0), DL,
11758 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11760 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11761 MemOps.push_back(Store);
11763 // Store ptr to overflow_arg_area
11764 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11765 FIN, DAG.getIntPtrConstant(4));
11766 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11768 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11769 MachinePointerInfo(SV, 8),
11771 MemOps.push_back(Store);
11773 // Store ptr to reg_save_area.
11774 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11775 FIN, DAG.getIntPtrConstant(8));
11776 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11778 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11779 MachinePointerInfo(SV, 16), false, false, 0);
11780 MemOps.push_back(Store);
11781 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11784 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11785 assert(Subtarget->is64Bit() &&
11786 "LowerVAARG only handles 64-bit va_arg!");
11787 assert((Subtarget->isTargetLinux() ||
11788 Subtarget->isTargetDarwin()) &&
11789 "Unhandled target in LowerVAARG");
11790 assert(Op.getNode()->getNumOperands() == 4);
11791 SDValue Chain = Op.getOperand(0);
11792 SDValue SrcPtr = Op.getOperand(1);
11793 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11794 unsigned Align = Op.getConstantOperandVal(3);
11797 EVT ArgVT = Op.getNode()->getValueType(0);
11798 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11799 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11802 // Decide which area this value should be read from.
11803 // TODO: Implement the AMD64 ABI in its entirety. This simple
11804 // selection mechanism works only for the basic types.
11805 if (ArgVT == MVT::f80) {
11806 llvm_unreachable("va_arg for f80 not yet implemented");
11807 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11808 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11809 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11810 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11812 llvm_unreachable("Unhandled argument type in LowerVAARG");
11815 if (ArgMode == 2) {
11816 // Sanity Check: Make sure using fp_offset makes sense.
11817 assert(!getTargetMachine().Options.UseSoftFloat &&
11818 !(DAG.getMachineFunction()
11819 .getFunction()->getAttributes()
11820 .hasAttribute(AttributeSet::FunctionIndex,
11821 Attribute::NoImplicitFloat)) &&
11822 Subtarget->hasSSE1());
11825 // Insert VAARG_64 node into the DAG
11826 // VAARG_64 returns two values: Variable Argument Address, Chain
11827 SmallVector<SDValue, 11> InstOps;
11828 InstOps.push_back(Chain);
11829 InstOps.push_back(SrcPtr);
11830 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11831 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11832 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11833 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11834 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11835 VTs, InstOps, MVT::i64,
11836 MachinePointerInfo(SV),
11838 /*Volatile=*/false,
11840 /*WriteMem=*/true);
11841 Chain = VAARG.getValue(1);
11843 // Load the next argument and return it
11844 return DAG.getLoad(ArgVT, dl,
11847 MachinePointerInfo(),
11848 false, false, false, 0);
11851 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11852 SelectionDAG &DAG) {
11853 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11854 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11855 SDValue Chain = Op.getOperand(0);
11856 SDValue DstPtr = Op.getOperand(1);
11857 SDValue SrcPtr = Op.getOperand(2);
11858 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11859 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11862 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11863 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11865 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11868 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11869 // amount is a constant. Takes immediate version of shift as input.
11870 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11871 SDValue SrcOp, uint64_t ShiftAmt,
11872 SelectionDAG &DAG) {
11873 MVT ElementType = VT.getVectorElementType();
11875 // Fold this packed shift into its first operand if ShiftAmt is 0.
11879 // Check for ShiftAmt >= element width
11880 if (ShiftAmt >= ElementType.getSizeInBits()) {
11881 if (Opc == X86ISD::VSRAI)
11882 ShiftAmt = ElementType.getSizeInBits() - 1;
11884 return DAG.getConstant(0, VT);
11887 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11888 && "Unknown target vector shift-by-constant node");
11890 // Fold this packed vector shift into a build vector if SrcOp is a
11891 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11892 if (VT == SrcOp.getSimpleValueType() &&
11893 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11894 SmallVector<SDValue, 8> Elts;
11895 unsigned NumElts = SrcOp->getNumOperands();
11896 ConstantSDNode *ND;
11899 default: llvm_unreachable(nullptr);
11900 case X86ISD::VSHLI:
11901 for (unsigned i=0; i!=NumElts; ++i) {
11902 SDValue CurrentOp = SrcOp->getOperand(i);
11903 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11904 Elts.push_back(CurrentOp);
11907 ND = cast<ConstantSDNode>(CurrentOp);
11908 const APInt &C = ND->getAPIntValue();
11909 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11912 case X86ISD::VSRLI:
11913 for (unsigned i=0; i!=NumElts; ++i) {
11914 SDValue CurrentOp = SrcOp->getOperand(i);
11915 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11916 Elts.push_back(CurrentOp);
11919 ND = cast<ConstantSDNode>(CurrentOp);
11920 const APInt &C = ND->getAPIntValue();
11921 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11924 case X86ISD::VSRAI:
11925 for (unsigned i=0; i!=NumElts; ++i) {
11926 SDValue CurrentOp = SrcOp->getOperand(i);
11927 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11928 Elts.push_back(CurrentOp);
11931 ND = cast<ConstantSDNode>(CurrentOp);
11932 const APInt &C = ND->getAPIntValue();
11933 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11938 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11941 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11944 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11945 // may or may not be a constant. Takes immediate version of shift as input.
11946 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11947 SDValue SrcOp, SDValue ShAmt,
11948 SelectionDAG &DAG) {
11949 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11951 // Catch shift-by-constant.
11952 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11953 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11954 CShAmt->getZExtValue(), DAG);
11956 // Change opcode to non-immediate version
11958 default: llvm_unreachable("Unknown target vector shift node");
11959 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11960 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11961 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11964 // Need to build a vector containing shift amount
11965 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11968 ShOps[1] = DAG.getConstant(0, MVT::i32);
11969 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11970 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11972 // The return type has to be a 128-bit type with the same element
11973 // type as the input type.
11974 MVT EltVT = VT.getVectorElementType();
11975 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11977 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11978 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11981 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11983 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11985 default: return SDValue(); // Don't custom lower most intrinsics.
11986 // Comparison intrinsics.
11987 case Intrinsic::x86_sse_comieq_ss:
11988 case Intrinsic::x86_sse_comilt_ss:
11989 case Intrinsic::x86_sse_comile_ss:
11990 case Intrinsic::x86_sse_comigt_ss:
11991 case Intrinsic::x86_sse_comige_ss:
11992 case Intrinsic::x86_sse_comineq_ss:
11993 case Intrinsic::x86_sse_ucomieq_ss:
11994 case Intrinsic::x86_sse_ucomilt_ss:
11995 case Intrinsic::x86_sse_ucomile_ss:
11996 case Intrinsic::x86_sse_ucomigt_ss:
11997 case Intrinsic::x86_sse_ucomige_ss:
11998 case Intrinsic::x86_sse_ucomineq_ss:
11999 case Intrinsic::x86_sse2_comieq_sd:
12000 case Intrinsic::x86_sse2_comilt_sd:
12001 case Intrinsic::x86_sse2_comile_sd:
12002 case Intrinsic::x86_sse2_comigt_sd:
12003 case Intrinsic::x86_sse2_comige_sd:
12004 case Intrinsic::x86_sse2_comineq_sd:
12005 case Intrinsic::x86_sse2_ucomieq_sd:
12006 case Intrinsic::x86_sse2_ucomilt_sd:
12007 case Intrinsic::x86_sse2_ucomile_sd:
12008 case Intrinsic::x86_sse2_ucomigt_sd:
12009 case Intrinsic::x86_sse2_ucomige_sd:
12010 case Intrinsic::x86_sse2_ucomineq_sd: {
12014 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12015 case Intrinsic::x86_sse_comieq_ss:
12016 case Intrinsic::x86_sse2_comieq_sd:
12017 Opc = X86ISD::COMI;
12020 case Intrinsic::x86_sse_comilt_ss:
12021 case Intrinsic::x86_sse2_comilt_sd:
12022 Opc = X86ISD::COMI;
12025 case Intrinsic::x86_sse_comile_ss:
12026 case Intrinsic::x86_sse2_comile_sd:
12027 Opc = X86ISD::COMI;
12030 case Intrinsic::x86_sse_comigt_ss:
12031 case Intrinsic::x86_sse2_comigt_sd:
12032 Opc = X86ISD::COMI;
12035 case Intrinsic::x86_sse_comige_ss:
12036 case Intrinsic::x86_sse2_comige_sd:
12037 Opc = X86ISD::COMI;
12040 case Intrinsic::x86_sse_comineq_ss:
12041 case Intrinsic::x86_sse2_comineq_sd:
12042 Opc = X86ISD::COMI;
12045 case Intrinsic::x86_sse_ucomieq_ss:
12046 case Intrinsic::x86_sse2_ucomieq_sd:
12047 Opc = X86ISD::UCOMI;
12050 case Intrinsic::x86_sse_ucomilt_ss:
12051 case Intrinsic::x86_sse2_ucomilt_sd:
12052 Opc = X86ISD::UCOMI;
12055 case Intrinsic::x86_sse_ucomile_ss:
12056 case Intrinsic::x86_sse2_ucomile_sd:
12057 Opc = X86ISD::UCOMI;
12060 case Intrinsic::x86_sse_ucomigt_ss:
12061 case Intrinsic::x86_sse2_ucomigt_sd:
12062 Opc = X86ISD::UCOMI;
12065 case Intrinsic::x86_sse_ucomige_ss:
12066 case Intrinsic::x86_sse2_ucomige_sd:
12067 Opc = X86ISD::UCOMI;
12070 case Intrinsic::x86_sse_ucomineq_ss:
12071 case Intrinsic::x86_sse2_ucomineq_sd:
12072 Opc = X86ISD::UCOMI;
12077 SDValue LHS = Op.getOperand(1);
12078 SDValue RHS = Op.getOperand(2);
12079 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12080 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12081 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12082 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12083 DAG.getConstant(X86CC, MVT::i8), Cond);
12084 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12087 // Arithmetic intrinsics.
12088 case Intrinsic::x86_sse2_pmulu_dq:
12089 case Intrinsic::x86_avx2_pmulu_dq:
12090 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12091 Op.getOperand(1), Op.getOperand(2));
12093 case Intrinsic::x86_sse41_pmuldq:
12094 case Intrinsic::x86_avx2_pmul_dq:
12095 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12096 Op.getOperand(1), Op.getOperand(2));
12098 case Intrinsic::x86_sse2_pmulhu_w:
12099 case Intrinsic::x86_avx2_pmulhu_w:
12100 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12101 Op.getOperand(1), Op.getOperand(2));
12103 case Intrinsic::x86_sse2_pmulh_w:
12104 case Intrinsic::x86_avx2_pmulh_w:
12105 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12106 Op.getOperand(1), Op.getOperand(2));
12108 // SSE2/AVX2 sub with unsigned saturation intrinsics
12109 case Intrinsic::x86_sse2_psubus_b:
12110 case Intrinsic::x86_sse2_psubus_w:
12111 case Intrinsic::x86_avx2_psubus_b:
12112 case Intrinsic::x86_avx2_psubus_w:
12113 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12114 Op.getOperand(1), Op.getOperand(2));
12116 // SSE3/AVX horizontal add/sub intrinsics
12117 case Intrinsic::x86_sse3_hadd_ps:
12118 case Intrinsic::x86_sse3_hadd_pd:
12119 case Intrinsic::x86_avx_hadd_ps_256:
12120 case Intrinsic::x86_avx_hadd_pd_256:
12121 case Intrinsic::x86_sse3_hsub_ps:
12122 case Intrinsic::x86_sse3_hsub_pd:
12123 case Intrinsic::x86_avx_hsub_ps_256:
12124 case Intrinsic::x86_avx_hsub_pd_256:
12125 case Intrinsic::x86_ssse3_phadd_w_128:
12126 case Intrinsic::x86_ssse3_phadd_d_128:
12127 case Intrinsic::x86_avx2_phadd_w:
12128 case Intrinsic::x86_avx2_phadd_d:
12129 case Intrinsic::x86_ssse3_phsub_w_128:
12130 case Intrinsic::x86_ssse3_phsub_d_128:
12131 case Intrinsic::x86_avx2_phsub_w:
12132 case Intrinsic::x86_avx2_phsub_d: {
12135 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12136 case Intrinsic::x86_sse3_hadd_ps:
12137 case Intrinsic::x86_sse3_hadd_pd:
12138 case Intrinsic::x86_avx_hadd_ps_256:
12139 case Intrinsic::x86_avx_hadd_pd_256:
12140 Opcode = X86ISD::FHADD;
12142 case Intrinsic::x86_sse3_hsub_ps:
12143 case Intrinsic::x86_sse3_hsub_pd:
12144 case Intrinsic::x86_avx_hsub_ps_256:
12145 case Intrinsic::x86_avx_hsub_pd_256:
12146 Opcode = X86ISD::FHSUB;
12148 case Intrinsic::x86_ssse3_phadd_w_128:
12149 case Intrinsic::x86_ssse3_phadd_d_128:
12150 case Intrinsic::x86_avx2_phadd_w:
12151 case Intrinsic::x86_avx2_phadd_d:
12152 Opcode = X86ISD::HADD;
12154 case Intrinsic::x86_ssse3_phsub_w_128:
12155 case Intrinsic::x86_ssse3_phsub_d_128:
12156 case Intrinsic::x86_avx2_phsub_w:
12157 case Intrinsic::x86_avx2_phsub_d:
12158 Opcode = X86ISD::HSUB;
12161 return DAG.getNode(Opcode, dl, Op.getValueType(),
12162 Op.getOperand(1), Op.getOperand(2));
12165 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12166 case Intrinsic::x86_sse2_pmaxu_b:
12167 case Intrinsic::x86_sse41_pmaxuw:
12168 case Intrinsic::x86_sse41_pmaxud:
12169 case Intrinsic::x86_avx2_pmaxu_b:
12170 case Intrinsic::x86_avx2_pmaxu_w:
12171 case Intrinsic::x86_avx2_pmaxu_d:
12172 case Intrinsic::x86_sse2_pminu_b:
12173 case Intrinsic::x86_sse41_pminuw:
12174 case Intrinsic::x86_sse41_pminud:
12175 case Intrinsic::x86_avx2_pminu_b:
12176 case Intrinsic::x86_avx2_pminu_w:
12177 case Intrinsic::x86_avx2_pminu_d:
12178 case Intrinsic::x86_sse41_pmaxsb:
12179 case Intrinsic::x86_sse2_pmaxs_w:
12180 case Intrinsic::x86_sse41_pmaxsd:
12181 case Intrinsic::x86_avx2_pmaxs_b:
12182 case Intrinsic::x86_avx2_pmaxs_w:
12183 case Intrinsic::x86_avx2_pmaxs_d:
12184 case Intrinsic::x86_sse41_pminsb:
12185 case Intrinsic::x86_sse2_pmins_w:
12186 case Intrinsic::x86_sse41_pminsd:
12187 case Intrinsic::x86_avx2_pmins_b:
12188 case Intrinsic::x86_avx2_pmins_w:
12189 case Intrinsic::x86_avx2_pmins_d: {
12192 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12193 case Intrinsic::x86_sse2_pmaxu_b:
12194 case Intrinsic::x86_sse41_pmaxuw:
12195 case Intrinsic::x86_sse41_pmaxud:
12196 case Intrinsic::x86_avx2_pmaxu_b:
12197 case Intrinsic::x86_avx2_pmaxu_w:
12198 case Intrinsic::x86_avx2_pmaxu_d:
12199 Opcode = X86ISD::UMAX;
12201 case Intrinsic::x86_sse2_pminu_b:
12202 case Intrinsic::x86_sse41_pminuw:
12203 case Intrinsic::x86_sse41_pminud:
12204 case Intrinsic::x86_avx2_pminu_b:
12205 case Intrinsic::x86_avx2_pminu_w:
12206 case Intrinsic::x86_avx2_pminu_d:
12207 Opcode = X86ISD::UMIN;
12209 case Intrinsic::x86_sse41_pmaxsb:
12210 case Intrinsic::x86_sse2_pmaxs_w:
12211 case Intrinsic::x86_sse41_pmaxsd:
12212 case Intrinsic::x86_avx2_pmaxs_b:
12213 case Intrinsic::x86_avx2_pmaxs_w:
12214 case Intrinsic::x86_avx2_pmaxs_d:
12215 Opcode = X86ISD::SMAX;
12217 case Intrinsic::x86_sse41_pminsb:
12218 case Intrinsic::x86_sse2_pmins_w:
12219 case Intrinsic::x86_sse41_pminsd:
12220 case Intrinsic::x86_avx2_pmins_b:
12221 case Intrinsic::x86_avx2_pmins_w:
12222 case Intrinsic::x86_avx2_pmins_d:
12223 Opcode = X86ISD::SMIN;
12226 return DAG.getNode(Opcode, dl, Op.getValueType(),
12227 Op.getOperand(1), Op.getOperand(2));
12230 // SSE/SSE2/AVX floating point max/min intrinsics.
12231 case Intrinsic::x86_sse_max_ps:
12232 case Intrinsic::x86_sse2_max_pd:
12233 case Intrinsic::x86_avx_max_ps_256:
12234 case Intrinsic::x86_avx_max_pd_256:
12235 case Intrinsic::x86_sse_min_ps:
12236 case Intrinsic::x86_sse2_min_pd:
12237 case Intrinsic::x86_avx_min_ps_256:
12238 case Intrinsic::x86_avx_min_pd_256: {
12241 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12242 case Intrinsic::x86_sse_max_ps:
12243 case Intrinsic::x86_sse2_max_pd:
12244 case Intrinsic::x86_avx_max_ps_256:
12245 case Intrinsic::x86_avx_max_pd_256:
12246 Opcode = X86ISD::FMAX;
12248 case Intrinsic::x86_sse_min_ps:
12249 case Intrinsic::x86_sse2_min_pd:
12250 case Intrinsic::x86_avx_min_ps_256:
12251 case Intrinsic::x86_avx_min_pd_256:
12252 Opcode = X86ISD::FMIN;
12255 return DAG.getNode(Opcode, dl, Op.getValueType(),
12256 Op.getOperand(1), Op.getOperand(2));
12259 // AVX2 variable shift intrinsics
12260 case Intrinsic::x86_avx2_psllv_d:
12261 case Intrinsic::x86_avx2_psllv_q:
12262 case Intrinsic::x86_avx2_psllv_d_256:
12263 case Intrinsic::x86_avx2_psllv_q_256:
12264 case Intrinsic::x86_avx2_psrlv_d:
12265 case Intrinsic::x86_avx2_psrlv_q:
12266 case Intrinsic::x86_avx2_psrlv_d_256:
12267 case Intrinsic::x86_avx2_psrlv_q_256:
12268 case Intrinsic::x86_avx2_psrav_d:
12269 case Intrinsic::x86_avx2_psrav_d_256: {
12272 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12273 case Intrinsic::x86_avx2_psllv_d:
12274 case Intrinsic::x86_avx2_psllv_q:
12275 case Intrinsic::x86_avx2_psllv_d_256:
12276 case Intrinsic::x86_avx2_psllv_q_256:
12279 case Intrinsic::x86_avx2_psrlv_d:
12280 case Intrinsic::x86_avx2_psrlv_q:
12281 case Intrinsic::x86_avx2_psrlv_d_256:
12282 case Intrinsic::x86_avx2_psrlv_q_256:
12285 case Intrinsic::x86_avx2_psrav_d:
12286 case Intrinsic::x86_avx2_psrav_d_256:
12290 return DAG.getNode(Opcode, dl, Op.getValueType(),
12291 Op.getOperand(1), Op.getOperand(2));
12294 case Intrinsic::x86_ssse3_pshuf_b_128:
12295 case Intrinsic::x86_avx2_pshuf_b:
12296 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12297 Op.getOperand(1), Op.getOperand(2));
12299 case Intrinsic::x86_ssse3_psign_b_128:
12300 case Intrinsic::x86_ssse3_psign_w_128:
12301 case Intrinsic::x86_ssse3_psign_d_128:
12302 case Intrinsic::x86_avx2_psign_b:
12303 case Intrinsic::x86_avx2_psign_w:
12304 case Intrinsic::x86_avx2_psign_d:
12305 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12306 Op.getOperand(1), Op.getOperand(2));
12308 case Intrinsic::x86_sse41_insertps:
12309 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12310 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12312 case Intrinsic::x86_avx_vperm2f128_ps_256:
12313 case Intrinsic::x86_avx_vperm2f128_pd_256:
12314 case Intrinsic::x86_avx_vperm2f128_si_256:
12315 case Intrinsic::x86_avx2_vperm2i128:
12316 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12317 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12319 case Intrinsic::x86_avx2_permd:
12320 case Intrinsic::x86_avx2_permps:
12321 // Operands intentionally swapped. Mask is last operand to intrinsic,
12322 // but second operand for node/instruction.
12323 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12324 Op.getOperand(2), Op.getOperand(1));
12326 case Intrinsic::x86_sse_sqrt_ps:
12327 case Intrinsic::x86_sse2_sqrt_pd:
12328 case Intrinsic::x86_avx_sqrt_ps_256:
12329 case Intrinsic::x86_avx_sqrt_pd_256:
12330 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12332 // ptest and testp intrinsics. The intrinsic these come from are designed to
12333 // return an integer value, not just an instruction so lower it to the ptest
12334 // or testp pattern and a setcc for the result.
12335 case Intrinsic::x86_sse41_ptestz:
12336 case Intrinsic::x86_sse41_ptestc:
12337 case Intrinsic::x86_sse41_ptestnzc:
12338 case Intrinsic::x86_avx_ptestz_256:
12339 case Intrinsic::x86_avx_ptestc_256:
12340 case Intrinsic::x86_avx_ptestnzc_256:
12341 case Intrinsic::x86_avx_vtestz_ps:
12342 case Intrinsic::x86_avx_vtestc_ps:
12343 case Intrinsic::x86_avx_vtestnzc_ps:
12344 case Intrinsic::x86_avx_vtestz_pd:
12345 case Intrinsic::x86_avx_vtestc_pd:
12346 case Intrinsic::x86_avx_vtestnzc_pd:
12347 case Intrinsic::x86_avx_vtestz_ps_256:
12348 case Intrinsic::x86_avx_vtestc_ps_256:
12349 case Intrinsic::x86_avx_vtestnzc_ps_256:
12350 case Intrinsic::x86_avx_vtestz_pd_256:
12351 case Intrinsic::x86_avx_vtestc_pd_256:
12352 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12353 bool IsTestPacked = false;
12356 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12357 case Intrinsic::x86_avx_vtestz_ps:
12358 case Intrinsic::x86_avx_vtestz_pd:
12359 case Intrinsic::x86_avx_vtestz_ps_256:
12360 case Intrinsic::x86_avx_vtestz_pd_256:
12361 IsTestPacked = true; // Fallthrough
12362 case Intrinsic::x86_sse41_ptestz:
12363 case Intrinsic::x86_avx_ptestz_256:
12365 X86CC = X86::COND_E;
12367 case Intrinsic::x86_avx_vtestc_ps:
12368 case Intrinsic::x86_avx_vtestc_pd:
12369 case Intrinsic::x86_avx_vtestc_ps_256:
12370 case Intrinsic::x86_avx_vtestc_pd_256:
12371 IsTestPacked = true; // Fallthrough
12372 case Intrinsic::x86_sse41_ptestc:
12373 case Intrinsic::x86_avx_ptestc_256:
12375 X86CC = X86::COND_B;
12377 case Intrinsic::x86_avx_vtestnzc_ps:
12378 case Intrinsic::x86_avx_vtestnzc_pd:
12379 case Intrinsic::x86_avx_vtestnzc_ps_256:
12380 case Intrinsic::x86_avx_vtestnzc_pd_256:
12381 IsTestPacked = true; // Fallthrough
12382 case Intrinsic::x86_sse41_ptestnzc:
12383 case Intrinsic::x86_avx_ptestnzc_256:
12385 X86CC = X86::COND_A;
12389 SDValue LHS = Op.getOperand(1);
12390 SDValue RHS = Op.getOperand(2);
12391 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12392 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12393 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12394 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12395 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12397 case Intrinsic::x86_avx512_kortestz_w:
12398 case Intrinsic::x86_avx512_kortestc_w: {
12399 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12400 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12401 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12402 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12403 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12404 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12405 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12408 // SSE/AVX shift intrinsics
12409 case Intrinsic::x86_sse2_psll_w:
12410 case Intrinsic::x86_sse2_psll_d:
12411 case Intrinsic::x86_sse2_psll_q:
12412 case Intrinsic::x86_avx2_psll_w:
12413 case Intrinsic::x86_avx2_psll_d:
12414 case Intrinsic::x86_avx2_psll_q:
12415 case Intrinsic::x86_sse2_psrl_w:
12416 case Intrinsic::x86_sse2_psrl_d:
12417 case Intrinsic::x86_sse2_psrl_q:
12418 case Intrinsic::x86_avx2_psrl_w:
12419 case Intrinsic::x86_avx2_psrl_d:
12420 case Intrinsic::x86_avx2_psrl_q:
12421 case Intrinsic::x86_sse2_psra_w:
12422 case Intrinsic::x86_sse2_psra_d:
12423 case Intrinsic::x86_avx2_psra_w:
12424 case Intrinsic::x86_avx2_psra_d: {
12427 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12428 case Intrinsic::x86_sse2_psll_w:
12429 case Intrinsic::x86_sse2_psll_d:
12430 case Intrinsic::x86_sse2_psll_q:
12431 case Intrinsic::x86_avx2_psll_w:
12432 case Intrinsic::x86_avx2_psll_d:
12433 case Intrinsic::x86_avx2_psll_q:
12434 Opcode = X86ISD::VSHL;
12436 case Intrinsic::x86_sse2_psrl_w:
12437 case Intrinsic::x86_sse2_psrl_d:
12438 case Intrinsic::x86_sse2_psrl_q:
12439 case Intrinsic::x86_avx2_psrl_w:
12440 case Intrinsic::x86_avx2_psrl_d:
12441 case Intrinsic::x86_avx2_psrl_q:
12442 Opcode = X86ISD::VSRL;
12444 case Intrinsic::x86_sse2_psra_w:
12445 case Intrinsic::x86_sse2_psra_d:
12446 case Intrinsic::x86_avx2_psra_w:
12447 case Intrinsic::x86_avx2_psra_d:
12448 Opcode = X86ISD::VSRA;
12451 return DAG.getNode(Opcode, dl, Op.getValueType(),
12452 Op.getOperand(1), Op.getOperand(2));
12455 // SSE/AVX immediate shift intrinsics
12456 case Intrinsic::x86_sse2_pslli_w:
12457 case Intrinsic::x86_sse2_pslli_d:
12458 case Intrinsic::x86_sse2_pslli_q:
12459 case Intrinsic::x86_avx2_pslli_w:
12460 case Intrinsic::x86_avx2_pslli_d:
12461 case Intrinsic::x86_avx2_pslli_q:
12462 case Intrinsic::x86_sse2_psrli_w:
12463 case Intrinsic::x86_sse2_psrli_d:
12464 case Intrinsic::x86_sse2_psrli_q:
12465 case Intrinsic::x86_avx2_psrli_w:
12466 case Intrinsic::x86_avx2_psrli_d:
12467 case Intrinsic::x86_avx2_psrli_q:
12468 case Intrinsic::x86_sse2_psrai_w:
12469 case Intrinsic::x86_sse2_psrai_d:
12470 case Intrinsic::x86_avx2_psrai_w:
12471 case Intrinsic::x86_avx2_psrai_d: {
12474 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12475 case Intrinsic::x86_sse2_pslli_w:
12476 case Intrinsic::x86_sse2_pslli_d:
12477 case Intrinsic::x86_sse2_pslli_q:
12478 case Intrinsic::x86_avx2_pslli_w:
12479 case Intrinsic::x86_avx2_pslli_d:
12480 case Intrinsic::x86_avx2_pslli_q:
12481 Opcode = X86ISD::VSHLI;
12483 case Intrinsic::x86_sse2_psrli_w:
12484 case Intrinsic::x86_sse2_psrli_d:
12485 case Intrinsic::x86_sse2_psrli_q:
12486 case Intrinsic::x86_avx2_psrli_w:
12487 case Intrinsic::x86_avx2_psrli_d:
12488 case Intrinsic::x86_avx2_psrli_q:
12489 Opcode = X86ISD::VSRLI;
12491 case Intrinsic::x86_sse2_psrai_w:
12492 case Intrinsic::x86_sse2_psrai_d:
12493 case Intrinsic::x86_avx2_psrai_w:
12494 case Intrinsic::x86_avx2_psrai_d:
12495 Opcode = X86ISD::VSRAI;
12498 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12499 Op.getOperand(1), Op.getOperand(2), DAG);
12502 case Intrinsic::x86_sse42_pcmpistria128:
12503 case Intrinsic::x86_sse42_pcmpestria128:
12504 case Intrinsic::x86_sse42_pcmpistric128:
12505 case Intrinsic::x86_sse42_pcmpestric128:
12506 case Intrinsic::x86_sse42_pcmpistrio128:
12507 case Intrinsic::x86_sse42_pcmpestrio128:
12508 case Intrinsic::x86_sse42_pcmpistris128:
12509 case Intrinsic::x86_sse42_pcmpestris128:
12510 case Intrinsic::x86_sse42_pcmpistriz128:
12511 case Intrinsic::x86_sse42_pcmpestriz128: {
12515 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12516 case Intrinsic::x86_sse42_pcmpistria128:
12517 Opcode = X86ISD::PCMPISTRI;
12518 X86CC = X86::COND_A;
12520 case Intrinsic::x86_sse42_pcmpestria128:
12521 Opcode = X86ISD::PCMPESTRI;
12522 X86CC = X86::COND_A;
12524 case Intrinsic::x86_sse42_pcmpistric128:
12525 Opcode = X86ISD::PCMPISTRI;
12526 X86CC = X86::COND_B;
12528 case Intrinsic::x86_sse42_pcmpestric128:
12529 Opcode = X86ISD::PCMPESTRI;
12530 X86CC = X86::COND_B;
12532 case Intrinsic::x86_sse42_pcmpistrio128:
12533 Opcode = X86ISD::PCMPISTRI;
12534 X86CC = X86::COND_O;
12536 case Intrinsic::x86_sse42_pcmpestrio128:
12537 Opcode = X86ISD::PCMPESTRI;
12538 X86CC = X86::COND_O;
12540 case Intrinsic::x86_sse42_pcmpistris128:
12541 Opcode = X86ISD::PCMPISTRI;
12542 X86CC = X86::COND_S;
12544 case Intrinsic::x86_sse42_pcmpestris128:
12545 Opcode = X86ISD::PCMPESTRI;
12546 X86CC = X86::COND_S;
12548 case Intrinsic::x86_sse42_pcmpistriz128:
12549 Opcode = X86ISD::PCMPISTRI;
12550 X86CC = X86::COND_E;
12552 case Intrinsic::x86_sse42_pcmpestriz128:
12553 Opcode = X86ISD::PCMPESTRI;
12554 X86CC = X86::COND_E;
12557 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12558 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12559 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12560 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12561 DAG.getConstant(X86CC, MVT::i8),
12562 SDValue(PCMP.getNode(), 1));
12563 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12566 case Intrinsic::x86_sse42_pcmpistri128:
12567 case Intrinsic::x86_sse42_pcmpestri128: {
12569 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12570 Opcode = X86ISD::PCMPISTRI;
12572 Opcode = X86ISD::PCMPESTRI;
12574 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12575 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12576 return DAG.getNode(Opcode, dl, VTs, NewOps);
12578 case Intrinsic::x86_fma_vfmadd_ps:
12579 case Intrinsic::x86_fma_vfmadd_pd:
12580 case Intrinsic::x86_fma_vfmsub_ps:
12581 case Intrinsic::x86_fma_vfmsub_pd:
12582 case Intrinsic::x86_fma_vfnmadd_ps:
12583 case Intrinsic::x86_fma_vfnmadd_pd:
12584 case Intrinsic::x86_fma_vfnmsub_ps:
12585 case Intrinsic::x86_fma_vfnmsub_pd:
12586 case Intrinsic::x86_fma_vfmaddsub_ps:
12587 case Intrinsic::x86_fma_vfmaddsub_pd:
12588 case Intrinsic::x86_fma_vfmsubadd_ps:
12589 case Intrinsic::x86_fma_vfmsubadd_pd:
12590 case Intrinsic::x86_fma_vfmadd_ps_256:
12591 case Intrinsic::x86_fma_vfmadd_pd_256:
12592 case Intrinsic::x86_fma_vfmsub_ps_256:
12593 case Intrinsic::x86_fma_vfmsub_pd_256:
12594 case Intrinsic::x86_fma_vfnmadd_ps_256:
12595 case Intrinsic::x86_fma_vfnmadd_pd_256:
12596 case Intrinsic::x86_fma_vfnmsub_ps_256:
12597 case Intrinsic::x86_fma_vfnmsub_pd_256:
12598 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12599 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12600 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12601 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12602 case Intrinsic::x86_fma_vfmadd_ps_512:
12603 case Intrinsic::x86_fma_vfmadd_pd_512:
12604 case Intrinsic::x86_fma_vfmsub_ps_512:
12605 case Intrinsic::x86_fma_vfmsub_pd_512:
12606 case Intrinsic::x86_fma_vfnmadd_ps_512:
12607 case Intrinsic::x86_fma_vfnmadd_pd_512:
12608 case Intrinsic::x86_fma_vfnmsub_ps_512:
12609 case Intrinsic::x86_fma_vfnmsub_pd_512:
12610 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12611 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12612 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12613 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12616 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12617 case Intrinsic::x86_fma_vfmadd_ps:
12618 case Intrinsic::x86_fma_vfmadd_pd:
12619 case Intrinsic::x86_fma_vfmadd_ps_256:
12620 case Intrinsic::x86_fma_vfmadd_pd_256:
12621 case Intrinsic::x86_fma_vfmadd_ps_512:
12622 case Intrinsic::x86_fma_vfmadd_pd_512:
12623 Opc = X86ISD::FMADD;
12625 case Intrinsic::x86_fma_vfmsub_ps:
12626 case Intrinsic::x86_fma_vfmsub_pd:
12627 case Intrinsic::x86_fma_vfmsub_ps_256:
12628 case Intrinsic::x86_fma_vfmsub_pd_256:
12629 case Intrinsic::x86_fma_vfmsub_ps_512:
12630 case Intrinsic::x86_fma_vfmsub_pd_512:
12631 Opc = X86ISD::FMSUB;
12633 case Intrinsic::x86_fma_vfnmadd_ps:
12634 case Intrinsic::x86_fma_vfnmadd_pd:
12635 case Intrinsic::x86_fma_vfnmadd_ps_256:
12636 case Intrinsic::x86_fma_vfnmadd_pd_256:
12637 case Intrinsic::x86_fma_vfnmadd_ps_512:
12638 case Intrinsic::x86_fma_vfnmadd_pd_512:
12639 Opc = X86ISD::FNMADD;
12641 case Intrinsic::x86_fma_vfnmsub_ps:
12642 case Intrinsic::x86_fma_vfnmsub_pd:
12643 case Intrinsic::x86_fma_vfnmsub_ps_256:
12644 case Intrinsic::x86_fma_vfnmsub_pd_256:
12645 case Intrinsic::x86_fma_vfnmsub_ps_512:
12646 case Intrinsic::x86_fma_vfnmsub_pd_512:
12647 Opc = X86ISD::FNMSUB;
12649 case Intrinsic::x86_fma_vfmaddsub_ps:
12650 case Intrinsic::x86_fma_vfmaddsub_pd:
12651 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12652 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12653 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12654 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12655 Opc = X86ISD::FMADDSUB;
12657 case Intrinsic::x86_fma_vfmsubadd_ps:
12658 case Intrinsic::x86_fma_vfmsubadd_pd:
12659 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12660 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12661 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12662 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12663 Opc = X86ISD::FMSUBADD;
12667 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12668 Op.getOperand(2), Op.getOperand(3));
12673 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12674 SDValue Src, SDValue Mask, SDValue Base,
12675 SDValue Index, SDValue ScaleOp, SDValue Chain,
12676 const X86Subtarget * Subtarget) {
12678 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12679 assert(C && "Invalid scale type");
12680 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12681 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12682 Index.getSimpleValueType().getVectorNumElements());
12684 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12686 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12688 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12689 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12690 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12691 SDValue Segment = DAG.getRegister(0, MVT::i32);
12692 if (Src.getOpcode() == ISD::UNDEF)
12693 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12694 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12695 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12696 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12697 return DAG.getMergeValues(RetOps, dl);
12700 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12701 SDValue Src, SDValue Mask, SDValue Base,
12702 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12704 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12705 assert(C && "Invalid scale type");
12706 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12707 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12708 SDValue Segment = DAG.getRegister(0, MVT::i32);
12709 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12710 Index.getSimpleValueType().getVectorNumElements());
12712 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12714 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12716 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12717 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12718 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12719 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12720 return SDValue(Res, 1);
12723 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12724 SDValue Mask, SDValue Base, SDValue Index,
12725 SDValue ScaleOp, SDValue Chain) {
12727 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12728 assert(C && "Invalid scale type");
12729 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12730 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12731 SDValue Segment = DAG.getRegister(0, MVT::i32);
12733 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12735 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12737 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12739 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12740 //SDVTList VTs = DAG.getVTList(MVT::Other);
12741 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12742 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12743 return SDValue(Res, 0);
12746 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12747 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12748 // also used to custom lower READCYCLECOUNTER nodes.
12749 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12750 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12751 SmallVectorImpl<SDValue> &Results) {
12752 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12753 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12756 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12757 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12758 // and the EAX register is loaded with the low-order 32 bits.
12759 if (Subtarget->is64Bit()) {
12760 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12761 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12764 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12765 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12768 SDValue Chain = HI.getValue(1);
12770 if (Opcode == X86ISD::RDTSCP_DAG) {
12771 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12773 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12774 // the ECX register. Add 'ecx' explicitly to the chain.
12775 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12777 // Explicitly store the content of ECX at the location passed in input
12778 // to the 'rdtscp' intrinsic.
12779 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12780 MachinePointerInfo(), false, false, 0);
12783 if (Subtarget->is64Bit()) {
12784 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12785 // the EAX register is loaded with the low-order 32 bits.
12786 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12787 DAG.getConstant(32, MVT::i8));
12788 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12789 Results.push_back(Chain);
12793 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12794 SDValue Ops[] = { LO, HI };
12795 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12796 Results.push_back(Pair);
12797 Results.push_back(Chain);
12800 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12801 SelectionDAG &DAG) {
12802 SmallVector<SDValue, 2> Results;
12804 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12806 return DAG.getMergeValues(Results, DL);
12809 enum IntrinsicType {
12810 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12813 struct IntrinsicData {
12814 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12815 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12816 IntrinsicType Type;
12821 std::map < unsigned, IntrinsicData> IntrMap;
12822 static void InitIntinsicsMap() {
12823 static bool Initialized = false;
12826 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12827 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12828 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12829 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12830 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12831 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12832 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12833 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12834 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12835 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12836 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
12837 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12838 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
12839 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12840 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
12841 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12842 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
12843 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12845 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12846 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12847 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
12848 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12849 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
12850 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12851 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
12852 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12853 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
12854 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12855 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
12856 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12857 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
12858 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12859 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
12860 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12862 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
12863 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12864 X86::VGATHERPF1QPSm)));
12865 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
12866 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12867 X86::VGATHERPF1QPDm)));
12868 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
12869 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12870 X86::VGATHERPF1DPDm)));
12871 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
12872 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12873 X86::VGATHERPF1DPSm)));
12874 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
12875 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12876 X86::VSCATTERPF1QPSm)));
12877 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
12878 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12879 X86::VSCATTERPF1QPDm)));
12880 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
12881 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12882 X86::VSCATTERPF1DPDm)));
12883 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
12884 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12885 X86::VSCATTERPF1DPSm)));
12886 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12887 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12888 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12889 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12890 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12891 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12892 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12893 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12894 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12895 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12896 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12897 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12898 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12899 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
12900 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12901 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
12902 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12903 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
12904 Initialized = true;
12907 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12908 SelectionDAG &DAG) {
12909 InitIntinsicsMap();
12910 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12911 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12912 if (itr == IntrMap.end())
12916 IntrinsicData Intr = itr->second;
12917 switch(Intr.Type) {
12920 // Emit the node with the right value type.
12921 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12922 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12924 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12925 // Otherwise return the value from Rand, which is always 0, casted to i32.
12926 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12927 DAG.getConstant(1, Op->getValueType(1)),
12928 DAG.getConstant(X86::COND_B, MVT::i32),
12929 SDValue(Result.getNode(), 1) };
12930 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12931 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12934 // Return { result, isValid, chain }.
12935 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12936 SDValue(Result.getNode(), 2));
12939 //gather(v1, mask, index, base, scale);
12940 SDValue Chain = Op.getOperand(0);
12941 SDValue Src = Op.getOperand(2);
12942 SDValue Base = Op.getOperand(3);
12943 SDValue Index = Op.getOperand(4);
12944 SDValue Mask = Op.getOperand(5);
12945 SDValue Scale = Op.getOperand(6);
12946 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12950 //scatter(base, mask, index, v1, scale);
12951 SDValue Chain = Op.getOperand(0);
12952 SDValue Base = Op.getOperand(2);
12953 SDValue Mask = Op.getOperand(3);
12954 SDValue Index = Op.getOperand(4);
12955 SDValue Src = Op.getOperand(5);
12956 SDValue Scale = Op.getOperand(6);
12957 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12960 SDValue Hint = Op.getOperand(6);
12962 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
12963 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12964 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12965 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12966 SDValue Chain = Op.getOperand(0);
12967 SDValue Mask = Op.getOperand(2);
12968 SDValue Index = Op.getOperand(3);
12969 SDValue Base = Op.getOperand(4);
12970 SDValue Scale = Op.getOperand(5);
12971 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12973 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12975 SmallVector<SDValue, 2> Results;
12976 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12977 return DAG.getMergeValues(Results, dl);
12979 // XTEST intrinsics.
12981 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12982 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12983 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12984 DAG.getConstant(X86::COND_NE, MVT::i8),
12986 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12987 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12988 Ret, SDValue(InTrans.getNode(), 1));
12991 llvm_unreachable("Unknown Intrinsic Type");
12994 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12995 SelectionDAG &DAG) const {
12996 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12997 MFI->setReturnAddressIsTaken(true);
12999 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13002 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13004 EVT PtrVT = getPointerTy();
13007 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13008 const X86RegisterInfo *RegInfo =
13009 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13010 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13011 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13012 DAG.getNode(ISD::ADD, dl, PtrVT,
13013 FrameAddr, Offset),
13014 MachinePointerInfo(), false, false, false, 0);
13017 // Just load the return address.
13018 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13019 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13020 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13023 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13024 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13025 MFI->setFrameAddressIsTaken(true);
13027 EVT VT = Op.getValueType();
13028 SDLoc dl(Op); // FIXME probably not meaningful
13029 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13030 const X86RegisterInfo *RegInfo =
13031 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13032 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13033 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13034 (FrameReg == X86::EBP && VT == MVT::i32)) &&
13035 "Invalid Frame Register!");
13036 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13038 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13039 MachinePointerInfo(),
13040 false, false, false, 0);
13044 // FIXME? Maybe this could be a TableGen attribute on some registers and
13045 // this table could be generated automatically from RegInfo.
13046 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13048 unsigned Reg = StringSwitch<unsigned>(RegName)
13049 .Case("esp", X86::ESP)
13050 .Case("rsp", X86::RSP)
13054 report_fatal_error("Invalid register name global variable");
13057 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13058 SelectionDAG &DAG) const {
13059 const X86RegisterInfo *RegInfo =
13060 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13061 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13064 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13065 SDValue Chain = Op.getOperand(0);
13066 SDValue Offset = Op.getOperand(1);
13067 SDValue Handler = Op.getOperand(2);
13070 EVT PtrVT = getPointerTy();
13071 const X86RegisterInfo *RegInfo =
13072 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13073 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13074 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13075 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13076 "Invalid Frame Register!");
13077 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13078 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13080 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13081 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13082 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13083 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13085 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13087 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13088 DAG.getRegister(StoreAddrReg, PtrVT));
13091 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13092 SelectionDAG &DAG) const {
13094 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13095 DAG.getVTList(MVT::i32, MVT::Other),
13096 Op.getOperand(0), Op.getOperand(1));
13099 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13100 SelectionDAG &DAG) const {
13102 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13103 Op.getOperand(0), Op.getOperand(1));
13106 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13107 return Op.getOperand(0);
13110 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13111 SelectionDAG &DAG) const {
13112 SDValue Root = Op.getOperand(0);
13113 SDValue Trmp = Op.getOperand(1); // trampoline
13114 SDValue FPtr = Op.getOperand(2); // nested function
13115 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13118 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13119 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13121 if (Subtarget->is64Bit()) {
13122 SDValue OutChains[6];
13124 // Large code-model.
13125 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13126 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13128 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13129 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13131 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13133 // Load the pointer to the nested function into R11.
13134 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13135 SDValue Addr = Trmp;
13136 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13137 Addr, MachinePointerInfo(TrmpAddr),
13140 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13141 DAG.getConstant(2, MVT::i64));
13142 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13143 MachinePointerInfo(TrmpAddr, 2),
13146 // Load the 'nest' parameter value into R10.
13147 // R10 is specified in X86CallingConv.td
13148 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13149 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13150 DAG.getConstant(10, MVT::i64));
13151 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13152 Addr, MachinePointerInfo(TrmpAddr, 10),
13155 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13156 DAG.getConstant(12, MVT::i64));
13157 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13158 MachinePointerInfo(TrmpAddr, 12),
13161 // Jump to the nested function.
13162 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13163 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13164 DAG.getConstant(20, MVT::i64));
13165 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13166 Addr, MachinePointerInfo(TrmpAddr, 20),
13169 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13170 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13171 DAG.getConstant(22, MVT::i64));
13172 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13173 MachinePointerInfo(TrmpAddr, 22),
13176 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13178 const Function *Func =
13179 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13180 CallingConv::ID CC = Func->getCallingConv();
13185 llvm_unreachable("Unsupported calling convention");
13186 case CallingConv::C:
13187 case CallingConv::X86_StdCall: {
13188 // Pass 'nest' parameter in ECX.
13189 // Must be kept in sync with X86CallingConv.td
13190 NestReg = X86::ECX;
13192 // Check that ECX wasn't needed by an 'inreg' parameter.
13193 FunctionType *FTy = Func->getFunctionType();
13194 const AttributeSet &Attrs = Func->getAttributes();
13196 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13197 unsigned InRegCount = 0;
13200 for (FunctionType::param_iterator I = FTy->param_begin(),
13201 E = FTy->param_end(); I != E; ++I, ++Idx)
13202 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13203 // FIXME: should only count parameters that are lowered to integers.
13204 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13206 if (InRegCount > 2) {
13207 report_fatal_error("Nest register in use - reduce number of inreg"
13213 case CallingConv::X86_FastCall:
13214 case CallingConv::X86_ThisCall:
13215 case CallingConv::Fast:
13216 // Pass 'nest' parameter in EAX.
13217 // Must be kept in sync with X86CallingConv.td
13218 NestReg = X86::EAX;
13222 SDValue OutChains[4];
13223 SDValue Addr, Disp;
13225 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13226 DAG.getConstant(10, MVT::i32));
13227 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13229 // This is storing the opcode for MOV32ri.
13230 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13231 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13232 OutChains[0] = DAG.getStore(Root, dl,
13233 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13234 Trmp, MachinePointerInfo(TrmpAddr),
13237 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13238 DAG.getConstant(1, MVT::i32));
13239 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13240 MachinePointerInfo(TrmpAddr, 1),
13243 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13244 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13245 DAG.getConstant(5, MVT::i32));
13246 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13247 MachinePointerInfo(TrmpAddr, 5),
13250 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13251 DAG.getConstant(6, MVT::i32));
13252 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13253 MachinePointerInfo(TrmpAddr, 6),
13256 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13260 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13261 SelectionDAG &DAG) const {
13263 The rounding mode is in bits 11:10 of FPSR, and has the following
13265 00 Round to nearest
13270 FLT_ROUNDS, on the other hand, expects the following:
13277 To perform the conversion, we do:
13278 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13281 MachineFunction &MF = DAG.getMachineFunction();
13282 const TargetMachine &TM = MF.getTarget();
13283 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13284 unsigned StackAlignment = TFI.getStackAlignment();
13285 MVT VT = Op.getSimpleValueType();
13288 // Save FP Control Word to stack slot
13289 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13290 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13292 MachineMemOperand *MMO =
13293 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13294 MachineMemOperand::MOStore, 2, 2);
13296 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13297 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13298 DAG.getVTList(MVT::Other),
13299 Ops, MVT::i16, MMO);
13301 // Load FP Control Word from stack slot
13302 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13303 MachinePointerInfo(), false, false, false, 0);
13305 // Transform as necessary
13307 DAG.getNode(ISD::SRL, DL, MVT::i16,
13308 DAG.getNode(ISD::AND, DL, MVT::i16,
13309 CWD, DAG.getConstant(0x800, MVT::i16)),
13310 DAG.getConstant(11, MVT::i8));
13312 DAG.getNode(ISD::SRL, DL, MVT::i16,
13313 DAG.getNode(ISD::AND, DL, MVT::i16,
13314 CWD, DAG.getConstant(0x400, MVT::i16)),
13315 DAG.getConstant(9, MVT::i8));
13318 DAG.getNode(ISD::AND, DL, MVT::i16,
13319 DAG.getNode(ISD::ADD, DL, MVT::i16,
13320 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13321 DAG.getConstant(1, MVT::i16)),
13322 DAG.getConstant(3, MVT::i16));
13324 return DAG.getNode((VT.getSizeInBits() < 16 ?
13325 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13328 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13329 MVT VT = Op.getSimpleValueType();
13331 unsigned NumBits = VT.getSizeInBits();
13334 Op = Op.getOperand(0);
13335 if (VT == MVT::i8) {
13336 // Zero extend to i32 since there is not an i8 bsr.
13338 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13341 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13342 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13343 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13345 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13348 DAG.getConstant(NumBits+NumBits-1, OpVT),
13349 DAG.getConstant(X86::COND_E, MVT::i8),
13352 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13354 // Finally xor with NumBits-1.
13355 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13358 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13362 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13363 MVT VT = Op.getSimpleValueType();
13365 unsigned NumBits = VT.getSizeInBits();
13368 Op = Op.getOperand(0);
13369 if (VT == MVT::i8) {
13370 // Zero extend to i32 since there is not an i8 bsr.
13372 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13375 // Issue a bsr (scan bits in reverse).
13376 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13377 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13379 // And xor with NumBits-1.
13380 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13383 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13387 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13388 MVT VT = Op.getSimpleValueType();
13389 unsigned NumBits = VT.getSizeInBits();
13391 Op = Op.getOperand(0);
13393 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13394 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13395 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13397 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13400 DAG.getConstant(NumBits, VT),
13401 DAG.getConstant(X86::COND_E, MVT::i8),
13404 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13407 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13408 // ones, and then concatenate the result back.
13409 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13410 MVT VT = Op.getSimpleValueType();
13412 assert(VT.is256BitVector() && VT.isInteger() &&
13413 "Unsupported value type for operation");
13415 unsigned NumElems = VT.getVectorNumElements();
13418 // Extract the LHS vectors
13419 SDValue LHS = Op.getOperand(0);
13420 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13421 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13423 // Extract the RHS vectors
13424 SDValue RHS = Op.getOperand(1);
13425 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13426 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13428 MVT EltVT = VT.getVectorElementType();
13429 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13431 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13432 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13433 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13436 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13437 assert(Op.getSimpleValueType().is256BitVector() &&
13438 Op.getSimpleValueType().isInteger() &&
13439 "Only handle AVX 256-bit vector integer operation");
13440 return Lower256IntArith(Op, DAG);
13443 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13444 assert(Op.getSimpleValueType().is256BitVector() &&
13445 Op.getSimpleValueType().isInteger() &&
13446 "Only handle AVX 256-bit vector integer operation");
13447 return Lower256IntArith(Op, DAG);
13450 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13451 SelectionDAG &DAG) {
13453 MVT VT = Op.getSimpleValueType();
13455 // Decompose 256-bit ops into smaller 128-bit ops.
13456 if (VT.is256BitVector() && !Subtarget->hasInt256())
13457 return Lower256IntArith(Op, DAG);
13459 SDValue A = Op.getOperand(0);
13460 SDValue B = Op.getOperand(1);
13462 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13463 if (VT == MVT::v4i32) {
13464 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13465 "Should not custom lower when pmuldq is available!");
13467 // Extract the odd parts.
13468 static const int UnpackMask[] = { 1, -1, 3, -1 };
13469 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13470 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13472 // Multiply the even parts.
13473 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13474 // Now multiply odd parts.
13475 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13477 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13478 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13480 // Merge the two vectors back together with a shuffle. This expands into 2
13482 static const int ShufMask[] = { 0, 4, 2, 6 };
13483 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13486 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13487 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13489 // Ahi = psrlqi(a, 32);
13490 // Bhi = psrlqi(b, 32);
13492 // AloBlo = pmuludq(a, b);
13493 // AloBhi = pmuludq(a, Bhi);
13494 // AhiBlo = pmuludq(Ahi, b);
13496 // AloBhi = psllqi(AloBhi, 32);
13497 // AhiBlo = psllqi(AhiBlo, 32);
13498 // return AloBlo + AloBhi + AhiBlo;
13500 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13501 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13503 // Bit cast to 32-bit vectors for MULUDQ
13504 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13505 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13506 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13507 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13508 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13509 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13511 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13512 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13513 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13515 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13516 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13518 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13519 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13522 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13523 assert(Subtarget->isTargetWin64() && "Unexpected target");
13524 EVT VT = Op.getValueType();
13525 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13526 "Unexpected return type for lowering");
13530 switch (Op->getOpcode()) {
13531 default: llvm_unreachable("Unexpected request for libcall!");
13532 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13533 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13534 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13535 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13536 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13537 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13541 SDValue InChain = DAG.getEntryNode();
13543 TargetLowering::ArgListTy Args;
13544 TargetLowering::ArgListEntry Entry;
13545 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13546 EVT ArgVT = Op->getOperand(i).getValueType();
13547 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13548 "Unexpected argument type for lowering");
13549 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13550 Entry.Node = StackPtr;
13551 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13553 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13554 Entry.Ty = PointerType::get(ArgTy,0);
13555 Entry.isSExt = false;
13556 Entry.isZExt = false;
13557 Args.push_back(Entry);
13560 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13563 TargetLowering::CallLoweringInfo CLI(DAG);
13564 CLI.setDebugLoc(dl).setChain(InChain)
13565 .setCallee(getLibcallCallingConv(LC),
13566 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13568 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13570 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13571 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13574 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13575 SelectionDAG &DAG) {
13576 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13577 EVT VT = Op0.getValueType();
13580 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13581 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13583 // Get the high parts.
13584 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13585 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13586 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13588 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13590 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13591 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13593 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13594 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13595 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13596 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13597 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13599 // Shuffle it back into the right order.
13600 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13601 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13602 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13603 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13605 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13606 // unsigned multiply.
13607 if (IsSigned && !Subtarget->hasSSE41()) {
13609 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13610 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13611 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13612 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13613 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13615 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13616 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13619 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13622 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13623 const X86Subtarget *Subtarget) {
13624 MVT VT = Op.getSimpleValueType();
13626 SDValue R = Op.getOperand(0);
13627 SDValue Amt = Op.getOperand(1);
13629 // Optimize shl/srl/sra with constant shift amount.
13630 if (isSplatVector(Amt.getNode())) {
13631 SDValue SclrAmt = Amt->getOperand(0);
13632 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13633 uint64_t ShiftAmt = C->getZExtValue();
13635 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13636 (Subtarget->hasInt256() &&
13637 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13638 (Subtarget->hasAVX512() &&
13639 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13640 if (Op.getOpcode() == ISD::SHL)
13641 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13643 if (Op.getOpcode() == ISD::SRL)
13644 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13646 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13647 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13651 if (VT == MVT::v16i8) {
13652 if (Op.getOpcode() == ISD::SHL) {
13653 // Make a large shift.
13654 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13655 MVT::v8i16, R, ShiftAmt,
13657 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13658 // Zero out the rightmost bits.
13659 SmallVector<SDValue, 16> V(16,
13660 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13662 return DAG.getNode(ISD::AND, dl, VT, SHL,
13663 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13665 if (Op.getOpcode() == ISD::SRL) {
13666 // Make a large shift.
13667 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13668 MVT::v8i16, R, ShiftAmt,
13670 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13671 // Zero out the leftmost bits.
13672 SmallVector<SDValue, 16> V(16,
13673 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13675 return DAG.getNode(ISD::AND, dl, VT, SRL,
13676 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13678 if (Op.getOpcode() == ISD::SRA) {
13679 if (ShiftAmt == 7) {
13680 // R s>> 7 === R s< 0
13681 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13682 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13685 // R s>> a === ((R u>> a) ^ m) - m
13686 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13687 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13689 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13690 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13691 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13694 llvm_unreachable("Unknown shift opcode.");
13697 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13698 if (Op.getOpcode() == ISD::SHL) {
13699 // Make a large shift.
13700 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13701 MVT::v16i16, R, ShiftAmt,
13703 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13704 // Zero out the rightmost bits.
13705 SmallVector<SDValue, 32> V(32,
13706 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13708 return DAG.getNode(ISD::AND, dl, VT, SHL,
13709 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13711 if (Op.getOpcode() == ISD::SRL) {
13712 // Make a large shift.
13713 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13714 MVT::v16i16, R, ShiftAmt,
13716 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13717 // Zero out the leftmost bits.
13718 SmallVector<SDValue, 32> V(32,
13719 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13721 return DAG.getNode(ISD::AND, dl, VT, SRL,
13722 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13724 if (Op.getOpcode() == ISD::SRA) {
13725 if (ShiftAmt == 7) {
13726 // R s>> 7 === R s< 0
13727 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13728 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13731 // R s>> a === ((R u>> a) ^ m) - m
13732 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13733 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13735 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13736 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13737 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13740 llvm_unreachable("Unknown shift opcode.");
13745 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13746 if (!Subtarget->is64Bit() &&
13747 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13748 Amt.getOpcode() == ISD::BITCAST &&
13749 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13750 Amt = Amt.getOperand(0);
13751 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13752 VT.getVectorNumElements();
13753 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13754 uint64_t ShiftAmt = 0;
13755 for (unsigned i = 0; i != Ratio; ++i) {
13756 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13760 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13762 // Check remaining shift amounts.
13763 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13764 uint64_t ShAmt = 0;
13765 for (unsigned j = 0; j != Ratio; ++j) {
13766 ConstantSDNode *C =
13767 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13771 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13773 if (ShAmt != ShiftAmt)
13776 switch (Op.getOpcode()) {
13778 llvm_unreachable("Unknown shift opcode!");
13780 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13783 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13786 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13794 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13795 const X86Subtarget* Subtarget) {
13796 MVT VT = Op.getSimpleValueType();
13798 SDValue R = Op.getOperand(0);
13799 SDValue Amt = Op.getOperand(1);
13801 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13802 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13803 (Subtarget->hasInt256() &&
13804 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13805 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13806 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13808 EVT EltVT = VT.getVectorElementType();
13810 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13811 unsigned NumElts = VT.getVectorNumElements();
13813 for (i = 0; i != NumElts; ++i) {
13814 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13818 for (j = i; j != NumElts; ++j) {
13819 SDValue Arg = Amt.getOperand(j);
13820 if (Arg.getOpcode() == ISD::UNDEF) continue;
13821 if (Arg != Amt.getOperand(i))
13824 if (i != NumElts && j == NumElts)
13825 BaseShAmt = Amt.getOperand(i);
13827 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13828 Amt = Amt.getOperand(0);
13829 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13830 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13831 SDValue InVec = Amt.getOperand(0);
13832 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13833 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13835 for (; i != NumElts; ++i) {
13836 SDValue Arg = InVec.getOperand(i);
13837 if (Arg.getOpcode() == ISD::UNDEF) continue;
13841 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13842 if (ConstantSDNode *C =
13843 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13844 unsigned SplatIdx =
13845 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13846 if (C->getZExtValue() == SplatIdx)
13847 BaseShAmt = InVec.getOperand(1);
13850 if (!BaseShAmt.getNode())
13851 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13852 DAG.getIntPtrConstant(0));
13856 if (BaseShAmt.getNode()) {
13857 if (EltVT.bitsGT(MVT::i32))
13858 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13859 else if (EltVT.bitsLT(MVT::i32))
13860 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13862 switch (Op.getOpcode()) {
13864 llvm_unreachable("Unknown shift opcode!");
13866 switch (VT.SimpleTy) {
13867 default: return SDValue();
13876 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13879 switch (VT.SimpleTy) {
13880 default: return SDValue();
13887 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13890 switch (VT.SimpleTy) {
13891 default: return SDValue();
13900 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13906 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13907 if (!Subtarget->is64Bit() &&
13908 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13909 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13910 Amt.getOpcode() == ISD::BITCAST &&
13911 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13912 Amt = Amt.getOperand(0);
13913 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13914 VT.getVectorNumElements();
13915 std::vector<SDValue> Vals(Ratio);
13916 for (unsigned i = 0; i != Ratio; ++i)
13917 Vals[i] = Amt.getOperand(i);
13918 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13919 for (unsigned j = 0; j != Ratio; ++j)
13920 if (Vals[j] != Amt.getOperand(i + j))
13923 switch (Op.getOpcode()) {
13925 llvm_unreachable("Unknown shift opcode!");
13927 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13929 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13931 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13938 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13939 SelectionDAG &DAG) {
13941 MVT VT = Op.getSimpleValueType();
13943 SDValue R = Op.getOperand(0);
13944 SDValue Amt = Op.getOperand(1);
13947 if (!Subtarget->hasSSE2())
13950 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13954 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13958 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13960 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13961 if (Subtarget->hasInt256()) {
13962 if (Op.getOpcode() == ISD::SRL &&
13963 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13964 VT == MVT::v4i64 || VT == MVT::v8i32))
13966 if (Op.getOpcode() == ISD::SHL &&
13967 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13968 VT == MVT::v4i64 || VT == MVT::v8i32))
13970 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13974 // If possible, lower this packed shift into a vector multiply instead of
13975 // expanding it into a sequence of scalar shifts.
13976 // Do this only if the vector shift count is a constant build_vector.
13977 if (Op.getOpcode() == ISD::SHL &&
13978 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13979 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13980 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13981 SmallVector<SDValue, 8> Elts;
13982 EVT SVT = VT.getScalarType();
13983 unsigned SVTBits = SVT.getSizeInBits();
13984 const APInt &One = APInt(SVTBits, 1);
13985 unsigned NumElems = VT.getVectorNumElements();
13987 for (unsigned i=0; i !=NumElems; ++i) {
13988 SDValue Op = Amt->getOperand(i);
13989 if (Op->getOpcode() == ISD::UNDEF) {
13990 Elts.push_back(Op);
13994 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13995 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13996 uint64_t ShAmt = C.getZExtValue();
13997 if (ShAmt >= SVTBits) {
13998 Elts.push_back(DAG.getUNDEF(SVT));
14001 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14003 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14004 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14007 // Lower SHL with variable shift amount.
14008 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14009 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14011 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14012 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14013 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14014 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14017 // If possible, lower this shift as a sequence of two shifts by
14018 // constant plus a MOVSS/MOVSD instead of scalarizing it.
14020 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14022 // Could be rewritten as:
14023 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14025 // The advantage is that the two shifts from the example would be
14026 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14027 // the vector shift into four scalar shifts plus four pairs of vector
14029 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14030 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14031 unsigned TargetOpcode = X86ISD::MOVSS;
14032 bool CanBeSimplified;
14033 // The splat value for the first packed shift (the 'X' from the example).
14034 SDValue Amt1 = Amt->getOperand(0);
14035 // The splat value for the second packed shift (the 'Y' from the example).
14036 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14037 Amt->getOperand(2);
14039 // See if it is possible to replace this node with a sequence of
14040 // two shifts followed by a MOVSS/MOVSD
14041 if (VT == MVT::v4i32) {
14042 // Check if it is legal to use a MOVSS.
14043 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14044 Amt2 == Amt->getOperand(3);
14045 if (!CanBeSimplified) {
14046 // Otherwise, check if we can still simplify this node using a MOVSD.
14047 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14048 Amt->getOperand(2) == Amt->getOperand(3);
14049 TargetOpcode = X86ISD::MOVSD;
14050 Amt2 = Amt->getOperand(2);
14053 // Do similar checks for the case where the machine value type
14055 CanBeSimplified = Amt1 == Amt->getOperand(1);
14056 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14057 CanBeSimplified = Amt2 == Amt->getOperand(i);
14059 if (!CanBeSimplified) {
14060 TargetOpcode = X86ISD::MOVSD;
14061 CanBeSimplified = true;
14062 Amt2 = Amt->getOperand(4);
14063 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14064 CanBeSimplified = Amt1 == Amt->getOperand(i);
14065 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14066 CanBeSimplified = Amt2 == Amt->getOperand(j);
14070 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14071 isa<ConstantSDNode>(Amt2)) {
14072 // Replace this node with two shifts followed by a MOVSS/MOVSD.
14073 EVT CastVT = MVT::v4i32;
14075 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14076 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14078 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14079 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14080 if (TargetOpcode == X86ISD::MOVSD)
14081 CastVT = MVT::v2i64;
14082 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14083 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14084 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14086 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14090 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14091 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14094 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14095 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14097 // Turn 'a' into a mask suitable for VSELECT
14098 SDValue VSelM = DAG.getConstant(0x80, VT);
14099 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14100 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14102 SDValue CM1 = DAG.getConstant(0x0f, VT);
14103 SDValue CM2 = DAG.getConstant(0x3f, VT);
14105 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14106 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14107 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14108 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14109 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14112 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14113 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14114 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14116 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14117 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14118 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14119 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14120 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14123 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14124 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14125 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14127 // return VSELECT(r, r+r, a);
14128 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14129 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14133 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14134 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14135 // solution better.
14136 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14137 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14139 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14140 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14141 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14142 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14143 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14146 // Decompose 256-bit shifts into smaller 128-bit shifts.
14147 if (VT.is256BitVector()) {
14148 unsigned NumElems = VT.getVectorNumElements();
14149 MVT EltVT = VT.getVectorElementType();
14150 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14152 // Extract the two vectors
14153 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14154 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14156 // Recreate the shift amount vectors
14157 SDValue Amt1, Amt2;
14158 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14159 // Constant shift amount
14160 SmallVector<SDValue, 4> Amt1Csts;
14161 SmallVector<SDValue, 4> Amt2Csts;
14162 for (unsigned i = 0; i != NumElems/2; ++i)
14163 Amt1Csts.push_back(Amt->getOperand(i));
14164 for (unsigned i = NumElems/2; i != NumElems; ++i)
14165 Amt2Csts.push_back(Amt->getOperand(i));
14167 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14168 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14170 // Variable shift amount
14171 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14172 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14175 // Issue new vector shifts for the smaller types
14176 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14177 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14179 // Concatenate the result back
14180 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14186 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14187 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14188 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14189 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14190 // has only one use.
14191 SDNode *N = Op.getNode();
14192 SDValue LHS = N->getOperand(0);
14193 SDValue RHS = N->getOperand(1);
14194 unsigned BaseOp = 0;
14197 switch (Op.getOpcode()) {
14198 default: llvm_unreachable("Unknown ovf instruction!");
14200 // A subtract of one will be selected as a INC. Note that INC doesn't
14201 // set CF, so we can't do this for UADDO.
14202 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14204 BaseOp = X86ISD::INC;
14205 Cond = X86::COND_O;
14208 BaseOp = X86ISD::ADD;
14209 Cond = X86::COND_O;
14212 BaseOp = X86ISD::ADD;
14213 Cond = X86::COND_B;
14216 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14217 // set CF, so we can't do this for USUBO.
14218 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14220 BaseOp = X86ISD::DEC;
14221 Cond = X86::COND_O;
14224 BaseOp = X86ISD::SUB;
14225 Cond = X86::COND_O;
14228 BaseOp = X86ISD::SUB;
14229 Cond = X86::COND_B;
14232 BaseOp = X86ISD::SMUL;
14233 Cond = X86::COND_O;
14235 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14236 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14238 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14241 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14242 DAG.getConstant(X86::COND_O, MVT::i32),
14243 SDValue(Sum.getNode(), 2));
14245 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14249 // Also sets EFLAGS.
14250 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14251 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14254 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14255 DAG.getConstant(Cond, MVT::i32),
14256 SDValue(Sum.getNode(), 1));
14258 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14261 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14262 SelectionDAG &DAG) const {
14264 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14265 MVT VT = Op.getSimpleValueType();
14267 if (!Subtarget->hasSSE2() || !VT.isVector())
14270 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14271 ExtraVT.getScalarType().getSizeInBits();
14273 switch (VT.SimpleTy) {
14274 default: return SDValue();
14277 if (!Subtarget->hasFp256())
14279 if (!Subtarget->hasInt256()) {
14280 // needs to be split
14281 unsigned NumElems = VT.getVectorNumElements();
14283 // Extract the LHS vectors
14284 SDValue LHS = Op.getOperand(0);
14285 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14286 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14288 MVT EltVT = VT.getVectorElementType();
14289 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14291 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14292 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14293 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14295 SDValue Extra = DAG.getValueType(ExtraVT);
14297 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14298 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14300 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14305 SDValue Op0 = Op.getOperand(0);
14306 SDValue Op00 = Op0.getOperand(0);
14308 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14309 if (Op0.getOpcode() == ISD::BITCAST &&
14310 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14311 // (sext (vzext x)) -> (vsext x)
14312 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14313 if (Tmp1.getNode()) {
14314 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14315 // This folding is only valid when the in-reg type is a vector of i8,
14317 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14318 ExtraEltVT == MVT::i32) {
14319 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14320 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14321 "This optimization is invalid without a VZEXT.");
14322 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14328 // If the above didn't work, then just use Shift-Left + Shift-Right.
14329 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14331 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14337 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14338 SelectionDAG &DAG) {
14340 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14341 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14342 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14343 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14345 // The only fence that needs an instruction is a sequentially-consistent
14346 // cross-thread fence.
14347 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14348 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14349 // no-sse2). There isn't any reason to disable it if the target processor
14351 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14352 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14354 SDValue Chain = Op.getOperand(0);
14355 SDValue Zero = DAG.getConstant(0, MVT::i32);
14357 DAG.getRegister(X86::ESP, MVT::i32), // Base
14358 DAG.getTargetConstant(1, MVT::i8), // Scale
14359 DAG.getRegister(0, MVT::i32), // Index
14360 DAG.getTargetConstant(0, MVT::i32), // Disp
14361 DAG.getRegister(0, MVT::i32), // Segment.
14365 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14366 return SDValue(Res, 0);
14369 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14370 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14373 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14374 SelectionDAG &DAG) {
14375 MVT T = Op.getSimpleValueType();
14379 switch(T.SimpleTy) {
14380 default: llvm_unreachable("Invalid value type!");
14381 case MVT::i8: Reg = X86::AL; size = 1; break;
14382 case MVT::i16: Reg = X86::AX; size = 2; break;
14383 case MVT::i32: Reg = X86::EAX; size = 4; break;
14385 assert(Subtarget->is64Bit() && "Node not type legal!");
14386 Reg = X86::RAX; size = 8;
14389 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14390 Op.getOperand(2), SDValue());
14391 SDValue Ops[] = { cpIn.getValue(0),
14394 DAG.getTargetConstant(size, MVT::i8),
14395 cpIn.getValue(1) };
14396 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14397 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14398 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14401 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14405 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14406 SelectionDAG &DAG) {
14407 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14408 MVT DstVT = Op.getSimpleValueType();
14410 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14411 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14412 if (DstVT != MVT::f64)
14413 // This conversion needs to be expanded.
14416 SDValue InVec = Op->getOperand(0);
14418 unsigned NumElts = SrcVT.getVectorNumElements();
14419 EVT SVT = SrcVT.getVectorElementType();
14421 // Widen the vector in input in the case of MVT::v2i32.
14422 // Example: from MVT::v2i32 to MVT::v4i32.
14423 SmallVector<SDValue, 16> Elts;
14424 for (unsigned i = 0, e = NumElts; i != e; ++i)
14425 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14426 DAG.getIntPtrConstant(i)));
14428 // Explicitly mark the extra elements as Undef.
14429 SDValue Undef = DAG.getUNDEF(SVT);
14430 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14431 Elts.push_back(Undef);
14433 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14434 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14435 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14436 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14437 DAG.getIntPtrConstant(0));
14440 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14441 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14442 assert((DstVT == MVT::i64 ||
14443 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14444 "Unexpected custom BITCAST");
14445 // i64 <=> MMX conversions are Legal.
14446 if (SrcVT==MVT::i64 && DstVT.isVector())
14448 if (DstVT==MVT::i64 && SrcVT.isVector())
14450 // MMX <=> MMX conversions are Legal.
14451 if (SrcVT.isVector() && DstVT.isVector())
14453 // All other conversions need to be expanded.
14457 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14458 SDNode *Node = Op.getNode();
14460 EVT T = Node->getValueType(0);
14461 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14462 DAG.getConstant(0, T), Node->getOperand(2));
14463 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14464 cast<AtomicSDNode>(Node)->getMemoryVT(),
14465 Node->getOperand(0),
14466 Node->getOperand(1), negOp,
14467 cast<AtomicSDNode>(Node)->getMemOperand(),
14468 cast<AtomicSDNode>(Node)->getOrdering(),
14469 cast<AtomicSDNode>(Node)->getSynchScope());
14472 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14473 SDNode *Node = Op.getNode();
14475 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14477 // Convert seq_cst store -> xchg
14478 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14479 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14480 // (The only way to get a 16-byte store is cmpxchg16b)
14481 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14482 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14483 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14484 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14485 cast<AtomicSDNode>(Node)->getMemoryVT(),
14486 Node->getOperand(0),
14487 Node->getOperand(1), Node->getOperand(2),
14488 cast<AtomicSDNode>(Node)->getMemOperand(),
14489 cast<AtomicSDNode>(Node)->getOrdering(),
14490 cast<AtomicSDNode>(Node)->getSynchScope());
14491 return Swap.getValue(1);
14493 // Other atomic stores have a simple pattern.
14497 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14498 EVT VT = Op.getNode()->getSimpleValueType(0);
14500 // Let legalize expand this if it isn't a legal type yet.
14501 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14504 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14507 bool ExtraOp = false;
14508 switch (Op.getOpcode()) {
14509 default: llvm_unreachable("Invalid code");
14510 case ISD::ADDC: Opc = X86ISD::ADD; break;
14511 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14512 case ISD::SUBC: Opc = X86ISD::SUB; break;
14513 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14517 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14519 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14520 Op.getOperand(1), Op.getOperand(2));
14523 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14524 SelectionDAG &DAG) {
14525 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14527 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14528 // which returns the values as { float, float } (in XMM0) or
14529 // { double, double } (which is returned in XMM0, XMM1).
14531 SDValue Arg = Op.getOperand(0);
14532 EVT ArgVT = Arg.getValueType();
14533 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14535 TargetLowering::ArgListTy Args;
14536 TargetLowering::ArgListEntry Entry;
14540 Entry.isSExt = false;
14541 Entry.isZExt = false;
14542 Args.push_back(Entry);
14544 bool isF64 = ArgVT == MVT::f64;
14545 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14546 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14547 // the results are returned via SRet in memory.
14548 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14549 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14550 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14552 Type *RetTy = isF64
14553 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14554 : (Type*)VectorType::get(ArgTy, 4);
14556 TargetLowering::CallLoweringInfo CLI(DAG);
14557 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14558 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14560 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14563 // Returned in xmm0 and xmm1.
14564 return CallResult.first;
14566 // Returned in bits 0:31 and 32:64 xmm0.
14567 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14568 CallResult.first, DAG.getIntPtrConstant(0));
14569 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14570 CallResult.first, DAG.getIntPtrConstant(1));
14571 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14572 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14575 /// LowerOperation - Provide custom lowering hooks for some operations.
14577 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14578 switch (Op.getOpcode()) {
14579 default: llvm_unreachable("Should not custom lower this!");
14580 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14581 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14582 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14583 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14584 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14585 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14586 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14587 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14588 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14589 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14590 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14591 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14592 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14593 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14594 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14595 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14596 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14597 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14598 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14599 case ISD::SHL_PARTS:
14600 case ISD::SRA_PARTS:
14601 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14602 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14603 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14604 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14605 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14606 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14607 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14608 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14609 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14610 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14611 case ISD::FABS: return LowerFABS(Op, DAG);
14612 case ISD::FNEG: return LowerFNEG(Op, DAG);
14613 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14614 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14615 case ISD::SETCC: return LowerSETCC(Op, DAG);
14616 case ISD::SELECT: return LowerSELECT(Op, DAG);
14617 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14618 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14619 case ISD::VASTART: return LowerVASTART(Op, DAG);
14620 case ISD::VAARG: return LowerVAARG(Op, DAG);
14621 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14622 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14623 case ISD::INTRINSIC_VOID:
14624 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14625 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14626 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14627 case ISD::FRAME_TO_ARGS_OFFSET:
14628 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14629 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14630 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14631 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14632 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14633 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14634 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14635 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14636 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14637 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14638 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14639 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14640 case ISD::UMUL_LOHI:
14641 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14644 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14650 case ISD::UMULO: return LowerXALUO(Op, DAG);
14651 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14652 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14656 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14657 case ISD::ADD: return LowerADD(Op, DAG);
14658 case ISD::SUB: return LowerSUB(Op, DAG);
14659 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14663 static void ReplaceATOMIC_LOAD(SDNode *Node,
14664 SmallVectorImpl<SDValue> &Results,
14665 SelectionDAG &DAG) {
14667 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14669 // Convert wide load -> cmpxchg8b/cmpxchg16b
14670 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14671 // (The only way to get a 16-byte load is cmpxchg16b)
14672 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14673 SDValue Zero = DAG.getConstant(0, VT);
14674 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14675 Node->getOperand(0),
14676 Node->getOperand(1), Zero, Zero,
14677 cast<AtomicSDNode>(Node)->getMemOperand(),
14678 cast<AtomicSDNode>(Node)->getOrdering(),
14679 cast<AtomicSDNode>(Node)->getOrdering(),
14680 cast<AtomicSDNode>(Node)->getSynchScope());
14681 Results.push_back(Swap.getValue(0));
14682 Results.push_back(Swap.getValue(1));
14686 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14687 SelectionDAG &DAG, unsigned NewOp) {
14689 assert (Node->getValueType(0) == MVT::i64 &&
14690 "Only know how to expand i64 atomics");
14692 SDValue Chain = Node->getOperand(0);
14693 SDValue In1 = Node->getOperand(1);
14694 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14695 Node->getOperand(2), DAG.getIntPtrConstant(0));
14696 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14697 Node->getOperand(2), DAG.getIntPtrConstant(1));
14698 SDValue Ops[] = { Chain, In1, In2L, In2H };
14699 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14701 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14702 cast<MemSDNode>(Node)->getMemOperand());
14703 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14704 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14705 Results.push_back(Result.getValue(2));
14708 /// ReplaceNodeResults - Replace a node with an illegal result type
14709 /// with a new node built out of custom code.
14710 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14711 SmallVectorImpl<SDValue>&Results,
14712 SelectionDAG &DAG) const {
14714 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14715 switch (N->getOpcode()) {
14717 llvm_unreachable("Do not know how to custom type legalize this operation!");
14718 case ISD::SIGN_EXTEND_INREG:
14723 // We don't want to expand or promote these.
14730 case ISD::UDIVREM: {
14731 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14732 Results.push_back(V);
14735 case ISD::FP_TO_SINT:
14736 case ISD::FP_TO_UINT: {
14737 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14739 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14742 std::pair<SDValue,SDValue> Vals =
14743 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14744 SDValue FIST = Vals.first, StackSlot = Vals.second;
14745 if (FIST.getNode()) {
14746 EVT VT = N->getValueType(0);
14747 // Return a load from the stack slot.
14748 if (StackSlot.getNode())
14749 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14750 MachinePointerInfo(),
14751 false, false, false, 0));
14753 Results.push_back(FIST);
14757 case ISD::UINT_TO_FP: {
14758 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14759 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14760 N->getValueType(0) != MVT::v2f32)
14762 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14764 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14766 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14767 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14768 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14769 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14770 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14771 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14774 case ISD::FP_ROUND: {
14775 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14777 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14778 Results.push_back(V);
14781 case ISD::INTRINSIC_W_CHAIN: {
14782 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14784 default : llvm_unreachable("Do not know how to custom type "
14785 "legalize this intrinsic operation!");
14786 case Intrinsic::x86_rdtsc:
14787 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14789 case Intrinsic::x86_rdtscp:
14790 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14794 case ISD::READCYCLECOUNTER: {
14795 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14798 case ISD::ATOMIC_CMP_SWAP: {
14799 EVT T = N->getValueType(0);
14800 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14801 bool Regs64bit = T == MVT::i128;
14802 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14803 SDValue cpInL, cpInH;
14804 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14805 DAG.getConstant(0, HalfT));
14806 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14807 DAG.getConstant(1, HalfT));
14808 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14809 Regs64bit ? X86::RAX : X86::EAX,
14811 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14812 Regs64bit ? X86::RDX : X86::EDX,
14813 cpInH, cpInL.getValue(1));
14814 SDValue swapInL, swapInH;
14815 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14816 DAG.getConstant(0, HalfT));
14817 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14818 DAG.getConstant(1, HalfT));
14819 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14820 Regs64bit ? X86::RBX : X86::EBX,
14821 swapInL, cpInH.getValue(1));
14822 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14823 Regs64bit ? X86::RCX : X86::ECX,
14824 swapInH, swapInL.getValue(1));
14825 SDValue Ops[] = { swapInH.getValue(0),
14827 swapInH.getValue(1) };
14828 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14829 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14830 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14831 X86ISD::LCMPXCHG8_DAG;
14832 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14833 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14834 Regs64bit ? X86::RAX : X86::EAX,
14835 HalfT, Result.getValue(1));
14836 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14837 Regs64bit ? X86::RDX : X86::EDX,
14838 HalfT, cpOutL.getValue(2));
14839 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14840 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14841 Results.push_back(cpOutH.getValue(1));
14844 case ISD::ATOMIC_LOAD_ADD:
14845 case ISD::ATOMIC_LOAD_AND:
14846 case ISD::ATOMIC_LOAD_NAND:
14847 case ISD::ATOMIC_LOAD_OR:
14848 case ISD::ATOMIC_LOAD_SUB:
14849 case ISD::ATOMIC_LOAD_XOR:
14850 case ISD::ATOMIC_LOAD_MAX:
14851 case ISD::ATOMIC_LOAD_MIN:
14852 case ISD::ATOMIC_LOAD_UMAX:
14853 case ISD::ATOMIC_LOAD_UMIN:
14854 case ISD::ATOMIC_SWAP: {
14856 switch (N->getOpcode()) {
14857 default: llvm_unreachable("Unexpected opcode");
14858 case ISD::ATOMIC_LOAD_ADD:
14859 Opc = X86ISD::ATOMADD64_DAG;
14861 case ISD::ATOMIC_LOAD_AND:
14862 Opc = X86ISD::ATOMAND64_DAG;
14864 case ISD::ATOMIC_LOAD_NAND:
14865 Opc = X86ISD::ATOMNAND64_DAG;
14867 case ISD::ATOMIC_LOAD_OR:
14868 Opc = X86ISD::ATOMOR64_DAG;
14870 case ISD::ATOMIC_LOAD_SUB:
14871 Opc = X86ISD::ATOMSUB64_DAG;
14873 case ISD::ATOMIC_LOAD_XOR:
14874 Opc = X86ISD::ATOMXOR64_DAG;
14876 case ISD::ATOMIC_LOAD_MAX:
14877 Opc = X86ISD::ATOMMAX64_DAG;
14879 case ISD::ATOMIC_LOAD_MIN:
14880 Opc = X86ISD::ATOMMIN64_DAG;
14882 case ISD::ATOMIC_LOAD_UMAX:
14883 Opc = X86ISD::ATOMUMAX64_DAG;
14885 case ISD::ATOMIC_LOAD_UMIN:
14886 Opc = X86ISD::ATOMUMIN64_DAG;
14888 case ISD::ATOMIC_SWAP:
14889 Opc = X86ISD::ATOMSWAP64_DAG;
14892 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14895 case ISD::ATOMIC_LOAD: {
14896 ReplaceATOMIC_LOAD(N, Results, DAG);
14899 case ISD::BITCAST: {
14900 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14901 EVT DstVT = N->getValueType(0);
14902 EVT SrcVT = N->getOperand(0)->getValueType(0);
14904 if (SrcVT != MVT::f64 ||
14905 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14908 unsigned NumElts = DstVT.getVectorNumElements();
14909 EVT SVT = DstVT.getVectorElementType();
14910 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14911 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14912 MVT::v2f64, N->getOperand(0));
14913 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14915 SmallVector<SDValue, 8> Elts;
14916 for (unsigned i = 0, e = NumElts; i != e; ++i)
14917 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14918 ToVecInt, DAG.getIntPtrConstant(i)));
14920 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14925 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14927 default: return nullptr;
14928 case X86ISD::BSF: return "X86ISD::BSF";
14929 case X86ISD::BSR: return "X86ISD::BSR";
14930 case X86ISD::SHLD: return "X86ISD::SHLD";
14931 case X86ISD::SHRD: return "X86ISD::SHRD";
14932 case X86ISD::FAND: return "X86ISD::FAND";
14933 case X86ISD::FANDN: return "X86ISD::FANDN";
14934 case X86ISD::FOR: return "X86ISD::FOR";
14935 case X86ISD::FXOR: return "X86ISD::FXOR";
14936 case X86ISD::FSRL: return "X86ISD::FSRL";
14937 case X86ISD::FILD: return "X86ISD::FILD";
14938 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14939 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14940 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14941 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14942 case X86ISD::FLD: return "X86ISD::FLD";
14943 case X86ISD::FST: return "X86ISD::FST";
14944 case X86ISD::CALL: return "X86ISD::CALL";
14945 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14946 case X86ISD::BT: return "X86ISD::BT";
14947 case X86ISD::CMP: return "X86ISD::CMP";
14948 case X86ISD::COMI: return "X86ISD::COMI";
14949 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14950 case X86ISD::CMPM: return "X86ISD::CMPM";
14951 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14952 case X86ISD::SETCC: return "X86ISD::SETCC";
14953 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14954 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14955 case X86ISD::CMOV: return "X86ISD::CMOV";
14956 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14957 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14958 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14959 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14960 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14961 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14962 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14963 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14964 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14965 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14966 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14967 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14968 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14969 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14970 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14971 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14972 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14973 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14974 case X86ISD::HADD: return "X86ISD::HADD";
14975 case X86ISD::HSUB: return "X86ISD::HSUB";
14976 case X86ISD::FHADD: return "X86ISD::FHADD";
14977 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14978 case X86ISD::UMAX: return "X86ISD::UMAX";
14979 case X86ISD::UMIN: return "X86ISD::UMIN";
14980 case X86ISD::SMAX: return "X86ISD::SMAX";
14981 case X86ISD::SMIN: return "X86ISD::SMIN";
14982 case X86ISD::FMAX: return "X86ISD::FMAX";
14983 case X86ISD::FMIN: return "X86ISD::FMIN";
14984 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14985 case X86ISD::FMINC: return "X86ISD::FMINC";
14986 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14987 case X86ISD::FRCP: return "X86ISD::FRCP";
14988 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14989 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14990 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14991 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14992 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14993 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14994 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14995 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14996 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14997 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14998 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14999 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
15000 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
15001 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
15002 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
15003 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
15004 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
15005 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
15006 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
15007 case X86ISD::VZEXT: return "X86ISD::VZEXT";
15008 case X86ISD::VSEXT: return "X86ISD::VSEXT";
15009 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
15010 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
15011 case X86ISD::VINSERT: return "X86ISD::VINSERT";
15012 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
15013 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
15014 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
15015 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
15016 case X86ISD::VSHL: return "X86ISD::VSHL";
15017 case X86ISD::VSRL: return "X86ISD::VSRL";
15018 case X86ISD::VSRA: return "X86ISD::VSRA";
15019 case X86ISD::VSHLI: return "X86ISD::VSHLI";
15020 case X86ISD::VSRLI: return "X86ISD::VSRLI";
15021 case X86ISD::VSRAI: return "X86ISD::VSRAI";
15022 case X86ISD::CMPP: return "X86ISD::CMPP";
15023 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
15024 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
15025 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
15026 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
15027 case X86ISD::ADD: return "X86ISD::ADD";
15028 case X86ISD::SUB: return "X86ISD::SUB";
15029 case X86ISD::ADC: return "X86ISD::ADC";
15030 case X86ISD::SBB: return "X86ISD::SBB";
15031 case X86ISD::SMUL: return "X86ISD::SMUL";
15032 case X86ISD::UMUL: return "X86ISD::UMUL";
15033 case X86ISD::INC: return "X86ISD::INC";
15034 case X86ISD::DEC: return "X86ISD::DEC";
15035 case X86ISD::OR: return "X86ISD::OR";
15036 case X86ISD::XOR: return "X86ISD::XOR";
15037 case X86ISD::AND: return "X86ISD::AND";
15038 case X86ISD::BEXTR: return "X86ISD::BEXTR";
15039 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
15040 case X86ISD::PTEST: return "X86ISD::PTEST";
15041 case X86ISD::TESTP: return "X86ISD::TESTP";
15042 case X86ISD::TESTM: return "X86ISD::TESTM";
15043 case X86ISD::TESTNM: return "X86ISD::TESTNM";
15044 case X86ISD::KORTEST: return "X86ISD::KORTEST";
15045 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
15046 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
15047 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
15048 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
15049 case X86ISD::SHUFP: return "X86ISD::SHUFP";
15050 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
15051 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
15052 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
15053 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
15054 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
15055 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
15056 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
15057 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
15058 case X86ISD::MOVSD: return "X86ISD::MOVSD";
15059 case X86ISD::MOVSS: return "X86ISD::MOVSS";
15060 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
15061 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
15062 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
15063 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
15064 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
15065 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
15066 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
15067 case X86ISD::VPERMV: return "X86ISD::VPERMV";
15068 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
15069 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
15070 case X86ISD::VPERMI: return "X86ISD::VPERMI";
15071 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
15072 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
15073 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15074 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
15075 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
15076 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
15077 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
15078 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
15079 case X86ISD::SAHF: return "X86ISD::SAHF";
15080 case X86ISD::RDRAND: return "X86ISD::RDRAND";
15081 case X86ISD::RDSEED: return "X86ISD::RDSEED";
15082 case X86ISD::FMADD: return "X86ISD::FMADD";
15083 case X86ISD::FMSUB: return "X86ISD::FMSUB";
15084 case X86ISD::FNMADD: return "X86ISD::FNMADD";
15085 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
15086 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
15087 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
15088 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
15089 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
15090 case X86ISD::XTEST: return "X86ISD::XTEST";
15094 // isLegalAddressingMode - Return true if the addressing mode represented
15095 // by AM is legal for this target, for a load/store of the specified type.
15096 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15098 // X86 supports extremely general addressing modes.
15099 CodeModel::Model M = getTargetMachine().getCodeModel();
15100 Reloc::Model R = getTargetMachine().getRelocationModel();
15102 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15103 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15108 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15110 // If a reference to this global requires an extra load, we can't fold it.
15111 if (isGlobalStubReference(GVFlags))
15114 // If BaseGV requires a register for the PIC base, we cannot also have a
15115 // BaseReg specified.
15116 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15119 // If lower 4G is not available, then we must use rip-relative addressing.
15120 if ((M != CodeModel::Small || R != Reloc::Static) &&
15121 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15125 switch (AM.Scale) {
15131 // These scales always work.
15136 // These scales are formed with basereg+scalereg. Only accept if there is
15141 default: // Other stuff never works.
15148 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15149 unsigned Bits = Ty->getScalarSizeInBits();
15151 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15152 // particularly cheaper than those without.
15156 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15157 // variable shifts just as cheap as scalar ones.
15158 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15161 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15162 // fully general vector.
15166 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15167 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15169 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15170 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15171 return NumBits1 > NumBits2;
15174 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15175 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15178 if (!isTypeLegal(EVT::getEVT(Ty1)))
15181 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15183 // Assuming the caller doesn't have a zeroext or signext return parameter,
15184 // truncation all the way down to i1 is valid.
15188 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15189 return isInt<32>(Imm);
15192 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15193 // Can also use sub to handle negated immediates.
15194 return isInt<32>(Imm);
15197 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15198 if (!VT1.isInteger() || !VT2.isInteger())
15200 unsigned NumBits1 = VT1.getSizeInBits();
15201 unsigned NumBits2 = VT2.getSizeInBits();
15202 return NumBits1 > NumBits2;
15205 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15206 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15207 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15210 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15211 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15212 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15215 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15216 EVT VT1 = Val.getValueType();
15217 if (isZExtFree(VT1, VT2))
15220 if (Val.getOpcode() != ISD::LOAD)
15223 if (!VT1.isSimple() || !VT1.isInteger() ||
15224 !VT2.isSimple() || !VT2.isInteger())
15227 switch (VT1.getSimpleVT().SimpleTy) {
15232 // X86 has 8, 16, and 32-bit zero-extending loads.
15240 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15241 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15244 VT = VT.getScalarType();
15246 if (!VT.isSimple())
15249 switch (VT.getSimpleVT().SimpleTy) {
15260 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15261 // i16 instructions are longer (0x66 prefix) and potentially slower.
15262 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15265 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15266 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15267 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15268 /// are assumed to be legal.
15270 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15272 if (!VT.isSimple())
15275 MVT SVT = VT.getSimpleVT();
15277 // Very little shuffling can be done for 64-bit vectors right now.
15278 if (VT.getSizeInBits() == 64)
15281 // If this is a single-input shuffle with no 128 bit lane crossings we can
15282 // lower it into pshufb.
15283 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15284 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15285 bool isLegal = true;
15286 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15287 if (M[I] >= (int)SVT.getVectorNumElements() ||
15288 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15297 // FIXME: blends, shifts.
15298 return (SVT.getVectorNumElements() == 2 ||
15299 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15300 isMOVLMask(M, SVT) ||
15301 isSHUFPMask(M, SVT) ||
15302 isPSHUFDMask(M, SVT) ||
15303 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15304 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15305 isPALIGNRMask(M, SVT, Subtarget) ||
15306 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15307 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15308 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15309 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15310 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15314 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15316 if (!VT.isSimple())
15319 MVT SVT = VT.getSimpleVT();
15320 unsigned NumElts = SVT.getVectorNumElements();
15321 // FIXME: This collection of masks seems suspect.
15324 if (NumElts == 4 && SVT.is128BitVector()) {
15325 return (isMOVLMask(Mask, SVT) ||
15326 isCommutedMOVLMask(Mask, SVT, true) ||
15327 isSHUFPMask(Mask, SVT) ||
15328 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15333 //===----------------------------------------------------------------------===//
15334 // X86 Scheduler Hooks
15335 //===----------------------------------------------------------------------===//
15337 /// Utility function to emit xbegin specifying the start of an RTM region.
15338 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15339 const TargetInstrInfo *TII) {
15340 DebugLoc DL = MI->getDebugLoc();
15342 const BasicBlock *BB = MBB->getBasicBlock();
15343 MachineFunction::iterator I = MBB;
15346 // For the v = xbegin(), we generate
15357 MachineBasicBlock *thisMBB = MBB;
15358 MachineFunction *MF = MBB->getParent();
15359 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15360 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15361 MF->insert(I, mainMBB);
15362 MF->insert(I, sinkMBB);
15364 // Transfer the remainder of BB and its successor edges to sinkMBB.
15365 sinkMBB->splice(sinkMBB->begin(), MBB,
15366 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15367 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15371 // # fallthrough to mainMBB
15372 // # abortion to sinkMBB
15373 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15374 thisMBB->addSuccessor(mainMBB);
15375 thisMBB->addSuccessor(sinkMBB);
15379 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15380 mainMBB->addSuccessor(sinkMBB);
15383 // EAX is live into the sinkMBB
15384 sinkMBB->addLiveIn(X86::EAX);
15385 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15386 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15389 MI->eraseFromParent();
15393 // Get CMPXCHG opcode for the specified data type.
15394 static unsigned getCmpXChgOpcode(EVT VT) {
15395 switch (VT.getSimpleVT().SimpleTy) {
15396 case MVT::i8: return X86::LCMPXCHG8;
15397 case MVT::i16: return X86::LCMPXCHG16;
15398 case MVT::i32: return X86::LCMPXCHG32;
15399 case MVT::i64: return X86::LCMPXCHG64;
15403 llvm_unreachable("Invalid operand size!");
15406 // Get LOAD opcode for the specified data type.
15407 static unsigned getLoadOpcode(EVT VT) {
15408 switch (VT.getSimpleVT().SimpleTy) {
15409 case MVT::i8: return X86::MOV8rm;
15410 case MVT::i16: return X86::MOV16rm;
15411 case MVT::i32: return X86::MOV32rm;
15412 case MVT::i64: return X86::MOV64rm;
15416 llvm_unreachable("Invalid operand size!");
15419 // Get opcode of the non-atomic one from the specified atomic instruction.
15420 static unsigned getNonAtomicOpcode(unsigned Opc) {
15422 case X86::ATOMAND8: return X86::AND8rr;
15423 case X86::ATOMAND16: return X86::AND16rr;
15424 case X86::ATOMAND32: return X86::AND32rr;
15425 case X86::ATOMAND64: return X86::AND64rr;
15426 case X86::ATOMOR8: return X86::OR8rr;
15427 case X86::ATOMOR16: return X86::OR16rr;
15428 case X86::ATOMOR32: return X86::OR32rr;
15429 case X86::ATOMOR64: return X86::OR64rr;
15430 case X86::ATOMXOR8: return X86::XOR8rr;
15431 case X86::ATOMXOR16: return X86::XOR16rr;
15432 case X86::ATOMXOR32: return X86::XOR32rr;
15433 case X86::ATOMXOR64: return X86::XOR64rr;
15435 llvm_unreachable("Unhandled atomic-load-op opcode!");
15438 // Get opcode of the non-atomic one from the specified atomic instruction with
15440 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15441 unsigned &ExtraOpc) {
15443 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15444 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15445 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15446 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15447 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15448 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15449 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15450 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15451 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15452 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15453 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15454 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15455 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15456 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15457 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15458 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15459 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15460 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15461 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15462 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15464 llvm_unreachable("Unhandled atomic-load-op opcode!");
15467 // Get opcode of the non-atomic one from the specified atomic instruction for
15468 // 64-bit data type on 32-bit target.
15469 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15471 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15472 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15473 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15474 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15475 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15476 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15477 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15478 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15479 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15480 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15482 llvm_unreachable("Unhandled atomic-load-op opcode!");
15485 // Get opcode of the non-atomic one from the specified atomic instruction for
15486 // 64-bit data type on 32-bit target with extra opcode.
15487 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15489 unsigned &ExtraOpc) {
15491 case X86::ATOMNAND6432:
15492 ExtraOpc = X86::NOT32r;
15493 HiOpc = X86::AND32rr;
15494 return X86::AND32rr;
15496 llvm_unreachable("Unhandled atomic-load-op opcode!");
15499 // Get pseudo CMOV opcode from the specified data type.
15500 static unsigned getPseudoCMOVOpc(EVT VT) {
15501 switch (VT.getSimpleVT().SimpleTy) {
15502 case MVT::i8: return X86::CMOV_GR8;
15503 case MVT::i16: return X86::CMOV_GR16;
15504 case MVT::i32: return X86::CMOV_GR32;
15508 llvm_unreachable("Unknown CMOV opcode!");
15511 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15512 // They will be translated into a spin-loop or compare-exchange loop from
15515 // dst = atomic-fetch-op MI.addr, MI.val
15521 // t1 = LOAD MI.addr
15523 // t4 = phi(t1, t3 / loop)
15524 // t2 = OP MI.val, t4
15526 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15532 MachineBasicBlock *
15533 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15534 MachineBasicBlock *MBB) const {
15535 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15536 DebugLoc DL = MI->getDebugLoc();
15538 MachineFunction *MF = MBB->getParent();
15539 MachineRegisterInfo &MRI = MF->getRegInfo();
15541 const BasicBlock *BB = MBB->getBasicBlock();
15542 MachineFunction::iterator I = MBB;
15545 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15546 "Unexpected number of operands");
15548 assert(MI->hasOneMemOperand() &&
15549 "Expected atomic-load-op to have one memoperand");
15551 // Memory Reference
15552 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15553 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15555 unsigned DstReg, SrcReg;
15556 unsigned MemOpndSlot;
15558 unsigned CurOp = 0;
15560 DstReg = MI->getOperand(CurOp++).getReg();
15561 MemOpndSlot = CurOp;
15562 CurOp += X86::AddrNumOperands;
15563 SrcReg = MI->getOperand(CurOp++).getReg();
15565 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15566 MVT::SimpleValueType VT = *RC->vt_begin();
15567 unsigned t1 = MRI.createVirtualRegister(RC);
15568 unsigned t2 = MRI.createVirtualRegister(RC);
15569 unsigned t3 = MRI.createVirtualRegister(RC);
15570 unsigned t4 = MRI.createVirtualRegister(RC);
15571 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15573 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15574 unsigned LOADOpc = getLoadOpcode(VT);
15576 // For the atomic load-arith operator, we generate
15579 // t1 = LOAD [MI.addr]
15581 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15582 // t1 = OP MI.val, EAX
15584 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15590 MachineBasicBlock *thisMBB = MBB;
15591 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15592 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15593 MF->insert(I, mainMBB);
15594 MF->insert(I, sinkMBB);
15596 MachineInstrBuilder MIB;
15598 // Transfer the remainder of BB and its successor edges to sinkMBB.
15599 sinkMBB->splice(sinkMBB->begin(), MBB,
15600 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15601 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15604 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15605 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15606 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15608 NewMO.setIsKill(false);
15609 MIB.addOperand(NewMO);
15611 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15612 unsigned flags = (*MMOI)->getFlags();
15613 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15614 MachineMemOperand *MMO =
15615 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15616 (*MMOI)->getSize(),
15617 (*MMOI)->getBaseAlignment(),
15618 (*MMOI)->getTBAAInfo(),
15619 (*MMOI)->getRanges());
15620 MIB.addMemOperand(MMO);
15623 thisMBB->addSuccessor(mainMBB);
15626 MachineBasicBlock *origMainMBB = mainMBB;
15629 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15630 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15632 unsigned Opc = MI->getOpcode();
15635 llvm_unreachable("Unhandled atomic-load-op opcode!");
15636 case X86::ATOMAND8:
15637 case X86::ATOMAND16:
15638 case X86::ATOMAND32:
15639 case X86::ATOMAND64:
15641 case X86::ATOMOR16:
15642 case X86::ATOMOR32:
15643 case X86::ATOMOR64:
15644 case X86::ATOMXOR8:
15645 case X86::ATOMXOR16:
15646 case X86::ATOMXOR32:
15647 case X86::ATOMXOR64: {
15648 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15649 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15653 case X86::ATOMNAND8:
15654 case X86::ATOMNAND16:
15655 case X86::ATOMNAND32:
15656 case X86::ATOMNAND64: {
15657 unsigned Tmp = MRI.createVirtualRegister(RC);
15659 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15660 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15662 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15665 case X86::ATOMMAX8:
15666 case X86::ATOMMAX16:
15667 case X86::ATOMMAX32:
15668 case X86::ATOMMAX64:
15669 case X86::ATOMMIN8:
15670 case X86::ATOMMIN16:
15671 case X86::ATOMMIN32:
15672 case X86::ATOMMIN64:
15673 case X86::ATOMUMAX8:
15674 case X86::ATOMUMAX16:
15675 case X86::ATOMUMAX32:
15676 case X86::ATOMUMAX64:
15677 case X86::ATOMUMIN8:
15678 case X86::ATOMUMIN16:
15679 case X86::ATOMUMIN32:
15680 case X86::ATOMUMIN64: {
15682 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15684 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15688 if (Subtarget->hasCMov()) {
15689 if (VT != MVT::i8) {
15691 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15695 // Promote i8 to i32 to use CMOV32
15696 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15697 const TargetRegisterClass *RC32 =
15698 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15699 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15700 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15701 unsigned Tmp = MRI.createVirtualRegister(RC32);
15703 unsigned Undef = MRI.createVirtualRegister(RC32);
15704 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15706 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15709 .addImm(X86::sub_8bit);
15710 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15713 .addImm(X86::sub_8bit);
15715 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15719 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15720 .addReg(Tmp, 0, X86::sub_8bit);
15723 // Use pseudo select and lower them.
15724 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15725 "Invalid atomic-load-op transformation!");
15726 unsigned SelOpc = getPseudoCMOVOpc(VT);
15727 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15728 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15729 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15730 .addReg(SrcReg).addReg(t4)
15732 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15733 // Replace the original PHI node as mainMBB is changed after CMOV
15735 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15736 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15737 Phi->eraseFromParent();
15743 // Copy PhyReg back from virtual register.
15744 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15747 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15748 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15749 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15751 NewMO.setIsKill(false);
15752 MIB.addOperand(NewMO);
15755 MIB.setMemRefs(MMOBegin, MMOEnd);
15757 // Copy PhyReg back to virtual register.
15758 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15761 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15763 mainMBB->addSuccessor(origMainMBB);
15764 mainMBB->addSuccessor(sinkMBB);
15767 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15768 TII->get(TargetOpcode::COPY), DstReg)
15771 MI->eraseFromParent();
15775 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15776 // instructions. They will be translated into a spin-loop or compare-exchange
15780 // dst = atomic-fetch-op MI.addr, MI.val
15786 // t1L = LOAD [MI.addr + 0]
15787 // t1H = LOAD [MI.addr + 4]
15789 // t4L = phi(t1L, t3L / loop)
15790 // t4H = phi(t1H, t3H / loop)
15791 // t2L = OP MI.val.lo, t4L
15792 // t2H = OP MI.val.hi, t4H
15797 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15805 MachineBasicBlock *
15806 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15807 MachineBasicBlock *MBB) const {
15808 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15809 DebugLoc DL = MI->getDebugLoc();
15811 MachineFunction *MF = MBB->getParent();
15812 MachineRegisterInfo &MRI = MF->getRegInfo();
15814 const BasicBlock *BB = MBB->getBasicBlock();
15815 MachineFunction::iterator I = MBB;
15818 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15819 "Unexpected number of operands");
15821 assert(MI->hasOneMemOperand() &&
15822 "Expected atomic-load-op32 to have one memoperand");
15824 // Memory Reference
15825 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15826 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15828 unsigned DstLoReg, DstHiReg;
15829 unsigned SrcLoReg, SrcHiReg;
15830 unsigned MemOpndSlot;
15832 unsigned CurOp = 0;
15834 DstLoReg = MI->getOperand(CurOp++).getReg();
15835 DstHiReg = MI->getOperand(CurOp++).getReg();
15836 MemOpndSlot = CurOp;
15837 CurOp += X86::AddrNumOperands;
15838 SrcLoReg = MI->getOperand(CurOp++).getReg();
15839 SrcHiReg = MI->getOperand(CurOp++).getReg();
15841 const TargetRegisterClass *RC = &X86::GR32RegClass;
15842 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15844 unsigned t1L = MRI.createVirtualRegister(RC);
15845 unsigned t1H = MRI.createVirtualRegister(RC);
15846 unsigned t2L = MRI.createVirtualRegister(RC);
15847 unsigned t2H = MRI.createVirtualRegister(RC);
15848 unsigned t3L = MRI.createVirtualRegister(RC);
15849 unsigned t3H = MRI.createVirtualRegister(RC);
15850 unsigned t4L = MRI.createVirtualRegister(RC);
15851 unsigned t4H = MRI.createVirtualRegister(RC);
15853 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15854 unsigned LOADOpc = X86::MOV32rm;
15856 // For the atomic load-arith operator, we generate
15859 // t1L = LOAD [MI.addr + 0]
15860 // t1H = LOAD [MI.addr + 4]
15862 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15863 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15864 // t2L = OP MI.val.lo, t4L
15865 // t2H = OP MI.val.hi, t4H
15868 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15876 MachineBasicBlock *thisMBB = MBB;
15877 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15878 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15879 MF->insert(I, mainMBB);
15880 MF->insert(I, sinkMBB);
15882 MachineInstrBuilder MIB;
15884 // Transfer the remainder of BB and its successor edges to sinkMBB.
15885 sinkMBB->splice(sinkMBB->begin(), MBB,
15886 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15887 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15891 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15892 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15893 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15895 NewMO.setIsKill(false);
15896 MIB.addOperand(NewMO);
15898 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15899 unsigned flags = (*MMOI)->getFlags();
15900 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15901 MachineMemOperand *MMO =
15902 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15903 (*MMOI)->getSize(),
15904 (*MMOI)->getBaseAlignment(),
15905 (*MMOI)->getTBAAInfo(),
15906 (*MMOI)->getRanges());
15907 MIB.addMemOperand(MMO);
15909 MachineInstr *LowMI = MIB;
15912 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15913 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15914 if (i == X86::AddrDisp) {
15915 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15917 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15919 NewMO.setIsKill(false);
15920 MIB.addOperand(NewMO);
15923 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15925 thisMBB->addSuccessor(mainMBB);
15928 MachineBasicBlock *origMainMBB = mainMBB;
15931 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15932 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15933 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15934 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15936 unsigned Opc = MI->getOpcode();
15939 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15940 case X86::ATOMAND6432:
15941 case X86::ATOMOR6432:
15942 case X86::ATOMXOR6432:
15943 case X86::ATOMADD6432:
15944 case X86::ATOMSUB6432: {
15946 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15947 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15949 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15953 case X86::ATOMNAND6432: {
15954 unsigned HiOpc, NOTOpc;
15955 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15956 unsigned TmpL = MRI.createVirtualRegister(RC);
15957 unsigned TmpH = MRI.createVirtualRegister(RC);
15958 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15960 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15962 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15963 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15966 case X86::ATOMMAX6432:
15967 case X86::ATOMMIN6432:
15968 case X86::ATOMUMAX6432:
15969 case X86::ATOMUMIN6432: {
15971 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15972 unsigned cL = MRI.createVirtualRegister(RC8);
15973 unsigned cH = MRI.createVirtualRegister(RC8);
15974 unsigned cL32 = MRI.createVirtualRegister(RC);
15975 unsigned cH32 = MRI.createVirtualRegister(RC);
15976 unsigned cc = MRI.createVirtualRegister(RC);
15977 // cl := cmp src_lo, lo
15978 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15979 .addReg(SrcLoReg).addReg(t4L);
15980 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15981 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15982 // ch := cmp src_hi, hi
15983 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15984 .addReg(SrcHiReg).addReg(t4H);
15985 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15986 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15987 // cc := if (src_hi == hi) ? cl : ch;
15988 if (Subtarget->hasCMov()) {
15989 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15990 .addReg(cH32).addReg(cL32);
15992 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15993 .addReg(cH32).addReg(cL32)
15994 .addImm(X86::COND_E);
15995 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15997 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15998 if (Subtarget->hasCMov()) {
15999 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16000 .addReg(SrcLoReg).addReg(t4L);
16001 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16002 .addReg(SrcHiReg).addReg(t4H);
16004 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16005 .addReg(SrcLoReg).addReg(t4L)
16006 .addImm(X86::COND_NE);
16007 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16008 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16009 // 2nd CMOV lowering.
16010 mainMBB->addLiveIn(X86::EFLAGS);
16011 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16012 .addReg(SrcHiReg).addReg(t4H)
16013 .addImm(X86::COND_NE);
16014 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16015 // Replace the original PHI node as mainMBB is changed after CMOV
16017 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16018 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16019 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16020 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16021 PhiL->eraseFromParent();
16022 PhiH->eraseFromParent();
16026 case X86::ATOMSWAP6432: {
16028 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16029 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16030 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16035 // Copy EDX:EAX back from HiReg:LoReg
16036 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16037 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16038 // Copy ECX:EBX from t1H:t1L
16039 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16040 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16042 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16043 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16044 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16046 NewMO.setIsKill(false);
16047 MIB.addOperand(NewMO);
16049 MIB.setMemRefs(MMOBegin, MMOEnd);
16051 // Copy EDX:EAX back to t3H:t3L
16052 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16053 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16055 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16057 mainMBB->addSuccessor(origMainMBB);
16058 mainMBB->addSuccessor(sinkMBB);
16061 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16062 TII->get(TargetOpcode::COPY), DstLoReg)
16064 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16065 TII->get(TargetOpcode::COPY), DstHiReg)
16068 MI->eraseFromParent();
16072 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16073 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16074 // in the .td file.
16075 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16076 const TargetInstrInfo *TII) {
16078 switch (MI->getOpcode()) {
16079 default: llvm_unreachable("illegal opcode!");
16080 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16081 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16082 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16083 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16084 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16085 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16086 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16087 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16090 DebugLoc dl = MI->getDebugLoc();
16091 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16093 unsigned NumArgs = MI->getNumOperands();
16094 for (unsigned i = 1; i < NumArgs; ++i) {
16095 MachineOperand &Op = MI->getOperand(i);
16096 if (!(Op.isReg() && Op.isImplicit()))
16097 MIB.addOperand(Op);
16099 if (MI->hasOneMemOperand())
16100 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16102 BuildMI(*BB, MI, dl,
16103 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16104 .addReg(X86::XMM0);
16106 MI->eraseFromParent();
16110 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16111 // defs in an instruction pattern
16112 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16113 const TargetInstrInfo *TII) {
16115 switch (MI->getOpcode()) {
16116 default: llvm_unreachable("illegal opcode!");
16117 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16118 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16119 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16120 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16121 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16122 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16123 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16124 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16127 DebugLoc dl = MI->getDebugLoc();
16128 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16130 unsigned NumArgs = MI->getNumOperands(); // remove the results
16131 for (unsigned i = 1; i < NumArgs; ++i) {
16132 MachineOperand &Op = MI->getOperand(i);
16133 if (!(Op.isReg() && Op.isImplicit()))
16134 MIB.addOperand(Op);
16136 if (MI->hasOneMemOperand())
16137 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16139 BuildMI(*BB, MI, dl,
16140 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16143 MI->eraseFromParent();
16147 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16148 const TargetInstrInfo *TII,
16149 const X86Subtarget* Subtarget) {
16150 DebugLoc dl = MI->getDebugLoc();
16152 // Address into RAX/EAX, other two args into ECX, EDX.
16153 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16154 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16155 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16156 for (int i = 0; i < X86::AddrNumOperands; ++i)
16157 MIB.addOperand(MI->getOperand(i));
16159 unsigned ValOps = X86::AddrNumOperands;
16160 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16161 .addReg(MI->getOperand(ValOps).getReg());
16162 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16163 .addReg(MI->getOperand(ValOps+1).getReg());
16165 // The instruction doesn't actually take any operands though.
16166 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16168 MI->eraseFromParent(); // The pseudo is gone now.
16172 MachineBasicBlock *
16173 X86TargetLowering::EmitVAARG64WithCustomInserter(
16175 MachineBasicBlock *MBB) const {
16176 // Emit va_arg instruction on X86-64.
16178 // Operands to this pseudo-instruction:
16179 // 0 ) Output : destination address (reg)
16180 // 1-5) Input : va_list address (addr, i64mem)
16181 // 6 ) ArgSize : Size (in bytes) of vararg type
16182 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16183 // 8 ) Align : Alignment of type
16184 // 9 ) EFLAGS (implicit-def)
16186 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16187 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16189 unsigned DestReg = MI->getOperand(0).getReg();
16190 MachineOperand &Base = MI->getOperand(1);
16191 MachineOperand &Scale = MI->getOperand(2);
16192 MachineOperand &Index = MI->getOperand(3);
16193 MachineOperand &Disp = MI->getOperand(4);
16194 MachineOperand &Segment = MI->getOperand(5);
16195 unsigned ArgSize = MI->getOperand(6).getImm();
16196 unsigned ArgMode = MI->getOperand(7).getImm();
16197 unsigned Align = MI->getOperand(8).getImm();
16199 // Memory Reference
16200 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16201 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16202 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16204 // Machine Information
16205 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16206 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16207 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16208 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16209 DebugLoc DL = MI->getDebugLoc();
16211 // struct va_list {
16214 // i64 overflow_area (address)
16215 // i64 reg_save_area (address)
16217 // sizeof(va_list) = 24
16218 // alignment(va_list) = 8
16220 unsigned TotalNumIntRegs = 6;
16221 unsigned TotalNumXMMRegs = 8;
16222 bool UseGPOffset = (ArgMode == 1);
16223 bool UseFPOffset = (ArgMode == 2);
16224 unsigned MaxOffset = TotalNumIntRegs * 8 +
16225 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16227 /* Align ArgSize to a multiple of 8 */
16228 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16229 bool NeedsAlign = (Align > 8);
16231 MachineBasicBlock *thisMBB = MBB;
16232 MachineBasicBlock *overflowMBB;
16233 MachineBasicBlock *offsetMBB;
16234 MachineBasicBlock *endMBB;
16236 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16237 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16238 unsigned OffsetReg = 0;
16240 if (!UseGPOffset && !UseFPOffset) {
16241 // If we only pull from the overflow region, we don't create a branch.
16242 // We don't need to alter control flow.
16243 OffsetDestReg = 0; // unused
16244 OverflowDestReg = DestReg;
16246 offsetMBB = nullptr;
16247 overflowMBB = thisMBB;
16250 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16251 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16252 // If not, pull from overflow_area. (branch to overflowMBB)
16257 // offsetMBB overflowMBB
16262 // Registers for the PHI in endMBB
16263 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16264 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16266 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16267 MachineFunction *MF = MBB->getParent();
16268 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16269 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16270 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16272 MachineFunction::iterator MBBIter = MBB;
16275 // Insert the new basic blocks
16276 MF->insert(MBBIter, offsetMBB);
16277 MF->insert(MBBIter, overflowMBB);
16278 MF->insert(MBBIter, endMBB);
16280 // Transfer the remainder of MBB and its successor edges to endMBB.
16281 endMBB->splice(endMBB->begin(), thisMBB,
16282 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16283 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16285 // Make offsetMBB and overflowMBB successors of thisMBB
16286 thisMBB->addSuccessor(offsetMBB);
16287 thisMBB->addSuccessor(overflowMBB);
16289 // endMBB is a successor of both offsetMBB and overflowMBB
16290 offsetMBB->addSuccessor(endMBB);
16291 overflowMBB->addSuccessor(endMBB);
16293 // Load the offset value into a register
16294 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16295 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16299 .addDisp(Disp, UseFPOffset ? 4 : 0)
16300 .addOperand(Segment)
16301 .setMemRefs(MMOBegin, MMOEnd);
16303 // Check if there is enough room left to pull this argument.
16304 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16306 .addImm(MaxOffset + 8 - ArgSizeA8);
16308 // Branch to "overflowMBB" if offset >= max
16309 // Fall through to "offsetMBB" otherwise
16310 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16311 .addMBB(overflowMBB);
16314 // In offsetMBB, emit code to use the reg_save_area.
16316 assert(OffsetReg != 0);
16318 // Read the reg_save_area address.
16319 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16320 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16325 .addOperand(Segment)
16326 .setMemRefs(MMOBegin, MMOEnd);
16328 // Zero-extend the offset
16329 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16330 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16333 .addImm(X86::sub_32bit);
16335 // Add the offset to the reg_save_area to get the final address.
16336 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16337 .addReg(OffsetReg64)
16338 .addReg(RegSaveReg);
16340 // Compute the offset for the next argument
16341 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16342 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16344 .addImm(UseFPOffset ? 16 : 8);
16346 // Store it back into the va_list.
16347 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16351 .addDisp(Disp, UseFPOffset ? 4 : 0)
16352 .addOperand(Segment)
16353 .addReg(NextOffsetReg)
16354 .setMemRefs(MMOBegin, MMOEnd);
16357 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16362 // Emit code to use overflow area
16365 // Load the overflow_area address into a register.
16366 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16367 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16372 .addOperand(Segment)
16373 .setMemRefs(MMOBegin, MMOEnd);
16375 // If we need to align it, do so. Otherwise, just copy the address
16376 // to OverflowDestReg.
16378 // Align the overflow address
16379 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16380 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16382 // aligned_addr = (addr + (align-1)) & ~(align-1)
16383 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16384 .addReg(OverflowAddrReg)
16387 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16389 .addImm(~(uint64_t)(Align-1));
16391 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16392 .addReg(OverflowAddrReg);
16395 // Compute the next overflow address after this argument.
16396 // (the overflow address should be kept 8-byte aligned)
16397 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16398 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16399 .addReg(OverflowDestReg)
16400 .addImm(ArgSizeA8);
16402 // Store the new overflow address.
16403 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16408 .addOperand(Segment)
16409 .addReg(NextAddrReg)
16410 .setMemRefs(MMOBegin, MMOEnd);
16412 // If we branched, emit the PHI to the front of endMBB.
16414 BuildMI(*endMBB, endMBB->begin(), DL,
16415 TII->get(X86::PHI), DestReg)
16416 .addReg(OffsetDestReg).addMBB(offsetMBB)
16417 .addReg(OverflowDestReg).addMBB(overflowMBB);
16420 // Erase the pseudo instruction
16421 MI->eraseFromParent();
16426 MachineBasicBlock *
16427 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16429 MachineBasicBlock *MBB) const {
16430 // Emit code to save XMM registers to the stack. The ABI says that the
16431 // number of registers to save is given in %al, so it's theoretically
16432 // possible to do an indirect jump trick to avoid saving all of them,
16433 // however this code takes a simpler approach and just executes all
16434 // of the stores if %al is non-zero. It's less code, and it's probably
16435 // easier on the hardware branch predictor, and stores aren't all that
16436 // expensive anyway.
16438 // Create the new basic blocks. One block contains all the XMM stores,
16439 // and one block is the final destination regardless of whether any
16440 // stores were performed.
16441 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16442 MachineFunction *F = MBB->getParent();
16443 MachineFunction::iterator MBBIter = MBB;
16445 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16446 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16447 F->insert(MBBIter, XMMSaveMBB);
16448 F->insert(MBBIter, EndMBB);
16450 // Transfer the remainder of MBB and its successor edges to EndMBB.
16451 EndMBB->splice(EndMBB->begin(), MBB,
16452 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16453 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16455 // The original block will now fall through to the XMM save block.
16456 MBB->addSuccessor(XMMSaveMBB);
16457 // The XMMSaveMBB will fall through to the end block.
16458 XMMSaveMBB->addSuccessor(EndMBB);
16460 // Now add the instructions.
16461 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16462 DebugLoc DL = MI->getDebugLoc();
16464 unsigned CountReg = MI->getOperand(0).getReg();
16465 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16466 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16468 if (!Subtarget->isTargetWin64()) {
16469 // If %al is 0, branch around the XMM save block.
16470 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16471 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16472 MBB->addSuccessor(EndMBB);
16475 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16476 // that was just emitted, but clearly shouldn't be "saved".
16477 assert((MI->getNumOperands() <= 3 ||
16478 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16479 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16480 && "Expected last argument to be EFLAGS");
16481 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16482 // In the XMM save block, save all the XMM argument registers.
16483 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16484 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16485 MachineMemOperand *MMO =
16486 F->getMachineMemOperand(
16487 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16488 MachineMemOperand::MOStore,
16489 /*Size=*/16, /*Align=*/16);
16490 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16491 .addFrameIndex(RegSaveFrameIndex)
16492 .addImm(/*Scale=*/1)
16493 .addReg(/*IndexReg=*/0)
16494 .addImm(/*Disp=*/Offset)
16495 .addReg(/*Segment=*/0)
16496 .addReg(MI->getOperand(i).getReg())
16497 .addMemOperand(MMO);
16500 MI->eraseFromParent(); // The pseudo instruction is gone now.
16505 // The EFLAGS operand of SelectItr might be missing a kill marker
16506 // because there were multiple uses of EFLAGS, and ISel didn't know
16507 // which to mark. Figure out whether SelectItr should have had a
16508 // kill marker, and set it if it should. Returns the correct kill
16510 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16511 MachineBasicBlock* BB,
16512 const TargetRegisterInfo* TRI) {
16513 // Scan forward through BB for a use/def of EFLAGS.
16514 MachineBasicBlock::iterator miI(std::next(SelectItr));
16515 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16516 const MachineInstr& mi = *miI;
16517 if (mi.readsRegister(X86::EFLAGS))
16519 if (mi.definesRegister(X86::EFLAGS))
16520 break; // Should have kill-flag - update below.
16523 // If we hit the end of the block, check whether EFLAGS is live into a
16525 if (miI == BB->end()) {
16526 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16527 sEnd = BB->succ_end();
16528 sItr != sEnd; ++sItr) {
16529 MachineBasicBlock* succ = *sItr;
16530 if (succ->isLiveIn(X86::EFLAGS))
16535 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16536 // out. SelectMI should have a kill flag on EFLAGS.
16537 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16541 MachineBasicBlock *
16542 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16543 MachineBasicBlock *BB) const {
16544 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16545 DebugLoc DL = MI->getDebugLoc();
16547 // To "insert" a SELECT_CC instruction, we actually have to insert the
16548 // diamond control-flow pattern. The incoming instruction knows the
16549 // destination vreg to set, the condition code register to branch on, the
16550 // true/false values to select between, and a branch opcode to use.
16551 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16552 MachineFunction::iterator It = BB;
16558 // cmpTY ccX, r1, r2
16560 // fallthrough --> copy0MBB
16561 MachineBasicBlock *thisMBB = BB;
16562 MachineFunction *F = BB->getParent();
16563 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16564 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16565 F->insert(It, copy0MBB);
16566 F->insert(It, sinkMBB);
16568 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16569 // live into the sink and copy blocks.
16570 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16571 if (!MI->killsRegister(X86::EFLAGS) &&
16572 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16573 copy0MBB->addLiveIn(X86::EFLAGS);
16574 sinkMBB->addLiveIn(X86::EFLAGS);
16577 // Transfer the remainder of BB and its successor edges to sinkMBB.
16578 sinkMBB->splice(sinkMBB->begin(), BB,
16579 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16580 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16582 // Add the true and fallthrough blocks as its successors.
16583 BB->addSuccessor(copy0MBB);
16584 BB->addSuccessor(sinkMBB);
16586 // Create the conditional branch instruction.
16588 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16589 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16592 // %FalseValue = ...
16593 // # fallthrough to sinkMBB
16594 copy0MBB->addSuccessor(sinkMBB);
16597 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16599 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16600 TII->get(X86::PHI), MI->getOperand(0).getReg())
16601 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16602 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16604 MI->eraseFromParent(); // The pseudo instruction is gone now.
16608 MachineBasicBlock *
16609 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16610 bool Is64Bit) const {
16611 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16612 DebugLoc DL = MI->getDebugLoc();
16613 MachineFunction *MF = BB->getParent();
16614 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16616 assert(MF->shouldSplitStack());
16618 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16619 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16622 // ... [Till the alloca]
16623 // If stacklet is not large enough, jump to mallocMBB
16626 // Allocate by subtracting from RSP
16627 // Jump to continueMBB
16630 // Allocate by call to runtime
16634 // [rest of original BB]
16637 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16638 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16639 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16641 MachineRegisterInfo &MRI = MF->getRegInfo();
16642 const TargetRegisterClass *AddrRegClass =
16643 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16645 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16646 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16647 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16648 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16649 sizeVReg = MI->getOperand(1).getReg(),
16650 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16652 MachineFunction::iterator MBBIter = BB;
16655 MF->insert(MBBIter, bumpMBB);
16656 MF->insert(MBBIter, mallocMBB);
16657 MF->insert(MBBIter, continueMBB);
16659 continueMBB->splice(continueMBB->begin(), BB,
16660 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16661 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16663 // Add code to the main basic block to check if the stack limit has been hit,
16664 // and if so, jump to mallocMBB otherwise to bumpMBB.
16665 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16666 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16667 .addReg(tmpSPVReg).addReg(sizeVReg);
16668 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16669 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16670 .addReg(SPLimitVReg);
16671 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16673 // bumpMBB simply decreases the stack pointer, since we know the current
16674 // stacklet has enough space.
16675 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16676 .addReg(SPLimitVReg);
16677 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16678 .addReg(SPLimitVReg);
16679 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16681 // Calls into a routine in libgcc to allocate more space from the heap.
16682 const uint32_t *RegMask =
16683 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16685 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16687 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16688 .addExternalSymbol("__morestack_allocate_stack_space")
16689 .addRegMask(RegMask)
16690 .addReg(X86::RDI, RegState::Implicit)
16691 .addReg(X86::RAX, RegState::ImplicitDefine);
16693 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16695 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16696 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16697 .addExternalSymbol("__morestack_allocate_stack_space")
16698 .addRegMask(RegMask)
16699 .addReg(X86::EAX, RegState::ImplicitDefine);
16703 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16706 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16707 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16708 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16710 // Set up the CFG correctly.
16711 BB->addSuccessor(bumpMBB);
16712 BB->addSuccessor(mallocMBB);
16713 mallocMBB->addSuccessor(continueMBB);
16714 bumpMBB->addSuccessor(continueMBB);
16716 // Take care of the PHI nodes.
16717 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16718 MI->getOperand(0).getReg())
16719 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16720 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16722 // Delete the original pseudo instruction.
16723 MI->eraseFromParent();
16726 return continueMBB;
16729 MachineBasicBlock *
16730 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16731 MachineBasicBlock *BB) const {
16732 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16733 DebugLoc DL = MI->getDebugLoc();
16735 assert(!Subtarget->isTargetMacho());
16737 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16738 // non-trivial part is impdef of ESP.
16740 if (Subtarget->isTargetWin64()) {
16741 if (Subtarget->isTargetCygMing()) {
16742 // ___chkstk(Mingw64):
16743 // Clobbers R10, R11, RAX and EFLAGS.
16745 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16746 .addExternalSymbol("___chkstk")
16747 .addReg(X86::RAX, RegState::Implicit)
16748 .addReg(X86::RSP, RegState::Implicit)
16749 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16750 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16751 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16753 // __chkstk(MSVCRT): does not update stack pointer.
16754 // Clobbers R10, R11 and EFLAGS.
16755 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16756 .addExternalSymbol("__chkstk")
16757 .addReg(X86::RAX, RegState::Implicit)
16758 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16759 // RAX has the offset to be subtracted from RSP.
16760 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16765 const char *StackProbeSymbol =
16766 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16768 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16769 .addExternalSymbol(StackProbeSymbol)
16770 .addReg(X86::EAX, RegState::Implicit)
16771 .addReg(X86::ESP, RegState::Implicit)
16772 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16773 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16774 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16777 MI->eraseFromParent(); // The pseudo instruction is gone now.
16781 MachineBasicBlock *
16782 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16783 MachineBasicBlock *BB) const {
16784 // This is pretty easy. We're taking the value that we received from
16785 // our load from the relocation, sticking it in either RDI (x86-64)
16786 // or EAX and doing an indirect call. The return value will then
16787 // be in the normal return register.
16788 const X86InstrInfo *TII
16789 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16790 DebugLoc DL = MI->getDebugLoc();
16791 MachineFunction *F = BB->getParent();
16793 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16794 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16796 // Get a register mask for the lowered call.
16797 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16798 // proper register mask.
16799 const uint32_t *RegMask =
16800 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16801 if (Subtarget->is64Bit()) {
16802 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16803 TII->get(X86::MOV64rm), X86::RDI)
16805 .addImm(0).addReg(0)
16806 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16807 MI->getOperand(3).getTargetFlags())
16809 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16810 addDirectMem(MIB, X86::RDI);
16811 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16812 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16813 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16814 TII->get(X86::MOV32rm), X86::EAX)
16816 .addImm(0).addReg(0)
16817 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16818 MI->getOperand(3).getTargetFlags())
16820 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16821 addDirectMem(MIB, X86::EAX);
16822 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16824 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16825 TII->get(X86::MOV32rm), X86::EAX)
16826 .addReg(TII->getGlobalBaseReg(F))
16827 .addImm(0).addReg(0)
16828 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16829 MI->getOperand(3).getTargetFlags())
16831 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16832 addDirectMem(MIB, X86::EAX);
16833 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16836 MI->eraseFromParent(); // The pseudo instruction is gone now.
16840 MachineBasicBlock *
16841 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16842 MachineBasicBlock *MBB) const {
16843 DebugLoc DL = MI->getDebugLoc();
16844 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16846 MachineFunction *MF = MBB->getParent();
16847 MachineRegisterInfo &MRI = MF->getRegInfo();
16849 const BasicBlock *BB = MBB->getBasicBlock();
16850 MachineFunction::iterator I = MBB;
16853 // Memory Reference
16854 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16855 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16858 unsigned MemOpndSlot = 0;
16860 unsigned CurOp = 0;
16862 DstReg = MI->getOperand(CurOp++).getReg();
16863 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16864 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16865 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16866 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16868 MemOpndSlot = CurOp;
16870 MVT PVT = getPointerTy();
16871 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16872 "Invalid Pointer Size!");
16874 // For v = setjmp(buf), we generate
16877 // buf[LabelOffset] = restoreMBB
16878 // SjLjSetup restoreMBB
16884 // v = phi(main, restore)
16889 MachineBasicBlock *thisMBB = MBB;
16890 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16891 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16892 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16893 MF->insert(I, mainMBB);
16894 MF->insert(I, sinkMBB);
16895 MF->push_back(restoreMBB);
16897 MachineInstrBuilder MIB;
16899 // Transfer the remainder of BB and its successor edges to sinkMBB.
16900 sinkMBB->splice(sinkMBB->begin(), MBB,
16901 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16902 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16905 unsigned PtrStoreOpc = 0;
16906 unsigned LabelReg = 0;
16907 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16908 Reloc::Model RM = getTargetMachine().getRelocationModel();
16909 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16910 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16912 // Prepare IP either in reg or imm.
16913 if (!UseImmLabel) {
16914 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16915 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16916 LabelReg = MRI.createVirtualRegister(PtrRC);
16917 if (Subtarget->is64Bit()) {
16918 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16922 .addMBB(restoreMBB)
16925 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16926 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16927 .addReg(XII->getGlobalBaseReg(MF))
16930 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16934 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16936 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16937 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16938 if (i == X86::AddrDisp)
16939 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16941 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16944 MIB.addReg(LabelReg);
16946 MIB.addMBB(restoreMBB);
16947 MIB.setMemRefs(MMOBegin, MMOEnd);
16949 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16950 .addMBB(restoreMBB);
16952 const X86RegisterInfo *RegInfo =
16953 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16954 MIB.addRegMask(RegInfo->getNoPreservedMask());
16955 thisMBB->addSuccessor(mainMBB);
16956 thisMBB->addSuccessor(restoreMBB);
16960 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16961 mainMBB->addSuccessor(sinkMBB);
16964 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16965 TII->get(X86::PHI), DstReg)
16966 .addReg(mainDstReg).addMBB(mainMBB)
16967 .addReg(restoreDstReg).addMBB(restoreMBB);
16970 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16971 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16972 restoreMBB->addSuccessor(sinkMBB);
16974 MI->eraseFromParent();
16978 MachineBasicBlock *
16979 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16980 MachineBasicBlock *MBB) const {
16981 DebugLoc DL = MI->getDebugLoc();
16982 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16984 MachineFunction *MF = MBB->getParent();
16985 MachineRegisterInfo &MRI = MF->getRegInfo();
16987 // Memory Reference
16988 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16989 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16991 MVT PVT = getPointerTy();
16992 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16993 "Invalid Pointer Size!");
16995 const TargetRegisterClass *RC =
16996 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16997 unsigned Tmp = MRI.createVirtualRegister(RC);
16998 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16999 const X86RegisterInfo *RegInfo =
17000 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
17001 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17002 unsigned SP = RegInfo->getStackRegister();
17004 MachineInstrBuilder MIB;
17006 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17007 const int64_t SPOffset = 2 * PVT.getStoreSize();
17009 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17010 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17013 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17014 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17015 MIB.addOperand(MI->getOperand(i));
17016 MIB.setMemRefs(MMOBegin, MMOEnd);
17018 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17019 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17020 if (i == X86::AddrDisp)
17021 MIB.addDisp(MI->getOperand(i), LabelOffset);
17023 MIB.addOperand(MI->getOperand(i));
17025 MIB.setMemRefs(MMOBegin, MMOEnd);
17027 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17028 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17029 if (i == X86::AddrDisp)
17030 MIB.addDisp(MI->getOperand(i), SPOffset);
17032 MIB.addOperand(MI->getOperand(i));
17034 MIB.setMemRefs(MMOBegin, MMOEnd);
17036 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17038 MI->eraseFromParent();
17042 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17043 // accumulator loops. Writing back to the accumulator allows the coalescer
17044 // to remove extra copies in the loop.
17045 MachineBasicBlock *
17046 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17047 MachineBasicBlock *MBB) const {
17048 MachineOperand &AddendOp = MI->getOperand(3);
17050 // Bail out early if the addend isn't a register - we can't switch these.
17051 if (!AddendOp.isReg())
17054 MachineFunction &MF = *MBB->getParent();
17055 MachineRegisterInfo &MRI = MF.getRegInfo();
17057 // Check whether the addend is defined by a PHI:
17058 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17059 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17060 if (!AddendDef.isPHI())
17063 // Look for the following pattern:
17065 // %addend = phi [%entry, 0], [%loop, %result]
17067 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17071 // %addend = phi [%entry, 0], [%loop, %result]
17073 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17075 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17076 assert(AddendDef.getOperand(i).isReg());
17077 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17078 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17079 if (&PHISrcInst == MI) {
17080 // Found a matching instruction.
17081 unsigned NewFMAOpc = 0;
17082 switch (MI->getOpcode()) {
17083 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17084 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17085 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17086 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17087 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17088 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17089 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17090 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17091 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17092 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17093 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17094 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17095 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17096 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17097 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17098 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17099 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17100 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17101 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17102 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17103 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17104 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17105 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17106 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17107 default: llvm_unreachable("Unrecognized FMA variant.");
17110 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17111 MachineInstrBuilder MIB =
17112 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17113 .addOperand(MI->getOperand(0))
17114 .addOperand(MI->getOperand(3))
17115 .addOperand(MI->getOperand(2))
17116 .addOperand(MI->getOperand(1));
17117 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17118 MI->eraseFromParent();
17125 MachineBasicBlock *
17126 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17127 MachineBasicBlock *BB) const {
17128 switch (MI->getOpcode()) {
17129 default: llvm_unreachable("Unexpected instr type to insert");
17130 case X86::TAILJMPd64:
17131 case X86::TAILJMPr64:
17132 case X86::TAILJMPm64:
17133 llvm_unreachable("TAILJMP64 would not be touched here.");
17134 case X86::TCRETURNdi64:
17135 case X86::TCRETURNri64:
17136 case X86::TCRETURNmi64:
17138 case X86::WIN_ALLOCA:
17139 return EmitLoweredWinAlloca(MI, BB);
17140 case X86::SEG_ALLOCA_32:
17141 return EmitLoweredSegAlloca(MI, BB, false);
17142 case X86::SEG_ALLOCA_64:
17143 return EmitLoweredSegAlloca(MI, BB, true);
17144 case X86::TLSCall_32:
17145 case X86::TLSCall_64:
17146 return EmitLoweredTLSCall(MI, BB);
17147 case X86::CMOV_GR8:
17148 case X86::CMOV_FR32:
17149 case X86::CMOV_FR64:
17150 case X86::CMOV_V4F32:
17151 case X86::CMOV_V2F64:
17152 case X86::CMOV_V2I64:
17153 case X86::CMOV_V8F32:
17154 case X86::CMOV_V4F64:
17155 case X86::CMOV_V4I64:
17156 case X86::CMOV_V16F32:
17157 case X86::CMOV_V8F64:
17158 case X86::CMOV_V8I64:
17159 case X86::CMOV_GR16:
17160 case X86::CMOV_GR32:
17161 case X86::CMOV_RFP32:
17162 case X86::CMOV_RFP64:
17163 case X86::CMOV_RFP80:
17164 return EmitLoweredSelect(MI, BB);
17166 case X86::FP32_TO_INT16_IN_MEM:
17167 case X86::FP32_TO_INT32_IN_MEM:
17168 case X86::FP32_TO_INT64_IN_MEM:
17169 case X86::FP64_TO_INT16_IN_MEM:
17170 case X86::FP64_TO_INT32_IN_MEM:
17171 case X86::FP64_TO_INT64_IN_MEM:
17172 case X86::FP80_TO_INT16_IN_MEM:
17173 case X86::FP80_TO_INT32_IN_MEM:
17174 case X86::FP80_TO_INT64_IN_MEM: {
17175 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17176 DebugLoc DL = MI->getDebugLoc();
17178 // Change the floating point control register to use "round towards zero"
17179 // mode when truncating to an integer value.
17180 MachineFunction *F = BB->getParent();
17181 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17182 addFrameReference(BuildMI(*BB, MI, DL,
17183 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17185 // Load the old value of the high byte of the control word...
17187 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17188 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17191 // Set the high part to be round to zero...
17192 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17195 // Reload the modified control word now...
17196 addFrameReference(BuildMI(*BB, MI, DL,
17197 TII->get(X86::FLDCW16m)), CWFrameIdx);
17199 // Restore the memory image of control word to original value
17200 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17203 // Get the X86 opcode to use.
17205 switch (MI->getOpcode()) {
17206 default: llvm_unreachable("illegal opcode!");
17207 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17208 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17209 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17210 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17211 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17212 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17213 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17214 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17215 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17219 MachineOperand &Op = MI->getOperand(0);
17221 AM.BaseType = X86AddressMode::RegBase;
17222 AM.Base.Reg = Op.getReg();
17224 AM.BaseType = X86AddressMode::FrameIndexBase;
17225 AM.Base.FrameIndex = Op.getIndex();
17227 Op = MI->getOperand(1);
17229 AM.Scale = Op.getImm();
17230 Op = MI->getOperand(2);
17232 AM.IndexReg = Op.getImm();
17233 Op = MI->getOperand(3);
17234 if (Op.isGlobal()) {
17235 AM.GV = Op.getGlobal();
17237 AM.Disp = Op.getImm();
17239 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17240 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17242 // Reload the original control word now.
17243 addFrameReference(BuildMI(*BB, MI, DL,
17244 TII->get(X86::FLDCW16m)), CWFrameIdx);
17246 MI->eraseFromParent(); // The pseudo instruction is gone now.
17249 // String/text processing lowering.
17250 case X86::PCMPISTRM128REG:
17251 case X86::VPCMPISTRM128REG:
17252 case X86::PCMPISTRM128MEM:
17253 case X86::VPCMPISTRM128MEM:
17254 case X86::PCMPESTRM128REG:
17255 case X86::VPCMPESTRM128REG:
17256 case X86::PCMPESTRM128MEM:
17257 case X86::VPCMPESTRM128MEM:
17258 assert(Subtarget->hasSSE42() &&
17259 "Target must have SSE4.2 or AVX features enabled");
17260 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17262 // String/text processing lowering.
17263 case X86::PCMPISTRIREG:
17264 case X86::VPCMPISTRIREG:
17265 case X86::PCMPISTRIMEM:
17266 case X86::VPCMPISTRIMEM:
17267 case X86::PCMPESTRIREG:
17268 case X86::VPCMPESTRIREG:
17269 case X86::PCMPESTRIMEM:
17270 case X86::VPCMPESTRIMEM:
17271 assert(Subtarget->hasSSE42() &&
17272 "Target must have SSE4.2 or AVX features enabled");
17273 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17275 // Thread synchronization.
17277 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17281 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17283 // Atomic Lowering.
17284 case X86::ATOMAND8:
17285 case X86::ATOMAND16:
17286 case X86::ATOMAND32:
17287 case X86::ATOMAND64:
17290 case X86::ATOMOR16:
17291 case X86::ATOMOR32:
17292 case X86::ATOMOR64:
17294 case X86::ATOMXOR16:
17295 case X86::ATOMXOR8:
17296 case X86::ATOMXOR32:
17297 case X86::ATOMXOR64:
17299 case X86::ATOMNAND8:
17300 case X86::ATOMNAND16:
17301 case X86::ATOMNAND32:
17302 case X86::ATOMNAND64:
17304 case X86::ATOMMAX8:
17305 case X86::ATOMMAX16:
17306 case X86::ATOMMAX32:
17307 case X86::ATOMMAX64:
17309 case X86::ATOMMIN8:
17310 case X86::ATOMMIN16:
17311 case X86::ATOMMIN32:
17312 case X86::ATOMMIN64:
17314 case X86::ATOMUMAX8:
17315 case X86::ATOMUMAX16:
17316 case X86::ATOMUMAX32:
17317 case X86::ATOMUMAX64:
17319 case X86::ATOMUMIN8:
17320 case X86::ATOMUMIN16:
17321 case X86::ATOMUMIN32:
17322 case X86::ATOMUMIN64:
17323 return EmitAtomicLoadArith(MI, BB);
17325 // This group does 64-bit operations on a 32-bit host.
17326 case X86::ATOMAND6432:
17327 case X86::ATOMOR6432:
17328 case X86::ATOMXOR6432:
17329 case X86::ATOMNAND6432:
17330 case X86::ATOMADD6432:
17331 case X86::ATOMSUB6432:
17332 case X86::ATOMMAX6432:
17333 case X86::ATOMMIN6432:
17334 case X86::ATOMUMAX6432:
17335 case X86::ATOMUMIN6432:
17336 case X86::ATOMSWAP6432:
17337 return EmitAtomicLoadArith6432(MI, BB);
17339 case X86::VASTART_SAVE_XMM_REGS:
17340 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17342 case X86::VAARG_64:
17343 return EmitVAARG64WithCustomInserter(MI, BB);
17345 case X86::EH_SjLj_SetJmp32:
17346 case X86::EH_SjLj_SetJmp64:
17347 return emitEHSjLjSetJmp(MI, BB);
17349 case X86::EH_SjLj_LongJmp32:
17350 case X86::EH_SjLj_LongJmp64:
17351 return emitEHSjLjLongJmp(MI, BB);
17353 case TargetOpcode::STACKMAP:
17354 case TargetOpcode::PATCHPOINT:
17355 return emitPatchPoint(MI, BB);
17357 case X86::VFMADDPDr213r:
17358 case X86::VFMADDPSr213r:
17359 case X86::VFMADDSDr213r:
17360 case X86::VFMADDSSr213r:
17361 case X86::VFMSUBPDr213r:
17362 case X86::VFMSUBPSr213r:
17363 case X86::VFMSUBSDr213r:
17364 case X86::VFMSUBSSr213r:
17365 case X86::VFNMADDPDr213r:
17366 case X86::VFNMADDPSr213r:
17367 case X86::VFNMADDSDr213r:
17368 case X86::VFNMADDSSr213r:
17369 case X86::VFNMSUBPDr213r:
17370 case X86::VFNMSUBPSr213r:
17371 case X86::VFNMSUBSDr213r:
17372 case X86::VFNMSUBSSr213r:
17373 case X86::VFMADDPDr213rY:
17374 case X86::VFMADDPSr213rY:
17375 case X86::VFMSUBPDr213rY:
17376 case X86::VFMSUBPSr213rY:
17377 case X86::VFNMADDPDr213rY:
17378 case X86::VFNMADDPSr213rY:
17379 case X86::VFNMSUBPDr213rY:
17380 case X86::VFNMSUBPSr213rY:
17381 return emitFMA3Instr(MI, BB);
17385 //===----------------------------------------------------------------------===//
17386 // X86 Optimization Hooks
17387 //===----------------------------------------------------------------------===//
17389 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17392 const SelectionDAG &DAG,
17393 unsigned Depth) const {
17394 unsigned BitWidth = KnownZero.getBitWidth();
17395 unsigned Opc = Op.getOpcode();
17396 assert((Opc >= ISD::BUILTIN_OP_END ||
17397 Opc == ISD::INTRINSIC_WO_CHAIN ||
17398 Opc == ISD::INTRINSIC_W_CHAIN ||
17399 Opc == ISD::INTRINSIC_VOID) &&
17400 "Should use MaskedValueIsZero if you don't know whether Op"
17401 " is a target node!");
17403 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17417 // These nodes' second result is a boolean.
17418 if (Op.getResNo() == 0)
17421 case X86ISD::SETCC:
17422 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17424 case ISD::INTRINSIC_WO_CHAIN: {
17425 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17426 unsigned NumLoBits = 0;
17429 case Intrinsic::x86_sse_movmsk_ps:
17430 case Intrinsic::x86_avx_movmsk_ps_256:
17431 case Intrinsic::x86_sse2_movmsk_pd:
17432 case Intrinsic::x86_avx_movmsk_pd_256:
17433 case Intrinsic::x86_mmx_pmovmskb:
17434 case Intrinsic::x86_sse2_pmovmskb_128:
17435 case Intrinsic::x86_avx2_pmovmskb: {
17436 // High bits of movmskp{s|d}, pmovmskb are known zero.
17438 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17439 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17440 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17441 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17442 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17443 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17444 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17445 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17447 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17456 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17458 const SelectionDAG &,
17459 unsigned Depth) const {
17460 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17461 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17462 return Op.getValueType().getScalarType().getSizeInBits();
17468 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17469 /// node is a GlobalAddress + offset.
17470 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17471 const GlobalValue* &GA,
17472 int64_t &Offset) const {
17473 if (N->getOpcode() == X86ISD::Wrapper) {
17474 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17475 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17476 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17480 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17483 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17484 /// same as extracting the high 128-bit part of 256-bit vector and then
17485 /// inserting the result into the low part of a new 256-bit vector
17486 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17487 EVT VT = SVOp->getValueType(0);
17488 unsigned NumElems = VT.getVectorNumElements();
17490 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17491 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17492 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17493 SVOp->getMaskElt(j) >= 0)
17499 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17500 /// same as extracting the low 128-bit part of 256-bit vector and then
17501 /// inserting the result into the high part of a new 256-bit vector
17502 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17503 EVT VT = SVOp->getValueType(0);
17504 unsigned NumElems = VT.getVectorNumElements();
17506 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17507 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17508 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17509 SVOp->getMaskElt(j) >= 0)
17515 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17516 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17517 TargetLowering::DAGCombinerInfo &DCI,
17518 const X86Subtarget* Subtarget) {
17520 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17521 SDValue V1 = SVOp->getOperand(0);
17522 SDValue V2 = SVOp->getOperand(1);
17523 EVT VT = SVOp->getValueType(0);
17524 unsigned NumElems = VT.getVectorNumElements();
17526 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17527 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17531 // V UNDEF BUILD_VECTOR UNDEF
17533 // CONCAT_VECTOR CONCAT_VECTOR
17536 // RESULT: V + zero extended
17538 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17539 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17540 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17543 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17546 // To match the shuffle mask, the first half of the mask should
17547 // be exactly the first vector, and all the rest a splat with the
17548 // first element of the second one.
17549 for (unsigned i = 0; i != NumElems/2; ++i)
17550 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17551 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17554 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17555 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17556 if (Ld->hasNUsesOfValue(1, 0)) {
17557 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17558 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17560 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17562 Ld->getPointerInfo(),
17563 Ld->getAlignment(),
17564 false/*isVolatile*/, true/*ReadMem*/,
17565 false/*WriteMem*/);
17567 // Make sure the newly-created LOAD is in the same position as Ld in
17568 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17569 // and update uses of Ld's output chain to use the TokenFactor.
17570 if (Ld->hasAnyUseOfValue(1)) {
17571 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17572 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17573 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17574 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17575 SDValue(ResNode.getNode(), 1));
17578 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17582 // Emit a zeroed vector and insert the desired subvector on its
17584 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17585 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17586 return DCI.CombineTo(N, InsV);
17589 //===--------------------------------------------------------------------===//
17590 // Combine some shuffles into subvector extracts and inserts:
17593 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17594 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17595 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17596 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17597 return DCI.CombineTo(N, InsV);
17600 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17601 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17602 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17603 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17604 return DCI.CombineTo(N, InsV);
17610 /// PerformShuffleCombine - Performs several different shuffle combines.
17611 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17612 TargetLowering::DAGCombinerInfo &DCI,
17613 const X86Subtarget *Subtarget) {
17615 SDValue N0 = N->getOperand(0);
17616 SDValue N1 = N->getOperand(1);
17617 EVT VT = N->getValueType(0);
17619 // Don't create instructions with illegal types after legalize types has run.
17620 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17621 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17624 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17625 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17626 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17627 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17629 // During Type Legalization, when promoting illegal vector types,
17630 // the backend might introduce new shuffle dag nodes and bitcasts.
17632 // This code performs the following transformation:
17633 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17634 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17636 // We do this only if both the bitcast and the BINOP dag nodes have
17637 // one use. Also, perform this transformation only if the new binary
17638 // operation is legal. This is to avoid introducing dag nodes that
17639 // potentially need to be further expanded (or custom lowered) into a
17640 // less optimal sequence of dag nodes.
17641 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17642 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17643 N0.getOpcode() == ISD::BITCAST) {
17644 SDValue BC0 = N0.getOperand(0);
17645 EVT SVT = BC0.getValueType();
17646 unsigned Opcode = BC0.getOpcode();
17647 unsigned NumElts = VT.getVectorNumElements();
17649 if (BC0.hasOneUse() && SVT.isVector() &&
17650 SVT.getVectorNumElements() * 2 == NumElts &&
17651 TLI.isOperationLegal(Opcode, VT)) {
17652 bool CanFold = false;
17664 unsigned SVTNumElts = SVT.getVectorNumElements();
17665 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17666 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17667 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17668 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17669 CanFold = SVOp->getMaskElt(i) < 0;
17672 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17673 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17674 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17675 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17680 // Only handle 128 wide vector from here on.
17681 if (!VT.is128BitVector())
17684 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17685 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17686 // consecutive, non-overlapping, and in the right order.
17687 SmallVector<SDValue, 16> Elts;
17688 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17689 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17691 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17694 /// PerformTruncateCombine - Converts truncate operation to
17695 /// a sequence of vector shuffle operations.
17696 /// It is possible when we truncate 256-bit vector to 128-bit vector
17697 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17698 TargetLowering::DAGCombinerInfo &DCI,
17699 const X86Subtarget *Subtarget) {
17703 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17704 /// specific shuffle of a load can be folded into a single element load.
17705 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17706 /// shuffles have been customed lowered so we need to handle those here.
17707 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17708 TargetLowering::DAGCombinerInfo &DCI) {
17709 if (DCI.isBeforeLegalizeOps())
17712 SDValue InVec = N->getOperand(0);
17713 SDValue EltNo = N->getOperand(1);
17715 if (!isa<ConstantSDNode>(EltNo))
17718 EVT VT = InVec.getValueType();
17720 bool HasShuffleIntoBitcast = false;
17721 if (InVec.getOpcode() == ISD::BITCAST) {
17722 // Don't duplicate a load with other uses.
17723 if (!InVec.hasOneUse())
17725 EVT BCVT = InVec.getOperand(0).getValueType();
17726 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17728 InVec = InVec.getOperand(0);
17729 HasShuffleIntoBitcast = true;
17732 if (!isTargetShuffle(InVec.getOpcode()))
17735 // Don't duplicate a load with other uses.
17736 if (!InVec.hasOneUse())
17739 SmallVector<int, 16> ShuffleMask;
17741 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17745 // Select the input vector, guarding against out of range extract vector.
17746 unsigned NumElems = VT.getVectorNumElements();
17747 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17748 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17749 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17750 : InVec.getOperand(1);
17752 // If inputs to shuffle are the same for both ops, then allow 2 uses
17753 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17755 if (LdNode.getOpcode() == ISD::BITCAST) {
17756 // Don't duplicate a load with other uses.
17757 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17760 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17761 LdNode = LdNode.getOperand(0);
17764 if (!ISD::isNormalLoad(LdNode.getNode()))
17767 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17769 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17772 if (HasShuffleIntoBitcast) {
17773 // If there's a bitcast before the shuffle, check if the load type and
17774 // alignment is valid.
17775 unsigned Align = LN0->getAlignment();
17776 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17777 unsigned NewAlign = TLI.getDataLayout()->
17778 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17780 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17784 // All checks match so transform back to vector_shuffle so that DAG combiner
17785 // can finish the job
17788 // Create shuffle node taking into account the case that its a unary shuffle
17789 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17790 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17791 InVec.getOperand(0), Shuffle,
17793 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17794 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17798 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17799 /// generation and convert it from being a bunch of shuffles and extracts
17800 /// to a simple store and scalar loads to extract the elements.
17801 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17802 TargetLowering::DAGCombinerInfo &DCI) {
17803 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17804 if (NewOp.getNode())
17807 SDValue InputVector = N->getOperand(0);
17809 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17810 // from mmx to v2i32 has a single usage.
17811 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17812 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17813 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17814 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17815 N->getValueType(0),
17816 InputVector.getNode()->getOperand(0));
17818 // Only operate on vectors of 4 elements, where the alternative shuffling
17819 // gets to be more expensive.
17820 if (InputVector.getValueType() != MVT::v4i32)
17823 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17824 // single use which is a sign-extend or zero-extend, and all elements are
17826 SmallVector<SDNode *, 4> Uses;
17827 unsigned ExtractedElements = 0;
17828 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17829 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17830 if (UI.getUse().getResNo() != InputVector.getResNo())
17833 SDNode *Extract = *UI;
17834 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17837 if (Extract->getValueType(0) != MVT::i32)
17839 if (!Extract->hasOneUse())
17841 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17842 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17844 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17847 // Record which element was extracted.
17848 ExtractedElements |=
17849 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17851 Uses.push_back(Extract);
17854 // If not all the elements were used, this may not be worthwhile.
17855 if (ExtractedElements != 15)
17858 // Ok, we've now decided to do the transformation.
17859 SDLoc dl(InputVector);
17861 // Store the value to a temporary stack slot.
17862 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17863 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17864 MachinePointerInfo(), false, false, 0);
17866 // Replace each use (extract) with a load of the appropriate element.
17867 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17868 UE = Uses.end(); UI != UE; ++UI) {
17869 SDNode *Extract = *UI;
17871 // cOMpute the element's address.
17872 SDValue Idx = Extract->getOperand(1);
17874 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17875 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17877 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17879 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17880 StackPtr, OffsetVal);
17882 // Load the scalar.
17883 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17884 ScalarAddr, MachinePointerInfo(),
17885 false, false, false, 0);
17887 // Replace the exact with the load.
17888 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17891 // The replacement was made in place; don't return anything.
17895 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17896 static std::pair<unsigned, bool>
17897 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17898 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17899 if (!VT.isVector())
17900 return std::make_pair(0, false);
17902 bool NeedSplit = false;
17903 switch (VT.getSimpleVT().SimpleTy) {
17904 default: return std::make_pair(0, false);
17908 if (!Subtarget->hasAVX2())
17910 if (!Subtarget->hasAVX())
17911 return std::make_pair(0, false);
17916 if (!Subtarget->hasSSE2())
17917 return std::make_pair(0, false);
17920 // SSE2 has only a small subset of the operations.
17921 bool hasUnsigned = Subtarget->hasSSE41() ||
17922 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17923 bool hasSigned = Subtarget->hasSSE41() ||
17924 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17926 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17929 // Check for x CC y ? x : y.
17930 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17931 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17936 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17939 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17942 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17945 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17947 // Check for x CC y ? y : x -- a min/max with reversed arms.
17948 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17949 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17954 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17957 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17960 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17963 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17967 return std::make_pair(Opc, NeedSplit);
17971 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17972 const X86Subtarget *Subtarget) {
17974 SDValue Cond = N->getOperand(0);
17975 SDValue LHS = N->getOperand(1);
17976 SDValue RHS = N->getOperand(2);
17978 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17979 SDValue CondSrc = Cond->getOperand(0);
17980 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17981 Cond = CondSrc->getOperand(0);
17984 MVT VT = N->getSimpleValueType(0);
17985 MVT EltVT = VT.getVectorElementType();
17986 unsigned NumElems = VT.getVectorNumElements();
17987 // There is no blend with immediate in AVX-512.
17988 if (VT.is512BitVector())
17991 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17993 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17996 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17999 unsigned MaskValue = 0;
18000 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18003 SmallVector<int, 8> ShuffleMask(NumElems, -1);
18004 for (unsigned i = 0; i < NumElems; ++i) {
18005 // Be sure we emit undef where we can.
18006 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18007 ShuffleMask[i] = -1;
18009 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18012 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18015 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18017 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18018 TargetLowering::DAGCombinerInfo &DCI,
18019 const X86Subtarget *Subtarget) {
18021 SDValue Cond = N->getOperand(0);
18022 // Get the LHS/RHS of the select.
18023 SDValue LHS = N->getOperand(1);
18024 SDValue RHS = N->getOperand(2);
18025 EVT VT = LHS.getValueType();
18026 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18028 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18029 // instructions match the semantics of the common C idiom x<y?x:y but not
18030 // x<=y?x:y, because of how they handle negative zero (which can be
18031 // ignored in unsafe-math mode).
18032 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18033 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18034 (Subtarget->hasSSE2() ||
18035 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18036 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18038 unsigned Opcode = 0;
18039 // Check for x CC y ? x : y.
18040 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18041 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18045 // Converting this to a min would handle NaNs incorrectly, and swapping
18046 // the operands would cause it to handle comparisons between positive
18047 // and negative zero incorrectly.
18048 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18049 if (!DAG.getTarget().Options.UnsafeFPMath &&
18050 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18052 std::swap(LHS, RHS);
18054 Opcode = X86ISD::FMIN;
18057 // Converting this to a min would handle comparisons between positive
18058 // and negative zero incorrectly.
18059 if (!DAG.getTarget().Options.UnsafeFPMath &&
18060 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18062 Opcode = X86ISD::FMIN;
18065 // Converting this to a min would handle both negative zeros and NaNs
18066 // incorrectly, but we can swap the operands to fix both.
18067 std::swap(LHS, RHS);
18071 Opcode = X86ISD::FMIN;
18075 // Converting this to a max would handle comparisons between positive
18076 // and negative zero incorrectly.
18077 if (!DAG.getTarget().Options.UnsafeFPMath &&
18078 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18080 Opcode = X86ISD::FMAX;
18083 // Converting this to a max would handle NaNs incorrectly, and swapping
18084 // the operands would cause it to handle comparisons between positive
18085 // and negative zero incorrectly.
18086 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18087 if (!DAG.getTarget().Options.UnsafeFPMath &&
18088 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18090 std::swap(LHS, RHS);
18092 Opcode = X86ISD::FMAX;
18095 // Converting this to a max would handle both negative zeros and NaNs
18096 // incorrectly, but we can swap the operands to fix both.
18097 std::swap(LHS, RHS);
18101 Opcode = X86ISD::FMAX;
18104 // Check for x CC y ? y : x -- a min/max with reversed arms.
18105 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18106 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18110 // Converting this to a min would handle comparisons between positive
18111 // and negative zero incorrectly, and swapping the operands would
18112 // cause it to handle NaNs incorrectly.
18113 if (!DAG.getTarget().Options.UnsafeFPMath &&
18114 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18115 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18117 std::swap(LHS, RHS);
18119 Opcode = X86ISD::FMIN;
18122 // Converting this to a min would handle NaNs incorrectly.
18123 if (!DAG.getTarget().Options.UnsafeFPMath &&
18124 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18126 Opcode = X86ISD::FMIN;
18129 // Converting this to a min would handle both negative zeros and NaNs
18130 // incorrectly, but we can swap the operands to fix both.
18131 std::swap(LHS, RHS);
18135 Opcode = X86ISD::FMIN;
18139 // Converting this to a max would handle NaNs incorrectly.
18140 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18142 Opcode = X86ISD::FMAX;
18145 // Converting this to a max would handle comparisons between positive
18146 // and negative zero incorrectly, and swapping the operands would
18147 // cause it to handle NaNs incorrectly.
18148 if (!DAG.getTarget().Options.UnsafeFPMath &&
18149 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18150 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18152 std::swap(LHS, RHS);
18154 Opcode = X86ISD::FMAX;
18157 // Converting this to a max would handle both negative zeros and NaNs
18158 // incorrectly, but we can swap the operands to fix both.
18159 std::swap(LHS, RHS);
18163 Opcode = X86ISD::FMAX;
18169 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18172 EVT CondVT = Cond.getValueType();
18173 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18174 CondVT.getVectorElementType() == MVT::i1) {
18175 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18176 // lowering on AVX-512. In this case we convert it to
18177 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18178 // The same situation for all 128 and 256-bit vectors of i8 and i16
18179 EVT OpVT = LHS.getValueType();
18180 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18181 (OpVT.getVectorElementType() == MVT::i8 ||
18182 OpVT.getVectorElementType() == MVT::i16)) {
18183 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18184 DCI.AddToWorklist(Cond.getNode());
18185 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18188 // If this is a select between two integer constants, try to do some
18190 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18191 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18192 // Don't do this for crazy integer types.
18193 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18194 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18195 // so that TrueC (the true value) is larger than FalseC.
18196 bool NeedsCondInvert = false;
18198 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18199 // Efficiently invertible.
18200 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18201 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18202 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18203 NeedsCondInvert = true;
18204 std::swap(TrueC, FalseC);
18207 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18208 if (FalseC->getAPIntValue() == 0 &&
18209 TrueC->getAPIntValue().isPowerOf2()) {
18210 if (NeedsCondInvert) // Invert the condition if needed.
18211 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18212 DAG.getConstant(1, Cond.getValueType()));
18214 // Zero extend the condition if needed.
18215 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18217 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18218 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18219 DAG.getConstant(ShAmt, MVT::i8));
18222 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18223 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18224 if (NeedsCondInvert) // Invert the condition if needed.
18225 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18226 DAG.getConstant(1, Cond.getValueType()));
18228 // Zero extend the condition if needed.
18229 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18230 FalseC->getValueType(0), Cond);
18231 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18232 SDValue(FalseC, 0));
18235 // Optimize cases that will turn into an LEA instruction. This requires
18236 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18237 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18238 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18239 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18241 bool isFastMultiplier = false;
18243 switch ((unsigned char)Diff) {
18245 case 1: // result = add base, cond
18246 case 2: // result = lea base( , cond*2)
18247 case 3: // result = lea base(cond, cond*2)
18248 case 4: // result = lea base( , cond*4)
18249 case 5: // result = lea base(cond, cond*4)
18250 case 8: // result = lea base( , cond*8)
18251 case 9: // result = lea base(cond, cond*8)
18252 isFastMultiplier = true;
18257 if (isFastMultiplier) {
18258 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18259 if (NeedsCondInvert) // Invert the condition if needed.
18260 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18261 DAG.getConstant(1, Cond.getValueType()));
18263 // Zero extend the condition if needed.
18264 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18266 // Scale the condition by the difference.
18268 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18269 DAG.getConstant(Diff, Cond.getValueType()));
18271 // Add the base if non-zero.
18272 if (FalseC->getAPIntValue() != 0)
18273 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18274 SDValue(FalseC, 0));
18281 // Canonicalize max and min:
18282 // (x > y) ? x : y -> (x >= y) ? x : y
18283 // (x < y) ? x : y -> (x <= y) ? x : y
18284 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18285 // the need for an extra compare
18286 // against zero. e.g.
18287 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18289 // testl %edi, %edi
18291 // cmovgl %edi, %eax
18295 // cmovsl %eax, %edi
18296 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18297 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18298 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18299 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18304 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18305 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18306 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18307 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18312 // Early exit check
18313 if (!TLI.isTypeLegal(VT))
18316 // Match VSELECTs into subs with unsigned saturation.
18317 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18318 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18319 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18320 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18321 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18323 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18324 // left side invert the predicate to simplify logic below.
18326 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18328 CC = ISD::getSetCCInverse(CC, true);
18329 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18333 if (Other.getNode() && Other->getNumOperands() == 2 &&
18334 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18335 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18336 SDValue CondRHS = Cond->getOperand(1);
18338 // Look for a general sub with unsigned saturation first.
18339 // x >= y ? x-y : 0 --> subus x, y
18340 // x > y ? x-y : 0 --> subus x, y
18341 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18342 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18343 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18345 // If the RHS is a constant we have to reverse the const canonicalization.
18346 // x > C-1 ? x+-C : 0 --> subus x, C
18347 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18348 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18349 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18350 if (CondRHS.getConstantOperandVal(0) == -A-1)
18351 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18352 DAG.getConstant(-A, VT));
18355 // Another special case: If C was a sign bit, the sub has been
18356 // canonicalized into a xor.
18357 // FIXME: Would it be better to use computeKnownBits to determine whether
18358 // it's safe to decanonicalize the xor?
18359 // x s< 0 ? x^C : 0 --> subus x, C
18360 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18361 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18362 isSplatVector(OpRHS.getNode())) {
18363 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18365 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18370 // Try to match a min/max vector operation.
18371 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18372 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18373 unsigned Opc = ret.first;
18374 bool NeedSplit = ret.second;
18376 if (Opc && NeedSplit) {
18377 unsigned NumElems = VT.getVectorNumElements();
18378 // Extract the LHS vectors
18379 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18380 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18382 // Extract the RHS vectors
18383 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18384 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18386 // Create min/max for each subvector
18387 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18388 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18390 // Merge the result
18391 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18393 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18396 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18397 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18398 // Check if SETCC has already been promoted
18399 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18400 // Check that condition value type matches vselect operand type
18403 assert(Cond.getValueType().isVector() &&
18404 "vector select expects a vector selector!");
18406 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18407 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18409 if (!TValIsAllOnes && !FValIsAllZeros) {
18410 // Try invert the condition if true value is not all 1s and false value
18412 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18413 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18415 if (TValIsAllZeros || FValIsAllOnes) {
18416 SDValue CC = Cond.getOperand(2);
18417 ISD::CondCode NewCC =
18418 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18419 Cond.getOperand(0).getValueType().isInteger());
18420 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18421 std::swap(LHS, RHS);
18422 TValIsAllOnes = FValIsAllOnes;
18423 FValIsAllZeros = TValIsAllZeros;
18427 if (TValIsAllOnes || FValIsAllZeros) {
18430 if (TValIsAllOnes && FValIsAllZeros)
18432 else if (TValIsAllOnes)
18433 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18434 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18435 else if (FValIsAllZeros)
18436 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18437 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18439 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18443 // Try to fold this VSELECT into a MOVSS/MOVSD
18444 if (N->getOpcode() == ISD::VSELECT &&
18445 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18446 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18447 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18448 bool CanFold = false;
18449 unsigned NumElems = Cond.getNumOperands();
18453 if (isZero(Cond.getOperand(0))) {
18456 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18457 // fold (vselect <0,-1> -> (movsd A, B)
18458 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18459 CanFold = isAllOnes(Cond.getOperand(i));
18460 } else if (isAllOnes(Cond.getOperand(0))) {
18464 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18465 // fold (vselect <-1,0> -> (movsd B, A)
18466 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18467 CanFold = isZero(Cond.getOperand(i));
18471 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18472 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18473 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18476 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18477 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18478 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18479 // (v2i64 (bitcast B)))))
18481 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18482 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18483 // (v2f64 (bitcast B)))))
18485 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18486 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18487 // (v2i64 (bitcast A)))))
18489 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18490 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18491 // (v2f64 (bitcast A)))))
18493 CanFold = (isZero(Cond.getOperand(0)) &&
18494 isZero(Cond.getOperand(1)) &&
18495 isAllOnes(Cond.getOperand(2)) &&
18496 isAllOnes(Cond.getOperand(3)));
18498 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18499 isAllOnes(Cond.getOperand(1)) &&
18500 isZero(Cond.getOperand(2)) &&
18501 isZero(Cond.getOperand(3))) {
18503 std::swap(LHS, RHS);
18507 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18508 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18509 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18510 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18512 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18518 // If we know that this node is legal then we know that it is going to be
18519 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18520 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18521 // to simplify previous instructions.
18522 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18523 !DCI.isBeforeLegalize() &&
18524 // We explicitly check against v8i16 and v16i16 because, although
18525 // they're marked as Custom, they might only be legal when Cond is a
18526 // build_vector of constants. This will be taken care in a later
18528 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18529 VT != MVT::v8i16)) {
18530 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18532 // Don't optimize vector selects that map to mask-registers.
18536 // Check all uses of that condition operand to check whether it will be
18537 // consumed by non-BLEND instructions, which may depend on all bits are set
18539 for (SDNode::use_iterator I = Cond->use_begin(),
18540 E = Cond->use_end(); I != E; ++I)
18541 if (I->getOpcode() != ISD::VSELECT)
18542 // TODO: Add other opcodes eventually lowered into BLEND.
18545 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18546 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18548 APInt KnownZero, KnownOne;
18549 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18550 DCI.isBeforeLegalizeOps());
18551 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18552 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18553 DCI.CommitTargetLoweringOpt(TLO);
18556 // We should generate an X86ISD::BLENDI from a vselect if its argument
18557 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18558 // constants. This specific pattern gets generated when we split a
18559 // selector for a 512 bit vector in a machine without AVX512 (but with
18560 // 256-bit vectors), during legalization:
18562 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18564 // Iff we find this pattern and the build_vectors are built from
18565 // constants, we translate the vselect into a shuffle_vector that we
18566 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18567 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18568 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18569 if (Shuffle.getNode())
18576 // Check whether a boolean test is testing a boolean value generated by
18577 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18580 // Simplify the following patterns:
18581 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18582 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18583 // to (Op EFLAGS Cond)
18585 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18586 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18587 // to (Op EFLAGS !Cond)
18589 // where Op could be BRCOND or CMOV.
18591 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18592 // Quit if not CMP and SUB with its value result used.
18593 if (Cmp.getOpcode() != X86ISD::CMP &&
18594 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18597 // Quit if not used as a boolean value.
18598 if (CC != X86::COND_E && CC != X86::COND_NE)
18601 // Check CMP operands. One of them should be 0 or 1 and the other should be
18602 // an SetCC or extended from it.
18603 SDValue Op1 = Cmp.getOperand(0);
18604 SDValue Op2 = Cmp.getOperand(1);
18607 const ConstantSDNode* C = nullptr;
18608 bool needOppositeCond = (CC == X86::COND_E);
18609 bool checkAgainstTrue = false; // Is it a comparison against 1?
18611 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18613 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18615 else // Quit if all operands are not constants.
18618 if (C->getZExtValue() == 1) {
18619 needOppositeCond = !needOppositeCond;
18620 checkAgainstTrue = true;
18621 } else if (C->getZExtValue() != 0)
18622 // Quit if the constant is neither 0 or 1.
18625 bool truncatedToBoolWithAnd = false;
18626 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18627 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18628 SetCC.getOpcode() == ISD::TRUNCATE ||
18629 SetCC.getOpcode() == ISD::AND) {
18630 if (SetCC.getOpcode() == ISD::AND) {
18632 ConstantSDNode *CS;
18633 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18634 CS->getZExtValue() == 1)
18636 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18637 CS->getZExtValue() == 1)
18641 SetCC = SetCC.getOperand(OpIdx);
18642 truncatedToBoolWithAnd = true;
18644 SetCC = SetCC.getOperand(0);
18647 switch (SetCC.getOpcode()) {
18648 case X86ISD::SETCC_CARRY:
18649 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18650 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18651 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18652 // truncated to i1 using 'and'.
18653 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18655 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18656 "Invalid use of SETCC_CARRY!");
18658 case X86ISD::SETCC:
18659 // Set the condition code or opposite one if necessary.
18660 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18661 if (needOppositeCond)
18662 CC = X86::GetOppositeBranchCondition(CC);
18663 return SetCC.getOperand(1);
18664 case X86ISD::CMOV: {
18665 // Check whether false/true value has canonical one, i.e. 0 or 1.
18666 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18667 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18668 // Quit if true value is not a constant.
18671 // Quit if false value is not a constant.
18673 SDValue Op = SetCC.getOperand(0);
18674 // Skip 'zext' or 'trunc' node.
18675 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18676 Op.getOpcode() == ISD::TRUNCATE)
18677 Op = Op.getOperand(0);
18678 // A special case for rdrand/rdseed, where 0 is set if false cond is
18680 if ((Op.getOpcode() != X86ISD::RDRAND &&
18681 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18684 // Quit if false value is not the constant 0 or 1.
18685 bool FValIsFalse = true;
18686 if (FVal && FVal->getZExtValue() != 0) {
18687 if (FVal->getZExtValue() != 1)
18689 // If FVal is 1, opposite cond is needed.
18690 needOppositeCond = !needOppositeCond;
18691 FValIsFalse = false;
18693 // Quit if TVal is not the constant opposite of FVal.
18694 if (FValIsFalse && TVal->getZExtValue() != 1)
18696 if (!FValIsFalse && TVal->getZExtValue() != 0)
18698 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18699 if (needOppositeCond)
18700 CC = X86::GetOppositeBranchCondition(CC);
18701 return SetCC.getOperand(3);
18708 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18709 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18710 TargetLowering::DAGCombinerInfo &DCI,
18711 const X86Subtarget *Subtarget) {
18714 // If the flag operand isn't dead, don't touch this CMOV.
18715 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18718 SDValue FalseOp = N->getOperand(0);
18719 SDValue TrueOp = N->getOperand(1);
18720 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18721 SDValue Cond = N->getOperand(3);
18723 if (CC == X86::COND_E || CC == X86::COND_NE) {
18724 switch (Cond.getOpcode()) {
18728 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18729 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18730 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18736 Flags = checkBoolTestSetCCCombine(Cond, CC);
18737 if (Flags.getNode() &&
18738 // Extra check as FCMOV only supports a subset of X86 cond.
18739 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18740 SDValue Ops[] = { FalseOp, TrueOp,
18741 DAG.getConstant(CC, MVT::i8), Flags };
18742 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18745 // If this is a select between two integer constants, try to do some
18746 // optimizations. Note that the operands are ordered the opposite of SELECT
18748 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18749 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18750 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18751 // larger than FalseC (the false value).
18752 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18753 CC = X86::GetOppositeBranchCondition(CC);
18754 std::swap(TrueC, FalseC);
18755 std::swap(TrueOp, FalseOp);
18758 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18759 // This is efficient for any integer data type (including i8/i16) and
18761 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18762 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18763 DAG.getConstant(CC, MVT::i8), Cond);
18765 // Zero extend the condition if needed.
18766 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18768 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18769 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18770 DAG.getConstant(ShAmt, MVT::i8));
18771 if (N->getNumValues() == 2) // Dead flag value?
18772 return DCI.CombineTo(N, Cond, SDValue());
18776 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18777 // for any integer data type, including i8/i16.
18778 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18779 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18780 DAG.getConstant(CC, MVT::i8), Cond);
18782 // Zero extend the condition if needed.
18783 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18784 FalseC->getValueType(0), Cond);
18785 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18786 SDValue(FalseC, 0));
18788 if (N->getNumValues() == 2) // Dead flag value?
18789 return DCI.CombineTo(N, Cond, SDValue());
18793 // Optimize cases that will turn into an LEA instruction. This requires
18794 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18795 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18796 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18797 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18799 bool isFastMultiplier = false;
18801 switch ((unsigned char)Diff) {
18803 case 1: // result = add base, cond
18804 case 2: // result = lea base( , cond*2)
18805 case 3: // result = lea base(cond, cond*2)
18806 case 4: // result = lea base( , cond*4)
18807 case 5: // result = lea base(cond, cond*4)
18808 case 8: // result = lea base( , cond*8)
18809 case 9: // result = lea base(cond, cond*8)
18810 isFastMultiplier = true;
18815 if (isFastMultiplier) {
18816 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18817 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18818 DAG.getConstant(CC, MVT::i8), Cond);
18819 // Zero extend the condition if needed.
18820 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18822 // Scale the condition by the difference.
18824 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18825 DAG.getConstant(Diff, Cond.getValueType()));
18827 // Add the base if non-zero.
18828 if (FalseC->getAPIntValue() != 0)
18829 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18830 SDValue(FalseC, 0));
18831 if (N->getNumValues() == 2) // Dead flag value?
18832 return DCI.CombineTo(N, Cond, SDValue());
18839 // Handle these cases:
18840 // (select (x != c), e, c) -> select (x != c), e, x),
18841 // (select (x == c), c, e) -> select (x == c), x, e)
18842 // where the c is an integer constant, and the "select" is the combination
18843 // of CMOV and CMP.
18845 // The rationale for this change is that the conditional-move from a constant
18846 // needs two instructions, however, conditional-move from a register needs
18847 // only one instruction.
18849 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18850 // some instruction-combining opportunities. This opt needs to be
18851 // postponed as late as possible.
18853 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18854 // the DCI.xxxx conditions are provided to postpone the optimization as
18855 // late as possible.
18857 ConstantSDNode *CmpAgainst = nullptr;
18858 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18859 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18860 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18862 if (CC == X86::COND_NE &&
18863 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18864 CC = X86::GetOppositeBranchCondition(CC);
18865 std::swap(TrueOp, FalseOp);
18868 if (CC == X86::COND_E &&
18869 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18870 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18871 DAG.getConstant(CC, MVT::i8), Cond };
18872 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18880 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18881 const X86Subtarget *Subtarget) {
18882 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18884 default: return SDValue();
18885 // SSE/AVX/AVX2 blend intrinsics.
18886 case Intrinsic::x86_avx2_pblendvb:
18887 case Intrinsic::x86_avx2_pblendw:
18888 case Intrinsic::x86_avx2_pblendd_128:
18889 case Intrinsic::x86_avx2_pblendd_256:
18890 // Don't try to simplify this intrinsic if we don't have AVX2.
18891 if (!Subtarget->hasAVX2())
18894 case Intrinsic::x86_avx_blend_pd_256:
18895 case Intrinsic::x86_avx_blend_ps_256:
18896 case Intrinsic::x86_avx_blendv_pd_256:
18897 case Intrinsic::x86_avx_blendv_ps_256:
18898 // Don't try to simplify this intrinsic if we don't have AVX.
18899 if (!Subtarget->hasAVX())
18902 case Intrinsic::x86_sse41_pblendw:
18903 case Intrinsic::x86_sse41_blendpd:
18904 case Intrinsic::x86_sse41_blendps:
18905 case Intrinsic::x86_sse41_blendvps:
18906 case Intrinsic::x86_sse41_blendvpd:
18907 case Intrinsic::x86_sse41_pblendvb: {
18908 SDValue Op0 = N->getOperand(1);
18909 SDValue Op1 = N->getOperand(2);
18910 SDValue Mask = N->getOperand(3);
18912 // Don't try to simplify this intrinsic if we don't have SSE4.1.
18913 if (!Subtarget->hasSSE41())
18916 // fold (blend A, A, Mask) -> A
18919 // fold (blend A, B, allZeros) -> A
18920 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18922 // fold (blend A, B, allOnes) -> B
18923 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18926 // Simplify the case where the mask is a constant i32 value.
18927 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18928 if (C->isNullValue())
18930 if (C->isAllOnesValue())
18935 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18936 case Intrinsic::x86_sse2_psrai_w:
18937 case Intrinsic::x86_sse2_psrai_d:
18938 case Intrinsic::x86_avx2_psrai_w:
18939 case Intrinsic::x86_avx2_psrai_d:
18940 case Intrinsic::x86_sse2_psra_w:
18941 case Intrinsic::x86_sse2_psra_d:
18942 case Intrinsic::x86_avx2_psra_w:
18943 case Intrinsic::x86_avx2_psra_d: {
18944 SDValue Op0 = N->getOperand(1);
18945 SDValue Op1 = N->getOperand(2);
18946 EVT VT = Op0.getValueType();
18947 assert(VT.isVector() && "Expected a vector type!");
18949 if (isa<BuildVectorSDNode>(Op1))
18950 Op1 = Op1.getOperand(0);
18952 if (!isa<ConstantSDNode>(Op1))
18955 EVT SVT = VT.getVectorElementType();
18956 unsigned SVTBits = SVT.getSizeInBits();
18958 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18959 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18960 uint64_t ShAmt = C.getZExtValue();
18962 // Don't try to convert this shift into a ISD::SRA if the shift
18963 // count is bigger than or equal to the element size.
18964 if (ShAmt >= SVTBits)
18967 // Trivial case: if the shift count is zero, then fold this
18968 // into the first operand.
18972 // Replace this packed shift intrinsic with a target independent
18974 SDValue Splat = DAG.getConstant(C, VT);
18975 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18980 /// PerformMulCombine - Optimize a single multiply with constant into two
18981 /// in order to implement it with two cheaper instructions, e.g.
18982 /// LEA + SHL, LEA + LEA.
18983 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18984 TargetLowering::DAGCombinerInfo &DCI) {
18985 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18988 EVT VT = N->getValueType(0);
18989 if (VT != MVT::i64)
18992 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18995 uint64_t MulAmt = C->getZExtValue();
18996 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18999 uint64_t MulAmt1 = 0;
19000 uint64_t MulAmt2 = 0;
19001 if ((MulAmt % 9) == 0) {
19003 MulAmt2 = MulAmt / 9;
19004 } else if ((MulAmt % 5) == 0) {
19006 MulAmt2 = MulAmt / 5;
19007 } else if ((MulAmt % 3) == 0) {
19009 MulAmt2 = MulAmt / 3;
19012 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19015 if (isPowerOf2_64(MulAmt2) &&
19016 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19017 // If second multiplifer is pow2, issue it first. We want the multiply by
19018 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19020 std::swap(MulAmt1, MulAmt2);
19023 if (isPowerOf2_64(MulAmt1))
19024 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19025 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19027 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19028 DAG.getConstant(MulAmt1, VT));
19030 if (isPowerOf2_64(MulAmt2))
19031 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19032 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19034 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19035 DAG.getConstant(MulAmt2, VT));
19037 // Do not add new nodes to DAG combiner worklist.
19038 DCI.CombineTo(N, NewMul, false);
19043 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19044 SDValue N0 = N->getOperand(0);
19045 SDValue N1 = N->getOperand(1);
19046 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19047 EVT VT = N0.getValueType();
19049 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19050 // since the result of setcc_c is all zero's or all ones.
19051 if (VT.isInteger() && !VT.isVector() &&
19052 N1C && N0.getOpcode() == ISD::AND &&
19053 N0.getOperand(1).getOpcode() == ISD::Constant) {
19054 SDValue N00 = N0.getOperand(0);
19055 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19056 ((N00.getOpcode() == ISD::ANY_EXTEND ||
19057 N00.getOpcode() == ISD::ZERO_EXTEND) &&
19058 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19059 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19060 APInt ShAmt = N1C->getAPIntValue();
19061 Mask = Mask.shl(ShAmt);
19063 return DAG.getNode(ISD::AND, SDLoc(N), VT,
19064 N00, DAG.getConstant(Mask, VT));
19068 // Hardware support for vector shifts is sparse which makes us scalarize the
19069 // vector operations in many cases. Also, on sandybridge ADD is faster than
19071 // (shl V, 1) -> add V,V
19072 if (isSplatVector(N1.getNode())) {
19073 assert(N0.getValueType().isVector() && "Invalid vector shift type");
19074 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19075 // We shift all of the values by one. In many cases we do not have
19076 // hardware support for this operation. This is better expressed as an ADD
19078 if (N1C && (1 == N1C->getZExtValue())) {
19079 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19086 /// \brief Returns a vector of 0s if the node in input is a vector logical
19087 /// shift by a constant amount which is known to be bigger than or equal
19088 /// to the vector element size in bits.
19089 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19090 const X86Subtarget *Subtarget) {
19091 EVT VT = N->getValueType(0);
19093 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19094 (!Subtarget->hasInt256() ||
19095 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19098 SDValue Amt = N->getOperand(1);
19100 if (isSplatVector(Amt.getNode())) {
19101 SDValue SclrAmt = Amt->getOperand(0);
19102 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19103 APInt ShiftAmt = C->getAPIntValue();
19104 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19106 // SSE2/AVX2 logical shifts always return a vector of 0s
19107 // if the shift amount is bigger than or equal to
19108 // the element size. The constant shift amount will be
19109 // encoded as a 8-bit immediate.
19110 if (ShiftAmt.trunc(8).uge(MaxAmount))
19111 return getZeroVector(VT, Subtarget, DAG, DL);
19118 /// PerformShiftCombine - Combine shifts.
19119 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19120 TargetLowering::DAGCombinerInfo &DCI,
19121 const X86Subtarget *Subtarget) {
19122 if (N->getOpcode() == ISD::SHL) {
19123 SDValue V = PerformSHLCombine(N, DAG);
19124 if (V.getNode()) return V;
19127 if (N->getOpcode() != ISD::SRA) {
19128 // Try to fold this logical shift into a zero vector.
19129 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19130 if (V.getNode()) return V;
19136 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19137 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19138 // and friends. Likewise for OR -> CMPNEQSS.
19139 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19140 TargetLowering::DAGCombinerInfo &DCI,
19141 const X86Subtarget *Subtarget) {
19144 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19145 // we're requiring SSE2 for both.
19146 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19147 SDValue N0 = N->getOperand(0);
19148 SDValue N1 = N->getOperand(1);
19149 SDValue CMP0 = N0->getOperand(1);
19150 SDValue CMP1 = N1->getOperand(1);
19153 // The SETCCs should both refer to the same CMP.
19154 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19157 SDValue CMP00 = CMP0->getOperand(0);
19158 SDValue CMP01 = CMP0->getOperand(1);
19159 EVT VT = CMP00.getValueType();
19161 if (VT == MVT::f32 || VT == MVT::f64) {
19162 bool ExpectingFlags = false;
19163 // Check for any users that want flags:
19164 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19165 !ExpectingFlags && UI != UE; ++UI)
19166 switch (UI->getOpcode()) {
19171 ExpectingFlags = true;
19173 case ISD::CopyToReg:
19174 case ISD::SIGN_EXTEND:
19175 case ISD::ZERO_EXTEND:
19176 case ISD::ANY_EXTEND:
19180 if (!ExpectingFlags) {
19181 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19182 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19184 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19185 X86::CondCode tmp = cc0;
19190 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19191 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19192 // FIXME: need symbolic constants for these magic numbers.
19193 // See X86ATTInstPrinter.cpp:printSSECC().
19194 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19195 if (Subtarget->hasAVX512()) {
19196 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19197 CMP01, DAG.getConstant(x86cc, MVT::i8));
19198 if (N->getValueType(0) != MVT::i1)
19199 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19203 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19204 CMP00.getValueType(), CMP00, CMP01,
19205 DAG.getConstant(x86cc, MVT::i8));
19207 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19208 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19210 if (is64BitFP && !Subtarget->is64Bit()) {
19211 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19212 // 64-bit integer, since that's not a legal type. Since
19213 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19214 // bits, but can do this little dance to extract the lowest 32 bits
19215 // and work with those going forward.
19216 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19218 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19220 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19221 Vector32, DAG.getIntPtrConstant(0));
19225 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19226 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19227 DAG.getConstant(1, IntVT));
19228 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19229 return OneBitOfTruth;
19237 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19238 /// so it can be folded inside ANDNP.
19239 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19240 EVT VT = N->getValueType(0);
19242 // Match direct AllOnes for 128 and 256-bit vectors
19243 if (ISD::isBuildVectorAllOnes(N))
19246 // Look through a bit convert.
19247 if (N->getOpcode() == ISD::BITCAST)
19248 N = N->getOperand(0).getNode();
19250 // Sometimes the operand may come from a insert_subvector building a 256-bit
19252 if (VT.is256BitVector() &&
19253 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19254 SDValue V1 = N->getOperand(0);
19255 SDValue V2 = N->getOperand(1);
19257 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19258 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19259 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19260 ISD::isBuildVectorAllOnes(V2.getNode()))
19267 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19268 // register. In most cases we actually compare or select YMM-sized registers
19269 // and mixing the two types creates horrible code. This method optimizes
19270 // some of the transition sequences.
19271 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19272 TargetLowering::DAGCombinerInfo &DCI,
19273 const X86Subtarget *Subtarget) {
19274 EVT VT = N->getValueType(0);
19275 if (!VT.is256BitVector())
19278 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19279 N->getOpcode() == ISD::ZERO_EXTEND ||
19280 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19282 SDValue Narrow = N->getOperand(0);
19283 EVT NarrowVT = Narrow->getValueType(0);
19284 if (!NarrowVT.is128BitVector())
19287 if (Narrow->getOpcode() != ISD::XOR &&
19288 Narrow->getOpcode() != ISD::AND &&
19289 Narrow->getOpcode() != ISD::OR)
19292 SDValue N0 = Narrow->getOperand(0);
19293 SDValue N1 = Narrow->getOperand(1);
19296 // The Left side has to be a trunc.
19297 if (N0.getOpcode() != ISD::TRUNCATE)
19300 // The type of the truncated inputs.
19301 EVT WideVT = N0->getOperand(0)->getValueType(0);
19305 // The right side has to be a 'trunc' or a constant vector.
19306 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19307 bool RHSConst = (isSplatVector(N1.getNode()) &&
19308 isa<ConstantSDNode>(N1->getOperand(0)));
19309 if (!RHSTrunc && !RHSConst)
19312 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19314 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19317 // Set N0 and N1 to hold the inputs to the new wide operation.
19318 N0 = N0->getOperand(0);
19320 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19321 N1->getOperand(0));
19322 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19323 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19324 } else if (RHSTrunc) {
19325 N1 = N1->getOperand(0);
19328 // Generate the wide operation.
19329 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19330 unsigned Opcode = N->getOpcode();
19332 case ISD::ANY_EXTEND:
19334 case ISD::ZERO_EXTEND: {
19335 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19336 APInt Mask = APInt::getAllOnesValue(InBits);
19337 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19338 return DAG.getNode(ISD::AND, DL, VT,
19339 Op, DAG.getConstant(Mask, VT));
19341 case ISD::SIGN_EXTEND:
19342 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19343 Op, DAG.getValueType(NarrowVT));
19345 llvm_unreachable("Unexpected opcode");
19349 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19350 TargetLowering::DAGCombinerInfo &DCI,
19351 const X86Subtarget *Subtarget) {
19352 EVT VT = N->getValueType(0);
19353 if (DCI.isBeforeLegalizeOps())
19356 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19360 // Create BEXTR instructions
19361 // BEXTR is ((X >> imm) & (2**size-1))
19362 if (VT == MVT::i32 || VT == MVT::i64) {
19363 SDValue N0 = N->getOperand(0);
19364 SDValue N1 = N->getOperand(1);
19367 // Check for BEXTR.
19368 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19369 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19370 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19371 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19372 if (MaskNode && ShiftNode) {
19373 uint64_t Mask = MaskNode->getZExtValue();
19374 uint64_t Shift = ShiftNode->getZExtValue();
19375 if (isMask_64(Mask)) {
19376 uint64_t MaskSize = CountPopulation_64(Mask);
19377 if (Shift + MaskSize <= VT.getSizeInBits())
19378 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19379 DAG.getConstant(Shift | (MaskSize << 8), VT));
19387 // Want to form ANDNP nodes:
19388 // 1) In the hopes of then easily combining them with OR and AND nodes
19389 // to form PBLEND/PSIGN.
19390 // 2) To match ANDN packed intrinsics
19391 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19394 SDValue N0 = N->getOperand(0);
19395 SDValue N1 = N->getOperand(1);
19398 // Check LHS for vnot
19399 if (N0.getOpcode() == ISD::XOR &&
19400 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19401 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19402 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19404 // Check RHS for vnot
19405 if (N1.getOpcode() == ISD::XOR &&
19406 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19407 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19408 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19413 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19414 TargetLowering::DAGCombinerInfo &DCI,
19415 const X86Subtarget *Subtarget) {
19416 if (DCI.isBeforeLegalizeOps())
19419 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19423 SDValue N0 = N->getOperand(0);
19424 SDValue N1 = N->getOperand(1);
19425 EVT VT = N->getValueType(0);
19427 // look for psign/blend
19428 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19429 if (!Subtarget->hasSSSE3() ||
19430 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19433 // Canonicalize pandn to RHS
19434 if (N0.getOpcode() == X86ISD::ANDNP)
19436 // or (and (m, y), (pandn m, x))
19437 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19438 SDValue Mask = N1.getOperand(0);
19439 SDValue X = N1.getOperand(1);
19441 if (N0.getOperand(0) == Mask)
19442 Y = N0.getOperand(1);
19443 if (N0.getOperand(1) == Mask)
19444 Y = N0.getOperand(0);
19446 // Check to see if the mask appeared in both the AND and ANDNP and
19450 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19451 // Look through mask bitcast.
19452 if (Mask.getOpcode() == ISD::BITCAST)
19453 Mask = Mask.getOperand(0);
19454 if (X.getOpcode() == ISD::BITCAST)
19455 X = X.getOperand(0);
19456 if (Y.getOpcode() == ISD::BITCAST)
19457 Y = Y.getOperand(0);
19459 EVT MaskVT = Mask.getValueType();
19461 // Validate that the Mask operand is a vector sra node.
19462 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19463 // there is no psrai.b
19464 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19465 unsigned SraAmt = ~0;
19466 if (Mask.getOpcode() == ISD::SRA) {
19467 SDValue Amt = Mask.getOperand(1);
19468 if (isSplatVector(Amt.getNode())) {
19469 SDValue SclrAmt = Amt->getOperand(0);
19470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19471 SraAmt = C->getZExtValue();
19473 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19474 SDValue SraC = Mask.getOperand(1);
19475 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19477 if ((SraAmt + 1) != EltBits)
19482 // Now we know we at least have a plendvb with the mask val. See if
19483 // we can form a psignb/w/d.
19484 // psign = x.type == y.type == mask.type && y = sub(0, x);
19485 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19486 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19487 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19488 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19489 "Unsupported VT for PSIGN");
19490 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19491 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19493 // PBLENDVB only available on SSE 4.1
19494 if (!Subtarget->hasSSE41())
19497 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19499 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19500 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19501 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19502 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19503 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19507 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19510 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19511 MachineFunction &MF = DAG.getMachineFunction();
19512 bool OptForSize = MF.getFunction()->getAttributes().
19513 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19515 // SHLD/SHRD instructions have lower register pressure, but on some
19516 // platforms they have higher latency than the equivalent
19517 // series of shifts/or that would otherwise be generated.
19518 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19519 // have higher latencies and we are not optimizing for size.
19520 if (!OptForSize && Subtarget->isSHLDSlow())
19523 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19525 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19527 if (!N0.hasOneUse() || !N1.hasOneUse())
19530 SDValue ShAmt0 = N0.getOperand(1);
19531 if (ShAmt0.getValueType() != MVT::i8)
19533 SDValue ShAmt1 = N1.getOperand(1);
19534 if (ShAmt1.getValueType() != MVT::i8)
19536 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19537 ShAmt0 = ShAmt0.getOperand(0);
19538 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19539 ShAmt1 = ShAmt1.getOperand(0);
19542 unsigned Opc = X86ISD::SHLD;
19543 SDValue Op0 = N0.getOperand(0);
19544 SDValue Op1 = N1.getOperand(0);
19545 if (ShAmt0.getOpcode() == ISD::SUB) {
19546 Opc = X86ISD::SHRD;
19547 std::swap(Op0, Op1);
19548 std::swap(ShAmt0, ShAmt1);
19551 unsigned Bits = VT.getSizeInBits();
19552 if (ShAmt1.getOpcode() == ISD::SUB) {
19553 SDValue Sum = ShAmt1.getOperand(0);
19554 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19555 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19556 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19557 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19558 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19559 return DAG.getNode(Opc, DL, VT,
19561 DAG.getNode(ISD::TRUNCATE, DL,
19564 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19565 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19567 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19568 return DAG.getNode(Opc, DL, VT,
19569 N0.getOperand(0), N1.getOperand(0),
19570 DAG.getNode(ISD::TRUNCATE, DL,
19577 // Generate NEG and CMOV for integer abs.
19578 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19579 EVT VT = N->getValueType(0);
19581 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19582 // 8-bit integer abs to NEG and CMOV.
19583 if (VT.isInteger() && VT.getSizeInBits() == 8)
19586 SDValue N0 = N->getOperand(0);
19587 SDValue N1 = N->getOperand(1);
19590 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19591 // and change it to SUB and CMOV.
19592 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19593 N0.getOpcode() == ISD::ADD &&
19594 N0.getOperand(1) == N1 &&
19595 N1.getOpcode() == ISD::SRA &&
19596 N1.getOperand(0) == N0.getOperand(0))
19597 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19598 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19599 // Generate SUB & CMOV.
19600 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19601 DAG.getConstant(0, VT), N0.getOperand(0));
19603 SDValue Ops[] = { N0.getOperand(0), Neg,
19604 DAG.getConstant(X86::COND_GE, MVT::i8),
19605 SDValue(Neg.getNode(), 1) };
19606 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19611 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19612 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19613 TargetLowering::DAGCombinerInfo &DCI,
19614 const X86Subtarget *Subtarget) {
19615 if (DCI.isBeforeLegalizeOps())
19618 if (Subtarget->hasCMov()) {
19619 SDValue RV = performIntegerAbsCombine(N, DAG);
19627 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19628 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19629 TargetLowering::DAGCombinerInfo &DCI,
19630 const X86Subtarget *Subtarget) {
19631 LoadSDNode *Ld = cast<LoadSDNode>(N);
19632 EVT RegVT = Ld->getValueType(0);
19633 EVT MemVT = Ld->getMemoryVT();
19635 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19636 unsigned RegSz = RegVT.getSizeInBits();
19638 // On Sandybridge unaligned 256bit loads are inefficient.
19639 ISD::LoadExtType Ext = Ld->getExtensionType();
19640 unsigned Alignment = Ld->getAlignment();
19641 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19642 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19643 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19644 unsigned NumElems = RegVT.getVectorNumElements();
19648 SDValue Ptr = Ld->getBasePtr();
19649 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19651 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19653 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19654 Ld->getPointerInfo(), Ld->isVolatile(),
19655 Ld->isNonTemporal(), Ld->isInvariant(),
19657 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19658 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19659 Ld->getPointerInfo(), Ld->isVolatile(),
19660 Ld->isNonTemporal(), Ld->isInvariant(),
19661 std::min(16U, Alignment));
19662 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19664 Load2.getValue(1));
19666 SDValue NewVec = DAG.getUNDEF(RegVT);
19667 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19668 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19669 return DCI.CombineTo(N, NewVec, TF, true);
19672 // If this is a vector EXT Load then attempt to optimize it using a
19673 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19674 // expansion is still better than scalar code.
19675 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19676 // emit a shuffle and a arithmetic shift.
19677 // TODO: It is possible to support ZExt by zeroing the undef values
19678 // during the shuffle phase or after the shuffle.
19679 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19680 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19681 assert(MemVT != RegVT && "Cannot extend to the same type");
19682 assert(MemVT.isVector() && "Must load a vector from memory");
19684 unsigned NumElems = RegVT.getVectorNumElements();
19685 unsigned MemSz = MemVT.getSizeInBits();
19686 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19688 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19691 // All sizes must be a power of two.
19692 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19695 // Attempt to load the original value using scalar loads.
19696 // Find the largest scalar type that divides the total loaded size.
19697 MVT SclrLoadTy = MVT::i8;
19698 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19699 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19700 MVT Tp = (MVT::SimpleValueType)tp;
19701 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19706 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19707 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19709 SclrLoadTy = MVT::f64;
19711 // Calculate the number of scalar loads that we need to perform
19712 // in order to load our vector from memory.
19713 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19714 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19717 unsigned loadRegZize = RegSz;
19718 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19721 // Represent our vector as a sequence of elements which are the
19722 // largest scalar that we can load.
19723 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19724 loadRegZize/SclrLoadTy.getSizeInBits());
19726 // Represent the data using the same element type that is stored in
19727 // memory. In practice, we ''widen'' MemVT.
19729 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19730 loadRegZize/MemVT.getScalarType().getSizeInBits());
19732 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19733 "Invalid vector type");
19735 // We can't shuffle using an illegal type.
19736 if (!TLI.isTypeLegal(WideVecVT))
19739 SmallVector<SDValue, 8> Chains;
19740 SDValue Ptr = Ld->getBasePtr();
19741 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19742 TLI.getPointerTy());
19743 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19745 for (unsigned i = 0; i < NumLoads; ++i) {
19746 // Perform a single load.
19747 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19748 Ptr, Ld->getPointerInfo(),
19749 Ld->isVolatile(), Ld->isNonTemporal(),
19750 Ld->isInvariant(), Ld->getAlignment());
19751 Chains.push_back(ScalarLoad.getValue(1));
19752 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19753 // another round of DAGCombining.
19755 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19757 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19758 ScalarLoad, DAG.getIntPtrConstant(i));
19760 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19763 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19765 // Bitcast the loaded value to a vector of the original element type, in
19766 // the size of the target vector type.
19767 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19768 unsigned SizeRatio = RegSz/MemSz;
19770 if (Ext == ISD::SEXTLOAD) {
19771 // If we have SSE4.1 we can directly emit a VSEXT node.
19772 if (Subtarget->hasSSE41()) {
19773 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19774 return DCI.CombineTo(N, Sext, TF, true);
19777 // Otherwise we'll shuffle the small elements in the high bits of the
19778 // larger type and perform an arithmetic shift. If the shift is not legal
19779 // it's better to scalarize.
19780 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19783 // Redistribute the loaded elements into the different locations.
19784 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19785 for (unsigned i = 0; i != NumElems; ++i)
19786 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19788 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19789 DAG.getUNDEF(WideVecVT),
19792 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19794 // Build the arithmetic shift.
19795 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19796 MemVT.getVectorElementType().getSizeInBits();
19797 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19798 DAG.getConstant(Amt, RegVT));
19800 return DCI.CombineTo(N, Shuff, TF, true);
19803 // Redistribute the loaded elements into the different locations.
19804 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19805 for (unsigned i = 0; i != NumElems; ++i)
19806 ShuffleVec[i*SizeRatio] = i;
19808 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19809 DAG.getUNDEF(WideVecVT),
19812 // Bitcast to the requested type.
19813 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19814 // Replace the original load with the new sequence
19815 // and return the new chain.
19816 return DCI.CombineTo(N, Shuff, TF, true);
19822 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19823 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19824 const X86Subtarget *Subtarget) {
19825 StoreSDNode *St = cast<StoreSDNode>(N);
19826 EVT VT = St->getValue().getValueType();
19827 EVT StVT = St->getMemoryVT();
19829 SDValue StoredVal = St->getOperand(1);
19830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19832 // If we are saving a concatenation of two XMM registers, perform two stores.
19833 // On Sandy Bridge, 256-bit memory operations are executed by two
19834 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19835 // memory operation.
19836 unsigned Alignment = St->getAlignment();
19837 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19838 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19839 StVT == VT && !IsAligned) {
19840 unsigned NumElems = VT.getVectorNumElements();
19844 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19845 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19847 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19848 SDValue Ptr0 = St->getBasePtr();
19849 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19851 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19852 St->getPointerInfo(), St->isVolatile(),
19853 St->isNonTemporal(), Alignment);
19854 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19855 St->getPointerInfo(), St->isVolatile(),
19856 St->isNonTemporal(),
19857 std::min(16U, Alignment));
19858 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19861 // Optimize trunc store (of multiple scalars) to shuffle and store.
19862 // First, pack all of the elements in one place. Next, store to memory
19863 // in fewer chunks.
19864 if (St->isTruncatingStore() && VT.isVector()) {
19865 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19866 unsigned NumElems = VT.getVectorNumElements();
19867 assert(StVT != VT && "Cannot truncate to the same type");
19868 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19869 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19871 // From, To sizes and ElemCount must be pow of two
19872 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19873 // We are going to use the original vector elt for storing.
19874 // Accumulated smaller vector elements must be a multiple of the store size.
19875 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19877 unsigned SizeRatio = FromSz / ToSz;
19879 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19881 // Create a type on which we perform the shuffle
19882 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19883 StVT.getScalarType(), NumElems*SizeRatio);
19885 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19887 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19888 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19889 for (unsigned i = 0; i != NumElems; ++i)
19890 ShuffleVec[i] = i * SizeRatio;
19892 // Can't shuffle using an illegal type.
19893 if (!TLI.isTypeLegal(WideVecVT))
19896 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19897 DAG.getUNDEF(WideVecVT),
19899 // At this point all of the data is stored at the bottom of the
19900 // register. We now need to save it to mem.
19902 // Find the largest store unit
19903 MVT StoreType = MVT::i8;
19904 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19905 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19906 MVT Tp = (MVT::SimpleValueType)tp;
19907 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19911 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19912 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19913 (64 <= NumElems * ToSz))
19914 StoreType = MVT::f64;
19916 // Bitcast the original vector into a vector of store-size units
19917 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19918 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19919 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19920 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19921 SmallVector<SDValue, 8> Chains;
19922 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19923 TLI.getPointerTy());
19924 SDValue Ptr = St->getBasePtr();
19926 // Perform one or more big stores into memory.
19927 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19928 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19929 StoreType, ShuffWide,
19930 DAG.getIntPtrConstant(i));
19931 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19932 St->getPointerInfo(), St->isVolatile(),
19933 St->isNonTemporal(), St->getAlignment());
19934 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19935 Chains.push_back(Ch);
19938 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19941 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19942 // the FP state in cases where an emms may be missing.
19943 // A preferable solution to the general problem is to figure out the right
19944 // places to insert EMMS. This qualifies as a quick hack.
19946 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19947 if (VT.getSizeInBits() != 64)
19950 const Function *F = DAG.getMachineFunction().getFunction();
19951 bool NoImplicitFloatOps = F->getAttributes().
19952 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19953 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19954 && Subtarget->hasSSE2();
19955 if ((VT.isVector() ||
19956 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19957 isa<LoadSDNode>(St->getValue()) &&
19958 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19959 St->getChain().hasOneUse() && !St->isVolatile()) {
19960 SDNode* LdVal = St->getValue().getNode();
19961 LoadSDNode *Ld = nullptr;
19962 int TokenFactorIndex = -1;
19963 SmallVector<SDValue, 8> Ops;
19964 SDNode* ChainVal = St->getChain().getNode();
19965 // Must be a store of a load. We currently handle two cases: the load
19966 // is a direct child, and it's under an intervening TokenFactor. It is
19967 // possible to dig deeper under nested TokenFactors.
19968 if (ChainVal == LdVal)
19969 Ld = cast<LoadSDNode>(St->getChain());
19970 else if (St->getValue().hasOneUse() &&
19971 ChainVal->getOpcode() == ISD::TokenFactor) {
19972 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19973 if (ChainVal->getOperand(i).getNode() == LdVal) {
19974 TokenFactorIndex = i;
19975 Ld = cast<LoadSDNode>(St->getValue());
19977 Ops.push_back(ChainVal->getOperand(i));
19981 if (!Ld || !ISD::isNormalLoad(Ld))
19984 // If this is not the MMX case, i.e. we are just turning i64 load/store
19985 // into f64 load/store, avoid the transformation if there are multiple
19986 // uses of the loaded value.
19987 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19992 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19993 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19995 if (Subtarget->is64Bit() || F64IsLegal) {
19996 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19997 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19998 Ld->getPointerInfo(), Ld->isVolatile(),
19999 Ld->isNonTemporal(), Ld->isInvariant(),
20000 Ld->getAlignment());
20001 SDValue NewChain = NewLd.getValue(1);
20002 if (TokenFactorIndex != -1) {
20003 Ops.push_back(NewChain);
20004 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20006 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20007 St->getPointerInfo(),
20008 St->isVolatile(), St->isNonTemporal(),
20009 St->getAlignment());
20012 // Otherwise, lower to two pairs of 32-bit loads / stores.
20013 SDValue LoAddr = Ld->getBasePtr();
20014 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20015 DAG.getConstant(4, MVT::i32));
20017 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20018 Ld->getPointerInfo(),
20019 Ld->isVolatile(), Ld->isNonTemporal(),
20020 Ld->isInvariant(), Ld->getAlignment());
20021 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20022 Ld->getPointerInfo().getWithOffset(4),
20023 Ld->isVolatile(), Ld->isNonTemporal(),
20025 MinAlign(Ld->getAlignment(), 4));
20027 SDValue NewChain = LoLd.getValue(1);
20028 if (TokenFactorIndex != -1) {
20029 Ops.push_back(LoLd);
20030 Ops.push_back(HiLd);
20031 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20034 LoAddr = St->getBasePtr();
20035 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20036 DAG.getConstant(4, MVT::i32));
20038 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20039 St->getPointerInfo(),
20040 St->isVolatile(), St->isNonTemporal(),
20041 St->getAlignment());
20042 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20043 St->getPointerInfo().getWithOffset(4),
20045 St->isNonTemporal(),
20046 MinAlign(St->getAlignment(), 4));
20047 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20052 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20053 /// and return the operands for the horizontal operation in LHS and RHS. A
20054 /// horizontal operation performs the binary operation on successive elements
20055 /// of its first operand, then on successive elements of its second operand,
20056 /// returning the resulting values in a vector. For example, if
20057 /// A = < float a0, float a1, float a2, float a3 >
20059 /// B = < float b0, float b1, float b2, float b3 >
20060 /// then the result of doing a horizontal operation on A and B is
20061 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20062 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20063 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20064 /// set to A, RHS to B, and the routine returns 'true'.
20065 /// Note that the binary operation should have the property that if one of the
20066 /// operands is UNDEF then the result is UNDEF.
20067 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20068 // Look for the following pattern: if
20069 // A = < float a0, float a1, float a2, float a3 >
20070 // B = < float b0, float b1, float b2, float b3 >
20072 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20073 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20074 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20075 // which is A horizontal-op B.
20077 // At least one of the operands should be a vector shuffle.
20078 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20079 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20082 MVT VT = LHS.getSimpleValueType();
20084 assert((VT.is128BitVector() || VT.is256BitVector()) &&
20085 "Unsupported vector type for horizontal add/sub");
20087 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20088 // operate independently on 128-bit lanes.
20089 unsigned NumElts = VT.getVectorNumElements();
20090 unsigned NumLanes = VT.getSizeInBits()/128;
20091 unsigned NumLaneElts = NumElts / NumLanes;
20092 assert((NumLaneElts % 2 == 0) &&
20093 "Vector type should have an even number of elements in each lane");
20094 unsigned HalfLaneElts = NumLaneElts/2;
20096 // View LHS in the form
20097 // LHS = VECTOR_SHUFFLE A, B, LMask
20098 // If LHS is not a shuffle then pretend it is the shuffle
20099 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20100 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20103 SmallVector<int, 16> LMask(NumElts);
20104 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20105 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20106 A = LHS.getOperand(0);
20107 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20108 B = LHS.getOperand(1);
20109 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20110 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20112 if (LHS.getOpcode() != ISD::UNDEF)
20114 for (unsigned i = 0; i != NumElts; ++i)
20118 // Likewise, view RHS in the form
20119 // RHS = VECTOR_SHUFFLE C, D, RMask
20121 SmallVector<int, 16> RMask(NumElts);
20122 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20123 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20124 C = RHS.getOperand(0);
20125 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20126 D = RHS.getOperand(1);
20127 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20128 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20130 if (RHS.getOpcode() != ISD::UNDEF)
20132 for (unsigned i = 0; i != NumElts; ++i)
20136 // Check that the shuffles are both shuffling the same vectors.
20137 if (!(A == C && B == D) && !(A == D && B == C))
20140 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20141 if (!A.getNode() && !B.getNode())
20144 // If A and B occur in reverse order in RHS, then "swap" them (which means
20145 // rewriting the mask).
20147 CommuteVectorShuffleMask(RMask, NumElts);
20149 // At this point LHS and RHS are equivalent to
20150 // LHS = VECTOR_SHUFFLE A, B, LMask
20151 // RHS = VECTOR_SHUFFLE A, B, RMask
20152 // Check that the masks correspond to performing a horizontal operation.
20153 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20154 for (unsigned i = 0; i != NumLaneElts; ++i) {
20155 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20157 // Ignore any UNDEF components.
20158 if (LIdx < 0 || RIdx < 0 ||
20159 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20160 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20163 // Check that successive elements are being operated on. If not, this is
20164 // not a horizontal operation.
20165 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20166 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20167 if (!(LIdx == Index && RIdx == Index + 1) &&
20168 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20173 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20174 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20178 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20179 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20180 const X86Subtarget *Subtarget) {
20181 EVT VT = N->getValueType(0);
20182 SDValue LHS = N->getOperand(0);
20183 SDValue RHS = N->getOperand(1);
20185 // Try to synthesize horizontal adds from adds of shuffles.
20186 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20187 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20188 isHorizontalBinOp(LHS, RHS, true))
20189 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20193 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20194 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20195 const X86Subtarget *Subtarget) {
20196 EVT VT = N->getValueType(0);
20197 SDValue LHS = N->getOperand(0);
20198 SDValue RHS = N->getOperand(1);
20200 // Try to synthesize horizontal subs from subs of shuffles.
20201 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20202 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20203 isHorizontalBinOp(LHS, RHS, false))
20204 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20208 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20209 /// X86ISD::FXOR nodes.
20210 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20211 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20212 // F[X]OR(0.0, x) -> x
20213 // F[X]OR(x, 0.0) -> x
20214 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20215 if (C->getValueAPF().isPosZero())
20216 return N->getOperand(1);
20217 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20218 if (C->getValueAPF().isPosZero())
20219 return N->getOperand(0);
20223 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20224 /// X86ISD::FMAX nodes.
20225 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20226 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20228 // Only perform optimizations if UnsafeMath is used.
20229 if (!DAG.getTarget().Options.UnsafeFPMath)
20232 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20233 // into FMINC and FMAXC, which are Commutative operations.
20234 unsigned NewOp = 0;
20235 switch (N->getOpcode()) {
20236 default: llvm_unreachable("unknown opcode");
20237 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20238 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20241 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20242 N->getOperand(0), N->getOperand(1));
20245 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20246 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20247 // FAND(0.0, x) -> 0.0
20248 // FAND(x, 0.0) -> 0.0
20249 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20250 if (C->getValueAPF().isPosZero())
20251 return N->getOperand(0);
20252 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20253 if (C->getValueAPF().isPosZero())
20254 return N->getOperand(1);
20258 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20259 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20260 // FANDN(x, 0.0) -> 0.0
20261 // FANDN(0.0, x) -> x
20262 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20263 if (C->getValueAPF().isPosZero())
20264 return N->getOperand(1);
20265 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20266 if (C->getValueAPF().isPosZero())
20267 return N->getOperand(1);
20271 static SDValue PerformBTCombine(SDNode *N,
20273 TargetLowering::DAGCombinerInfo &DCI) {
20274 // BT ignores high bits in the bit index operand.
20275 SDValue Op1 = N->getOperand(1);
20276 if (Op1.hasOneUse()) {
20277 unsigned BitWidth = Op1.getValueSizeInBits();
20278 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20279 APInt KnownZero, KnownOne;
20280 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20281 !DCI.isBeforeLegalizeOps());
20282 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20283 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20284 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20285 DCI.CommitTargetLoweringOpt(TLO);
20290 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20291 SDValue Op = N->getOperand(0);
20292 if (Op.getOpcode() == ISD::BITCAST)
20293 Op = Op.getOperand(0);
20294 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20295 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20296 VT.getVectorElementType().getSizeInBits() ==
20297 OpVT.getVectorElementType().getSizeInBits()) {
20298 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20303 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20304 const X86Subtarget *Subtarget) {
20305 EVT VT = N->getValueType(0);
20306 if (!VT.isVector())
20309 SDValue N0 = N->getOperand(0);
20310 SDValue N1 = N->getOperand(1);
20311 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20314 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20315 // both SSE and AVX2 since there is no sign-extended shift right
20316 // operation on a vector with 64-bit elements.
20317 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20318 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20319 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20320 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20321 SDValue N00 = N0.getOperand(0);
20323 // EXTLOAD has a better solution on AVX2,
20324 // it may be replaced with X86ISD::VSEXT node.
20325 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20326 if (!ISD::isNormalLoad(N00.getNode()))
20329 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20330 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20332 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20338 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20339 TargetLowering::DAGCombinerInfo &DCI,
20340 const X86Subtarget *Subtarget) {
20341 if (!DCI.isBeforeLegalizeOps())
20344 if (!Subtarget->hasFp256())
20347 EVT VT = N->getValueType(0);
20348 if (VT.isVector() && VT.getSizeInBits() == 256) {
20349 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20357 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20358 const X86Subtarget* Subtarget) {
20360 EVT VT = N->getValueType(0);
20362 // Let legalize expand this if it isn't a legal type yet.
20363 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20366 EVT ScalarVT = VT.getScalarType();
20367 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20368 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20371 SDValue A = N->getOperand(0);
20372 SDValue B = N->getOperand(1);
20373 SDValue C = N->getOperand(2);
20375 bool NegA = (A.getOpcode() == ISD::FNEG);
20376 bool NegB = (B.getOpcode() == ISD::FNEG);
20377 bool NegC = (C.getOpcode() == ISD::FNEG);
20379 // Negative multiplication when NegA xor NegB
20380 bool NegMul = (NegA != NegB);
20382 A = A.getOperand(0);
20384 B = B.getOperand(0);
20386 C = C.getOperand(0);
20390 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20392 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20394 return DAG.getNode(Opcode, dl, VT, A, B, C);
20397 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20398 TargetLowering::DAGCombinerInfo &DCI,
20399 const X86Subtarget *Subtarget) {
20400 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20401 // (and (i32 x86isd::setcc_carry), 1)
20402 // This eliminates the zext. This transformation is necessary because
20403 // ISD::SETCC is always legalized to i8.
20405 SDValue N0 = N->getOperand(0);
20406 EVT VT = N->getValueType(0);
20408 if (N0.getOpcode() == ISD::AND &&
20410 N0.getOperand(0).hasOneUse()) {
20411 SDValue N00 = N0.getOperand(0);
20412 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20413 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20414 if (!C || C->getZExtValue() != 1)
20416 return DAG.getNode(ISD::AND, dl, VT,
20417 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20418 N00.getOperand(0), N00.getOperand(1)),
20419 DAG.getConstant(1, VT));
20423 if (N0.getOpcode() == ISD::TRUNCATE &&
20425 N0.getOperand(0).hasOneUse()) {
20426 SDValue N00 = N0.getOperand(0);
20427 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20428 return DAG.getNode(ISD::AND, dl, VT,
20429 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20430 N00.getOperand(0), N00.getOperand(1)),
20431 DAG.getConstant(1, VT));
20434 if (VT.is256BitVector()) {
20435 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20443 // Optimize x == -y --> x+y == 0
20444 // x != -y --> x+y != 0
20445 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20446 const X86Subtarget* Subtarget) {
20447 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20448 SDValue LHS = N->getOperand(0);
20449 SDValue RHS = N->getOperand(1);
20450 EVT VT = N->getValueType(0);
20453 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20455 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20456 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20457 LHS.getValueType(), RHS, LHS.getOperand(1));
20458 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20459 addV, DAG.getConstant(0, addV.getValueType()), CC);
20461 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20462 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20463 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20464 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20465 RHS.getValueType(), LHS, RHS.getOperand(1));
20466 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20467 addV, DAG.getConstant(0, addV.getValueType()), CC);
20470 if (VT.getScalarType() == MVT::i1) {
20471 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20472 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20473 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20474 if (!IsSEXT0 && !IsVZero0)
20476 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20477 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20478 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20480 if (!IsSEXT1 && !IsVZero1)
20483 if (IsSEXT0 && IsVZero1) {
20484 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20485 if (CC == ISD::SETEQ)
20486 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20487 return LHS.getOperand(0);
20489 if (IsSEXT1 && IsVZero0) {
20490 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20491 if (CC == ISD::SETEQ)
20492 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20493 return RHS.getOperand(0);
20500 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20501 const X86Subtarget *Subtarget) {
20503 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20504 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20505 "X86insertps is only defined for v4x32");
20507 SDValue Ld = N->getOperand(1);
20508 if (MayFoldLoad(Ld)) {
20509 // Extract the countS bits from the immediate so we can get the proper
20510 // address when narrowing the vector load to a specific element.
20511 // When the second source op is a memory address, interps doesn't use
20512 // countS and just gets an f32 from that address.
20513 unsigned DestIndex =
20514 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20515 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20519 // Create this as a scalar to vector to match the instruction pattern.
20520 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20521 // countS bits are ignored when loading from memory on insertps, which
20522 // means we don't need to explicitly set them to 0.
20523 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20524 LoadScalarToVector, N->getOperand(2));
20527 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20528 // as "sbb reg,reg", since it can be extended without zext and produces
20529 // an all-ones bit which is more useful than 0/1 in some cases.
20530 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20533 return DAG.getNode(ISD::AND, DL, VT,
20534 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20535 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20536 DAG.getConstant(1, VT));
20537 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20538 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20539 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20540 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20543 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20544 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20545 TargetLowering::DAGCombinerInfo &DCI,
20546 const X86Subtarget *Subtarget) {
20548 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20549 SDValue EFLAGS = N->getOperand(1);
20551 if (CC == X86::COND_A) {
20552 // Try to convert COND_A into COND_B in an attempt to facilitate
20553 // materializing "setb reg".
20555 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20556 // cannot take an immediate as its first operand.
20558 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20559 EFLAGS.getValueType().isInteger() &&
20560 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20561 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20562 EFLAGS.getNode()->getVTList(),
20563 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20564 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20565 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20569 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20570 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20572 if (CC == X86::COND_B)
20573 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20577 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20578 if (Flags.getNode()) {
20579 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20580 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20586 // Optimize branch condition evaluation.
20588 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20589 TargetLowering::DAGCombinerInfo &DCI,
20590 const X86Subtarget *Subtarget) {
20592 SDValue Chain = N->getOperand(0);
20593 SDValue Dest = N->getOperand(1);
20594 SDValue EFLAGS = N->getOperand(3);
20595 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20599 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20600 if (Flags.getNode()) {
20601 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20602 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20609 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20610 const X86TargetLowering *XTLI) {
20611 SDValue Op0 = N->getOperand(0);
20612 EVT InVT = Op0->getValueType(0);
20614 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20615 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20617 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20618 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20619 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20622 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20623 // a 32-bit target where SSE doesn't support i64->FP operations.
20624 if (Op0.getOpcode() == ISD::LOAD) {
20625 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20626 EVT VT = Ld->getValueType(0);
20627 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20628 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20629 !XTLI->getSubtarget()->is64Bit() &&
20631 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20632 Ld->getChain(), Op0, DAG);
20633 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20640 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20641 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20642 X86TargetLowering::DAGCombinerInfo &DCI) {
20643 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20644 // the result is either zero or one (depending on the input carry bit).
20645 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20646 if (X86::isZeroNode(N->getOperand(0)) &&
20647 X86::isZeroNode(N->getOperand(1)) &&
20648 // We don't have a good way to replace an EFLAGS use, so only do this when
20650 SDValue(N, 1).use_empty()) {
20652 EVT VT = N->getValueType(0);
20653 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20654 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20655 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20656 DAG.getConstant(X86::COND_B,MVT::i8),
20658 DAG.getConstant(1, VT));
20659 return DCI.CombineTo(N, Res1, CarryOut);
20665 // fold (add Y, (sete X, 0)) -> adc 0, Y
20666 // (add Y, (setne X, 0)) -> sbb -1, Y
20667 // (sub (sete X, 0), Y) -> sbb 0, Y
20668 // (sub (setne X, 0), Y) -> adc -1, Y
20669 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20672 // Look through ZExts.
20673 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20674 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20677 SDValue SetCC = Ext.getOperand(0);
20678 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20681 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20682 if (CC != X86::COND_E && CC != X86::COND_NE)
20685 SDValue Cmp = SetCC.getOperand(1);
20686 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20687 !X86::isZeroNode(Cmp.getOperand(1)) ||
20688 !Cmp.getOperand(0).getValueType().isInteger())
20691 SDValue CmpOp0 = Cmp.getOperand(0);
20692 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20693 DAG.getConstant(1, CmpOp0.getValueType()));
20695 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20696 if (CC == X86::COND_NE)
20697 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20698 DL, OtherVal.getValueType(), OtherVal,
20699 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20700 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20701 DL, OtherVal.getValueType(), OtherVal,
20702 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20705 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20706 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20707 const X86Subtarget *Subtarget) {
20708 EVT VT = N->getValueType(0);
20709 SDValue Op0 = N->getOperand(0);
20710 SDValue Op1 = N->getOperand(1);
20712 // Try to synthesize horizontal adds from adds of shuffles.
20713 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20714 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20715 isHorizontalBinOp(Op0, Op1, true))
20716 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20718 return OptimizeConditionalInDecrement(N, DAG);
20721 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20722 const X86Subtarget *Subtarget) {
20723 SDValue Op0 = N->getOperand(0);
20724 SDValue Op1 = N->getOperand(1);
20726 // X86 can't encode an immediate LHS of a sub. See if we can push the
20727 // negation into a preceding instruction.
20728 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20729 // If the RHS of the sub is a XOR with one use and a constant, invert the
20730 // immediate. Then add one to the LHS of the sub so we can turn
20731 // X-Y -> X+~Y+1, saving one register.
20732 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20733 isa<ConstantSDNode>(Op1.getOperand(1))) {
20734 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20735 EVT VT = Op0.getValueType();
20736 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20738 DAG.getConstant(~XorC, VT));
20739 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20740 DAG.getConstant(C->getAPIntValue()+1, VT));
20744 // Try to synthesize horizontal adds from adds of shuffles.
20745 EVT VT = N->getValueType(0);
20746 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20747 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20748 isHorizontalBinOp(Op0, Op1, true))
20749 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20751 return OptimizeConditionalInDecrement(N, DAG);
20754 /// performVZEXTCombine - Performs build vector combines
20755 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20756 TargetLowering::DAGCombinerInfo &DCI,
20757 const X86Subtarget *Subtarget) {
20758 // (vzext (bitcast (vzext (x)) -> (vzext x)
20759 SDValue In = N->getOperand(0);
20760 while (In.getOpcode() == ISD::BITCAST)
20761 In = In.getOperand(0);
20763 if (In.getOpcode() != X86ISD::VZEXT)
20766 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20770 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20771 DAGCombinerInfo &DCI) const {
20772 SelectionDAG &DAG = DCI.DAG;
20773 switch (N->getOpcode()) {
20775 case ISD::EXTRACT_VECTOR_ELT:
20776 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20778 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20779 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20780 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20781 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20782 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20783 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20786 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20787 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20788 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20789 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20790 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20791 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20792 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20793 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20794 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20796 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20798 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20799 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20800 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20801 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20802 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20803 case ISD::ANY_EXTEND:
20804 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20805 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20806 case ISD::SIGN_EXTEND_INREG:
20807 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20808 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20809 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20810 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20811 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20812 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20813 case X86ISD::SHUFP: // Handle all target specific shuffles
20814 case X86ISD::PALIGNR:
20815 case X86ISD::UNPCKH:
20816 case X86ISD::UNPCKL:
20817 case X86ISD::MOVHLPS:
20818 case X86ISD::MOVLHPS:
20819 case X86ISD::PSHUFD:
20820 case X86ISD::PSHUFHW:
20821 case X86ISD::PSHUFLW:
20822 case X86ISD::MOVSS:
20823 case X86ISD::MOVSD:
20824 case X86ISD::VPERMILP:
20825 case X86ISD::VPERM2X128:
20826 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20827 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20828 case ISD::INTRINSIC_WO_CHAIN:
20829 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20830 case X86ISD::INSERTPS:
20831 return PerformINSERTPSCombine(N, DAG, Subtarget);
20832 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
20838 /// isTypeDesirableForOp - Return true if the target has native support for
20839 /// the specified value type and it is 'desirable' to use the type for the
20840 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20841 /// instruction encodings are longer and some i16 instructions are slow.
20842 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20843 if (!isTypeLegal(VT))
20845 if (VT != MVT::i16)
20852 case ISD::SIGN_EXTEND:
20853 case ISD::ZERO_EXTEND:
20854 case ISD::ANY_EXTEND:
20867 /// IsDesirableToPromoteOp - This method query the target whether it is
20868 /// beneficial for dag combiner to promote the specified node. If true, it
20869 /// should return the desired promotion type by reference.
20870 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20871 EVT VT = Op.getValueType();
20872 if (VT != MVT::i16)
20875 bool Promote = false;
20876 bool Commute = false;
20877 switch (Op.getOpcode()) {
20880 LoadSDNode *LD = cast<LoadSDNode>(Op);
20881 // If the non-extending load has a single use and it's not live out, then it
20882 // might be folded.
20883 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20884 Op.hasOneUse()*/) {
20885 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20886 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20887 // The only case where we'd want to promote LOAD (rather then it being
20888 // promoted as an operand is when it's only use is liveout.
20889 if (UI->getOpcode() != ISD::CopyToReg)
20896 case ISD::SIGN_EXTEND:
20897 case ISD::ZERO_EXTEND:
20898 case ISD::ANY_EXTEND:
20903 SDValue N0 = Op.getOperand(0);
20904 // Look out for (store (shl (load), x)).
20905 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20918 SDValue N0 = Op.getOperand(0);
20919 SDValue N1 = Op.getOperand(1);
20920 if (!Commute && MayFoldLoad(N1))
20922 // Avoid disabling potential load folding opportunities.
20923 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20925 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20935 //===----------------------------------------------------------------------===//
20936 // X86 Inline Assembly Support
20937 //===----------------------------------------------------------------------===//
20940 // Helper to match a string separated by whitespace.
20941 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20942 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20944 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20945 StringRef piece(*args[i]);
20946 if (!s.startswith(piece)) // Check if the piece matches.
20949 s = s.substr(piece.size());
20950 StringRef::size_type pos = s.find_first_not_of(" \t");
20951 if (pos == 0) // We matched a prefix.
20959 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20962 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20964 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20965 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20966 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20967 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20969 if (AsmPieces.size() == 3)
20971 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20978 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20979 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20981 std::string AsmStr = IA->getAsmString();
20983 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20984 if (!Ty || Ty->getBitWidth() % 16 != 0)
20987 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20988 SmallVector<StringRef, 4> AsmPieces;
20989 SplitString(AsmStr, AsmPieces, ";\n");
20991 switch (AsmPieces.size()) {
20992 default: return false;
20994 // FIXME: this should verify that we are targeting a 486 or better. If not,
20995 // we will turn this bswap into something that will be lowered to logical
20996 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20997 // lower so don't worry about this.
20999 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21000 matchAsm(AsmPieces[0], "bswapl", "$0") ||
21001 matchAsm(AsmPieces[0], "bswapq", "$0") ||
21002 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21003 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21004 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21005 // No need to check constraints, nothing other than the equivalent of
21006 // "=r,0" would be valid here.
21007 return IntrinsicLowering::LowerToByteSwap(CI);
21010 // rorw $$8, ${0:w} --> llvm.bswap.i16
21011 if (CI->getType()->isIntegerTy(16) &&
21012 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21013 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21014 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21016 const std::string &ConstraintsStr = IA->getConstraintString();
21017 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21018 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21019 if (clobbersFlagRegisters(AsmPieces))
21020 return IntrinsicLowering::LowerToByteSwap(CI);
21024 if (CI->getType()->isIntegerTy(32) &&
21025 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21026 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21027 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21028 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21030 const std::string &ConstraintsStr = IA->getConstraintString();
21031 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21032 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21033 if (clobbersFlagRegisters(AsmPieces))
21034 return IntrinsicLowering::LowerToByteSwap(CI);
21037 if (CI->getType()->isIntegerTy(64)) {
21038 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21039 if (Constraints.size() >= 2 &&
21040 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21041 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21042 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
21043 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21044 matchAsm(AsmPieces[1], "bswap", "%edx") &&
21045 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21046 return IntrinsicLowering::LowerToByteSwap(CI);
21054 /// getConstraintType - Given a constraint letter, return the type of
21055 /// constraint it is for this target.
21056 X86TargetLowering::ConstraintType
21057 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21058 if (Constraint.size() == 1) {
21059 switch (Constraint[0]) {
21070 return C_RegisterClass;
21094 return TargetLowering::getConstraintType(Constraint);
21097 /// Examine constraint type and operand type and determine a weight value.
21098 /// This object must already have been set up with the operand type
21099 /// and the current alternative constraint selected.
21100 TargetLowering::ConstraintWeight
21101 X86TargetLowering::getSingleConstraintMatchWeight(
21102 AsmOperandInfo &info, const char *constraint) const {
21103 ConstraintWeight weight = CW_Invalid;
21104 Value *CallOperandVal = info.CallOperandVal;
21105 // If we don't have a value, we can't do a match,
21106 // but allow it at the lowest weight.
21107 if (!CallOperandVal)
21109 Type *type = CallOperandVal->getType();
21110 // Look at the constraint type.
21111 switch (*constraint) {
21113 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21124 if (CallOperandVal->getType()->isIntegerTy())
21125 weight = CW_SpecificReg;
21130 if (type->isFloatingPointTy())
21131 weight = CW_SpecificReg;
21134 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21135 weight = CW_SpecificReg;
21139 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21140 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21141 weight = CW_Register;
21144 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21145 if (C->getZExtValue() <= 31)
21146 weight = CW_Constant;
21150 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21151 if (C->getZExtValue() <= 63)
21152 weight = CW_Constant;
21156 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21157 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21158 weight = CW_Constant;
21162 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21163 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21164 weight = CW_Constant;
21168 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21169 if (C->getZExtValue() <= 3)
21170 weight = CW_Constant;
21174 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21175 if (C->getZExtValue() <= 0xff)
21176 weight = CW_Constant;
21181 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21182 weight = CW_Constant;
21186 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21187 if ((C->getSExtValue() >= -0x80000000LL) &&
21188 (C->getSExtValue() <= 0x7fffffffLL))
21189 weight = CW_Constant;
21193 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21194 if (C->getZExtValue() <= 0xffffffff)
21195 weight = CW_Constant;
21202 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21203 /// with another that has more specific requirements based on the type of the
21204 /// corresponding operand.
21205 const char *X86TargetLowering::
21206 LowerXConstraint(EVT ConstraintVT) const {
21207 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21208 // 'f' like normal targets.
21209 if (ConstraintVT.isFloatingPoint()) {
21210 if (Subtarget->hasSSE2())
21212 if (Subtarget->hasSSE1())
21216 return TargetLowering::LowerXConstraint(ConstraintVT);
21219 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21220 /// vector. If it is invalid, don't add anything to Ops.
21221 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21222 std::string &Constraint,
21223 std::vector<SDValue>&Ops,
21224 SelectionDAG &DAG) const {
21227 // Only support length 1 constraints for now.
21228 if (Constraint.length() > 1) return;
21230 char ConstraintLetter = Constraint[0];
21231 switch (ConstraintLetter) {
21234 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21235 if (C->getZExtValue() <= 31) {
21236 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21242 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21243 if (C->getZExtValue() <= 63) {
21244 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21250 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21251 if (isInt<8>(C->getSExtValue())) {
21252 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21258 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21259 if (C->getZExtValue() <= 255) {
21260 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21266 // 32-bit signed value
21267 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21268 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21269 C->getSExtValue())) {
21270 // Widen to 64 bits here to get it sign extended.
21271 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21274 // FIXME gcc accepts some relocatable values here too, but only in certain
21275 // memory models; it's complicated.
21280 // 32-bit unsigned value
21281 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21282 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21283 C->getZExtValue())) {
21284 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21288 // FIXME gcc accepts some relocatable values here too, but only in certain
21289 // memory models; it's complicated.
21293 // Literal immediates are always ok.
21294 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21295 // Widen to 64 bits here to get it sign extended.
21296 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21300 // In any sort of PIC mode addresses need to be computed at runtime by
21301 // adding in a register or some sort of table lookup. These can't
21302 // be used as immediates.
21303 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21306 // If we are in non-pic codegen mode, we allow the address of a global (with
21307 // an optional displacement) to be used with 'i'.
21308 GlobalAddressSDNode *GA = nullptr;
21309 int64_t Offset = 0;
21311 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21313 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21314 Offset += GA->getOffset();
21316 } else if (Op.getOpcode() == ISD::ADD) {
21317 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21318 Offset += C->getZExtValue();
21319 Op = Op.getOperand(0);
21322 } else if (Op.getOpcode() == ISD::SUB) {
21323 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21324 Offset += -C->getZExtValue();
21325 Op = Op.getOperand(0);
21330 // Otherwise, this isn't something we can handle, reject it.
21334 const GlobalValue *GV = GA->getGlobal();
21335 // If we require an extra load to get this address, as in PIC mode, we
21336 // can't accept it.
21337 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21338 getTargetMachine())))
21341 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21342 GA->getValueType(0), Offset);
21347 if (Result.getNode()) {
21348 Ops.push_back(Result);
21351 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21354 std::pair<unsigned, const TargetRegisterClass*>
21355 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21357 // First, see if this is a constraint that directly corresponds to an LLVM
21359 if (Constraint.size() == 1) {
21360 // GCC Constraint Letters
21361 switch (Constraint[0]) {
21363 // TODO: Slight differences here in allocation order and leaving
21364 // RIP in the class. Do they matter any more here than they do
21365 // in the normal allocation?
21366 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21367 if (Subtarget->is64Bit()) {
21368 if (VT == MVT::i32 || VT == MVT::f32)
21369 return std::make_pair(0U, &X86::GR32RegClass);
21370 if (VT == MVT::i16)
21371 return std::make_pair(0U, &X86::GR16RegClass);
21372 if (VT == MVT::i8 || VT == MVT::i1)
21373 return std::make_pair(0U, &X86::GR8RegClass);
21374 if (VT == MVT::i64 || VT == MVT::f64)
21375 return std::make_pair(0U, &X86::GR64RegClass);
21378 // 32-bit fallthrough
21379 case 'Q': // Q_REGS
21380 if (VT == MVT::i32 || VT == MVT::f32)
21381 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21382 if (VT == MVT::i16)
21383 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21384 if (VT == MVT::i8 || VT == MVT::i1)
21385 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21386 if (VT == MVT::i64)
21387 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21389 case 'r': // GENERAL_REGS
21390 case 'l': // INDEX_REGS
21391 if (VT == MVT::i8 || VT == MVT::i1)
21392 return std::make_pair(0U, &X86::GR8RegClass);
21393 if (VT == MVT::i16)
21394 return std::make_pair(0U, &X86::GR16RegClass);
21395 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21396 return std::make_pair(0U, &X86::GR32RegClass);
21397 return std::make_pair(0U, &X86::GR64RegClass);
21398 case 'R': // LEGACY_REGS
21399 if (VT == MVT::i8 || VT == MVT::i1)
21400 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21401 if (VT == MVT::i16)
21402 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21403 if (VT == MVT::i32 || !Subtarget->is64Bit())
21404 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21405 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21406 case 'f': // FP Stack registers.
21407 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21408 // value to the correct fpstack register class.
21409 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21410 return std::make_pair(0U, &X86::RFP32RegClass);
21411 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21412 return std::make_pair(0U, &X86::RFP64RegClass);
21413 return std::make_pair(0U, &X86::RFP80RegClass);
21414 case 'y': // MMX_REGS if MMX allowed.
21415 if (!Subtarget->hasMMX()) break;
21416 return std::make_pair(0U, &X86::VR64RegClass);
21417 case 'Y': // SSE_REGS if SSE2 allowed
21418 if (!Subtarget->hasSSE2()) break;
21420 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21421 if (!Subtarget->hasSSE1()) break;
21423 switch (VT.SimpleTy) {
21425 // Scalar SSE types.
21428 return std::make_pair(0U, &X86::FR32RegClass);
21431 return std::make_pair(0U, &X86::FR64RegClass);
21439 return std::make_pair(0U, &X86::VR128RegClass);
21447 return std::make_pair(0U, &X86::VR256RegClass);
21452 return std::make_pair(0U, &X86::VR512RegClass);
21458 // Use the default implementation in TargetLowering to convert the register
21459 // constraint into a member of a register class.
21460 std::pair<unsigned, const TargetRegisterClass*> Res;
21461 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21463 // Not found as a standard register?
21465 // Map st(0) -> st(7) -> ST0
21466 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21467 tolower(Constraint[1]) == 's' &&
21468 tolower(Constraint[2]) == 't' &&
21469 Constraint[3] == '(' &&
21470 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21471 Constraint[5] == ')' &&
21472 Constraint[6] == '}') {
21474 Res.first = X86::ST0+Constraint[4]-'0';
21475 Res.second = &X86::RFP80RegClass;
21479 // GCC allows "st(0)" to be called just plain "st".
21480 if (StringRef("{st}").equals_lower(Constraint)) {
21481 Res.first = X86::ST0;
21482 Res.second = &X86::RFP80RegClass;
21487 if (StringRef("{flags}").equals_lower(Constraint)) {
21488 Res.first = X86::EFLAGS;
21489 Res.second = &X86::CCRRegClass;
21493 // 'A' means EAX + EDX.
21494 if (Constraint == "A") {
21495 Res.first = X86::EAX;
21496 Res.second = &X86::GR32_ADRegClass;
21502 // Otherwise, check to see if this is a register class of the wrong value
21503 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21504 // turn into {ax},{dx}.
21505 if (Res.second->hasType(VT))
21506 return Res; // Correct type already, nothing to do.
21508 // All of the single-register GCC register classes map their values onto
21509 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21510 // really want an 8-bit or 32-bit register, map to the appropriate register
21511 // class and return the appropriate register.
21512 if (Res.second == &X86::GR16RegClass) {
21513 if (VT == MVT::i8 || VT == MVT::i1) {
21514 unsigned DestReg = 0;
21515 switch (Res.first) {
21517 case X86::AX: DestReg = X86::AL; break;
21518 case X86::DX: DestReg = X86::DL; break;
21519 case X86::CX: DestReg = X86::CL; break;
21520 case X86::BX: DestReg = X86::BL; break;
21523 Res.first = DestReg;
21524 Res.second = &X86::GR8RegClass;
21526 } else if (VT == MVT::i32 || VT == MVT::f32) {
21527 unsigned DestReg = 0;
21528 switch (Res.first) {
21530 case X86::AX: DestReg = X86::EAX; break;
21531 case X86::DX: DestReg = X86::EDX; break;
21532 case X86::CX: DestReg = X86::ECX; break;
21533 case X86::BX: DestReg = X86::EBX; break;
21534 case X86::SI: DestReg = X86::ESI; break;
21535 case X86::DI: DestReg = X86::EDI; break;
21536 case X86::BP: DestReg = X86::EBP; break;
21537 case X86::SP: DestReg = X86::ESP; break;
21540 Res.first = DestReg;
21541 Res.second = &X86::GR32RegClass;
21543 } else if (VT == MVT::i64 || VT == MVT::f64) {
21544 unsigned DestReg = 0;
21545 switch (Res.first) {
21547 case X86::AX: DestReg = X86::RAX; break;
21548 case X86::DX: DestReg = X86::RDX; break;
21549 case X86::CX: DestReg = X86::RCX; break;
21550 case X86::BX: DestReg = X86::RBX; break;
21551 case X86::SI: DestReg = X86::RSI; break;
21552 case X86::DI: DestReg = X86::RDI; break;
21553 case X86::BP: DestReg = X86::RBP; break;
21554 case X86::SP: DestReg = X86::RSP; break;
21557 Res.first = DestReg;
21558 Res.second = &X86::GR64RegClass;
21561 } else if (Res.second == &X86::FR32RegClass ||
21562 Res.second == &X86::FR64RegClass ||
21563 Res.second == &X86::VR128RegClass ||
21564 Res.second == &X86::VR256RegClass ||
21565 Res.second == &X86::FR32XRegClass ||
21566 Res.second == &X86::FR64XRegClass ||
21567 Res.second == &X86::VR128XRegClass ||
21568 Res.second == &X86::VR256XRegClass ||
21569 Res.second == &X86::VR512RegClass) {
21570 // Handle references to XMM physical registers that got mapped into the
21571 // wrong class. This can happen with constraints like {xmm0} where the
21572 // target independent register mapper will just pick the first match it can
21573 // find, ignoring the required type.
21575 if (VT == MVT::f32 || VT == MVT::i32)
21576 Res.second = &X86::FR32RegClass;
21577 else if (VT == MVT::f64 || VT == MVT::i64)
21578 Res.second = &X86::FR64RegClass;
21579 else if (X86::VR128RegClass.hasType(VT))
21580 Res.second = &X86::VR128RegClass;
21581 else if (X86::VR256RegClass.hasType(VT))
21582 Res.second = &X86::VR256RegClass;
21583 else if (X86::VR512RegClass.hasType(VT))
21584 Res.second = &X86::VR512RegClass;
21590 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21592 // Scaling factors are not free at all.
21593 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21594 // will take 2 allocations in the out of order engine instead of 1
21595 // for plain addressing mode, i.e. inst (reg1).
21597 // vaddps (%rsi,%drx), %ymm0, %ymm1
21598 // Requires two allocations (one for the load, one for the computation)
21600 // vaddps (%rsi), %ymm0, %ymm1
21601 // Requires just 1 allocation, i.e., freeing allocations for other operations
21602 // and having less micro operations to execute.
21604 // For some X86 architectures, this is even worse because for instance for
21605 // stores, the complex addressing mode forces the instruction to use the
21606 // "load" ports instead of the dedicated "store" port.
21607 // E.g., on Haswell:
21608 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21609 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21610 if (isLegalAddressingMode(AM, Ty))
21611 // Scale represents reg2 * scale, thus account for 1
21612 // as soon as we use a second register.
21613 return AM.Scale != 0;
21617 bool X86TargetLowering::isTargetFTOL() const {
21618 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();