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 // FIXME: This should stop caching the target machine as soon as
200 // we can remove resetOperationActions et al.
201 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
202 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
203 Subtarget = &TM.getSubtarget<X86Subtarget>();
204 X86ScalarSSEf64 = Subtarget->hasSSE2();
205 X86ScalarSSEf32 = Subtarget->hasSSE1();
206 TD = getDataLayout();
208 resetOperationActions();
211 void X86TargetLowering::resetOperationActions() {
212 const TargetMachine &TM = getTargetMachine();
213 static bool FirstTimeThrough = true;
215 // If none of the target options have changed, then we don't need to reset the
216 // operation actions.
217 if (!FirstTimeThrough && TO == TM.Options) return;
219 if (!FirstTimeThrough) {
220 // Reinitialize the actions.
222 FirstTimeThrough = false;
227 // Set up the TargetLowering object.
228 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
230 // X86 is weird, it always uses i8 for shift amounts and setcc results.
231 setBooleanContents(ZeroOrOneBooleanContent);
232 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
233 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235 // For 64-bit since we have so many registers use the ILP scheduler, for
236 // 32-bit code use the register pressure specific scheduling.
237 // For Atom, always use ILP scheduling.
238 if (Subtarget->isAtom())
239 setSchedulingPreference(Sched::ILP);
240 else if (Subtarget->is64Bit())
241 setSchedulingPreference(Sched::ILP);
243 setSchedulingPreference(Sched::RegPressure);
244 const X86RegisterInfo *RegInfo =
245 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
246 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
248 // Bypass expensive divides on Atom when compiling with O2
249 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
250 addBypassSlowDiv(32, 8);
251 if (Subtarget->is64Bit())
252 addBypassSlowDiv(64, 16);
255 if (Subtarget->isTargetKnownWindowsMSVC()) {
256 // Setup Windows compiler runtime calls.
257 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
258 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
259 setLibcallName(RTLIB::SREM_I64, "_allrem");
260 setLibcallName(RTLIB::UREM_I64, "_aullrem");
261 setLibcallName(RTLIB::MUL_I64, "_allmul");
262 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
266 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
268 // The _ftol2 runtime function has an unusual calling conv, which
269 // is modeled by a special pseudo-instruction.
270 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
273 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
276 if (Subtarget->isTargetDarwin()) {
277 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
278 setUseUnderscoreSetJmp(false);
279 setUseUnderscoreLongJmp(false);
280 } else if (Subtarget->isTargetWindowsGNU()) {
281 // MS runtime is weird: it exports _setjmp, but longjmp!
282 setUseUnderscoreSetJmp(true);
283 setUseUnderscoreLongJmp(false);
285 setUseUnderscoreSetJmp(true);
286 setUseUnderscoreLongJmp(true);
289 // Set up the register classes.
290 addRegisterClass(MVT::i8, &X86::GR8RegClass);
291 addRegisterClass(MVT::i16, &X86::GR16RegClass);
292 addRegisterClass(MVT::i32, &X86::GR32RegClass);
293 if (Subtarget->is64Bit())
294 addRegisterClass(MVT::i64, &X86::GR64RegClass);
296 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
298 // We don't accept any truncstore of integer registers.
299 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
303 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
304 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
306 // SETOEQ and SETUNE require checking two conditions.
307 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
320 if (Subtarget->is64Bit()) {
321 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
322 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
323 } else if (!TM.Options.UseSoftFloat) {
324 // We have an algorithm for SSE2->double, and we turn this into a
325 // 64-bit FILD followed by conditional FADD for other targets.
326 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
327 // We have an algorithm for SSE2, and we turn this into a 64-bit
328 // FILD for other targets.
329 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
332 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
335 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
337 if (!TM.Options.UseSoftFloat) {
338 // SSE has no i16 to fp conversion, only i32
339 if (X86ScalarSSEf32) {
340 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
341 // f32 and f64 cases are Legal, f80 case is not
342 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
352 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
353 // are Legal, f80 is custom lowered.
354 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
355 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
357 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
360 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
362 if (X86ScalarSSEf32) {
363 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
364 // f32 and f64 cases are Legal, f80 case is not
365 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
371 // Handle FP_TO_UINT by promoting the destination to a larger signed
373 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
377 if (Subtarget->is64Bit()) {
378 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
379 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
380 } else if (!TM.Options.UseSoftFloat) {
381 // Since AVX is a superset of SSE3, only check for SSE here.
382 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
383 // Expand FP_TO_UINT into a select.
384 // FIXME: We would like to use a Custom expander here eventually to do
385 // the optimal thing for SSE vs. the default expansion in the legalizer.
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
388 // With SSE3 we can use fisttpll to convert to a signed i64; without
389 // SSE, we're stuck with a fistpll.
390 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
393 if (isTargetFTOL()) {
394 // Use the _ftol2 runtime function, which has a pseudo-instruction
395 // to handle its weird calling convention.
396 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
399 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
400 if (!X86ScalarSSEf64) {
401 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
402 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
403 if (Subtarget->is64Bit()) {
404 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
405 // Without SSE, i64->f64 goes through memory.
406 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
410 // Scalar integer divide and remainder are lowered to use operations that
411 // produce two results, to match the available instructions. This exposes
412 // the two-result form to trivial CSE, which is able to combine x/y and x%y
413 // into a single instruction.
415 // Scalar integer multiply-high is also lowered to use two-result
416 // operations, to match the available instructions. However, plain multiply
417 // (low) operations are left as Legal, as there are single-result
418 // instructions for this in x86. Using the two-result multiply instructions
419 // when both high and low results are needed must be arranged by dagcombine.
420 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422 setOperationAction(ISD::MULHS, VT, Expand);
423 setOperationAction(ISD::MULHU, VT, Expand);
424 setOperationAction(ISD::SDIV, VT, Expand);
425 setOperationAction(ISD::UDIV, VT, Expand);
426 setOperationAction(ISD::SREM, VT, Expand);
427 setOperationAction(ISD::UREM, VT, Expand);
429 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
430 setOperationAction(ISD::ADDC, VT, Custom);
431 setOperationAction(ISD::ADDE, VT, Custom);
432 setOperationAction(ISD::SUBC, VT, Custom);
433 setOperationAction(ISD::SUBE, VT, Custom);
436 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
437 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
438 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
445 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
447 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
448 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
449 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
450 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
451 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
452 if (Subtarget->is64Bit())
453 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
454 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
455 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
456 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
457 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
458 setOperationAction(ISD::FREM , MVT::f32 , Expand);
459 setOperationAction(ISD::FREM , MVT::f64 , Expand);
460 setOperationAction(ISD::FREM , MVT::f80 , Expand);
461 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
463 // Promote the i8 variants and force them on up to i32 which has a shorter
465 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
466 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
467 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
468 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
469 if (Subtarget->hasBMI()) {
470 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
471 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
472 if (Subtarget->is64Bit())
473 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
475 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
476 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
477 if (Subtarget->is64Bit())
478 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
481 if (Subtarget->hasLZCNT()) {
482 // When promoting the i8 variants, force them to i32 for a shorter
484 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
485 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
487 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
493 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
494 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
495 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
497 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
498 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
499 if (Subtarget->is64Bit()) {
500 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
505 if (Subtarget->hasPOPCNT()) {
506 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
508 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
509 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
510 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
511 if (Subtarget->is64Bit())
512 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
515 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
517 if (!Subtarget->hasMOVBE())
518 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
520 // These should be promoted to a larger select which is supported.
521 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
522 // X86 wants to expand cmov itself.
523 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
524 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
525 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
526 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
527 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
528 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
530 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
531 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
532 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
533 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
534 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
535 if (Subtarget->is64Bit()) {
536 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
537 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
539 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
540 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
541 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
542 // support continuation, user-level threading, and etc.. As a result, no
543 // other SjLj exception interfaces are implemented and please don't build
544 // your own exception handling based on them.
545 // LLVM/Clang supports zero-cost DWARF exception handling.
546 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
547 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
550 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
551 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
552 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
553 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
554 if (Subtarget->is64Bit())
555 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
556 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
557 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
558 if (Subtarget->is64Bit()) {
559 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
560 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
561 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
562 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
563 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
565 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
566 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
567 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
568 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
569 if (Subtarget->is64Bit()) {
570 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
571 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
572 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
575 if (Subtarget->hasSSE1())
576 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
578 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
580 // Expand certain atomics
581 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
583 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
585 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
588 if (!Subtarget->is64Bit()) {
589 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
595 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
596 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
597 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
598 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
599 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
600 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
603 if (Subtarget->hasCmpxchg16b()) {
604 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
607 // FIXME - use subtarget debug flags
608 if (!Subtarget->isTargetDarwin() &&
609 !Subtarget->isTargetELF() &&
610 !Subtarget->isTargetCygMing()) {
611 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
614 if (Subtarget->is64Bit()) {
615 setExceptionPointerRegister(X86::RAX);
616 setExceptionSelectorRegister(X86::RDX);
618 setExceptionPointerRegister(X86::EAX);
619 setExceptionSelectorRegister(X86::EDX);
621 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
622 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
624 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
625 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
627 setOperationAction(ISD::TRAP, MVT::Other, Legal);
628 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
630 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
631 setOperationAction(ISD::VASTART , MVT::Other, Custom);
632 setOperationAction(ISD::VAEND , MVT::Other, Expand);
633 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
634 // TargetInfo::X86_64ABIBuiltinVaList
635 setOperationAction(ISD::VAARG , MVT::Other, Custom);
636 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
638 // TargetInfo::CharPtrBuiltinVaList
639 setOperationAction(ISD::VAARG , MVT::Other, Expand);
640 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
643 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
644 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
646 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
647 MVT::i64 : MVT::i32, Custom);
649 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
650 // f32 and f64 use SSE.
651 // Set up the FP register classes.
652 addRegisterClass(MVT::f32, &X86::FR32RegClass);
653 addRegisterClass(MVT::f64, &X86::FR64RegClass);
655 // Use ANDPD to simulate FABS.
656 setOperationAction(ISD::FABS , MVT::f64, Custom);
657 setOperationAction(ISD::FABS , MVT::f32, Custom);
659 // Use XORP to simulate FNEG.
660 setOperationAction(ISD::FNEG , MVT::f64, Custom);
661 setOperationAction(ISD::FNEG , MVT::f32, Custom);
663 // Use ANDPD and ORPD to simulate FCOPYSIGN.
664 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
665 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
667 // Lower this to FGETSIGNx86 plus an AND.
668 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
669 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
671 // We don't support sin/cos/fmod
672 setOperationAction(ISD::FSIN , MVT::f64, Expand);
673 setOperationAction(ISD::FCOS , MVT::f64, Expand);
674 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
675 setOperationAction(ISD::FSIN , MVT::f32, Expand);
676 setOperationAction(ISD::FCOS , MVT::f32, Expand);
677 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
679 // Expand FP immediates into loads from the stack, except for the special
681 addLegalFPImmediate(APFloat(+0.0)); // xorpd
682 addLegalFPImmediate(APFloat(+0.0f)); // xorps
683 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
684 // Use SSE for f32, x87 for f64.
685 // Set up the FP register classes.
686 addRegisterClass(MVT::f32, &X86::FR32RegClass);
687 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
689 // Use ANDPS to simulate FABS.
690 setOperationAction(ISD::FABS , MVT::f32, Custom);
692 // Use XORP to simulate FNEG.
693 setOperationAction(ISD::FNEG , MVT::f32, Custom);
695 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
697 // Use ANDPS and ORPS to simulate FCOPYSIGN.
698 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
699 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
701 // We don't support sin/cos/fmod
702 setOperationAction(ISD::FSIN , MVT::f32, Expand);
703 setOperationAction(ISD::FCOS , MVT::f32, Expand);
704 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
706 // Special cases we handle for FP constants.
707 addLegalFPImmediate(APFloat(+0.0f)); // xorps
708 addLegalFPImmediate(APFloat(+0.0)); // FLD0
709 addLegalFPImmediate(APFloat(+1.0)); // FLD1
710 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
711 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
713 if (!TM.Options.UnsafeFPMath) {
714 setOperationAction(ISD::FSIN , MVT::f64, Expand);
715 setOperationAction(ISD::FCOS , MVT::f64, Expand);
716 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
718 } else if (!TM.Options.UseSoftFloat) {
719 // f32 and f64 in x87.
720 // Set up the FP register classes.
721 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
722 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
724 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
725 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
726 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
727 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
729 if (!TM.Options.UnsafeFPMath) {
730 setOperationAction(ISD::FSIN , MVT::f64, Expand);
731 setOperationAction(ISD::FSIN , MVT::f32, Expand);
732 setOperationAction(ISD::FCOS , MVT::f64, Expand);
733 setOperationAction(ISD::FCOS , MVT::f32, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
735 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
737 addLegalFPImmediate(APFloat(+0.0)); // FLD0
738 addLegalFPImmediate(APFloat(+1.0)); // FLD1
739 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
740 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
741 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
742 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
743 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
744 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
747 // We don't support FMA.
748 setOperationAction(ISD::FMA, MVT::f64, Expand);
749 setOperationAction(ISD::FMA, MVT::f32, Expand);
751 // Long double always uses X87.
752 if (!TM.Options.UseSoftFloat) {
753 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
754 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
755 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
757 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
758 addLegalFPImmediate(TmpFlt); // FLD0
760 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
763 APFloat TmpFlt2(+1.0);
764 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
766 addLegalFPImmediate(TmpFlt2); // FLD1
767 TmpFlt2.changeSign();
768 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
771 if (!TM.Options.UnsafeFPMath) {
772 setOperationAction(ISD::FSIN , MVT::f80, Expand);
773 setOperationAction(ISD::FCOS , MVT::f80, Expand);
774 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
777 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
778 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
779 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
780 setOperationAction(ISD::FRINT, MVT::f80, Expand);
781 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
782 setOperationAction(ISD::FMA, MVT::f80, Expand);
785 // Always use a library call for pow.
786 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
787 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
788 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
790 setOperationAction(ISD::FLOG, MVT::f80, Expand);
791 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
792 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
793 setOperationAction(ISD::FEXP, MVT::f80, Expand);
794 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
796 // First set operation action for all vector types to either promote
797 // (for widening) or expand (for scalarization). Then we will selectively
798 // turn on ones that can be effectively codegen'd.
799 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
800 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
801 MVT VT = (MVT::SimpleValueType)i;
802 setOperationAction(ISD::ADD , VT, Expand);
803 setOperationAction(ISD::SUB , VT, Expand);
804 setOperationAction(ISD::FADD, VT, Expand);
805 setOperationAction(ISD::FNEG, VT, Expand);
806 setOperationAction(ISD::FSUB, VT, Expand);
807 setOperationAction(ISD::MUL , VT, Expand);
808 setOperationAction(ISD::FMUL, VT, Expand);
809 setOperationAction(ISD::SDIV, VT, Expand);
810 setOperationAction(ISD::UDIV, VT, Expand);
811 setOperationAction(ISD::FDIV, VT, Expand);
812 setOperationAction(ISD::SREM, VT, Expand);
813 setOperationAction(ISD::UREM, VT, Expand);
814 setOperationAction(ISD::LOAD, VT, Expand);
815 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
816 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
817 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
818 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
819 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
820 setOperationAction(ISD::FABS, VT, Expand);
821 setOperationAction(ISD::FSIN, VT, Expand);
822 setOperationAction(ISD::FSINCOS, VT, Expand);
823 setOperationAction(ISD::FCOS, VT, Expand);
824 setOperationAction(ISD::FSINCOS, VT, Expand);
825 setOperationAction(ISD::FREM, VT, Expand);
826 setOperationAction(ISD::FMA, VT, Expand);
827 setOperationAction(ISD::FPOWI, VT, Expand);
828 setOperationAction(ISD::FSQRT, VT, Expand);
829 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
830 setOperationAction(ISD::FFLOOR, VT, Expand);
831 setOperationAction(ISD::FCEIL, VT, Expand);
832 setOperationAction(ISD::FTRUNC, VT, Expand);
833 setOperationAction(ISD::FRINT, VT, Expand);
834 setOperationAction(ISD::FNEARBYINT, VT, Expand);
835 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::MULHS, VT, Expand);
837 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
838 setOperationAction(ISD::MULHU, VT, Expand);
839 setOperationAction(ISD::SDIVREM, VT, Expand);
840 setOperationAction(ISD::UDIVREM, VT, Expand);
841 setOperationAction(ISD::FPOW, VT, Expand);
842 setOperationAction(ISD::CTPOP, VT, Expand);
843 setOperationAction(ISD::CTTZ, VT, Expand);
844 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
845 setOperationAction(ISD::CTLZ, VT, Expand);
846 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
847 setOperationAction(ISD::SHL, VT, Expand);
848 setOperationAction(ISD::SRA, VT, Expand);
849 setOperationAction(ISD::SRL, VT, Expand);
850 setOperationAction(ISD::ROTL, VT, Expand);
851 setOperationAction(ISD::ROTR, VT, Expand);
852 setOperationAction(ISD::BSWAP, VT, Expand);
853 setOperationAction(ISD::SETCC, VT, Expand);
854 setOperationAction(ISD::FLOG, VT, Expand);
855 setOperationAction(ISD::FLOG2, VT, Expand);
856 setOperationAction(ISD::FLOG10, VT, Expand);
857 setOperationAction(ISD::FEXP, VT, Expand);
858 setOperationAction(ISD::FEXP2, VT, Expand);
859 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
860 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
861 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
862 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
863 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
864 setOperationAction(ISD::TRUNCATE, VT, Expand);
865 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
866 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
867 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
868 setOperationAction(ISD::VSELECT, VT, Expand);
869 setOperationAction(ISD::SELECT_CC, VT, Expand);
870 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
871 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
872 setTruncStoreAction(VT,
873 (MVT::SimpleValueType)InnerVT, Expand);
874 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
875 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
876 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
879 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
880 // with -msoft-float, disable use of MMX as well.
881 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
882 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
883 // No operations on x86mmx supported, everything uses intrinsics.
886 // MMX-sized vectors (other than x86mmx) are expected to be expanded
887 // into smaller operations.
888 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
889 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
890 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
891 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
892 setOperationAction(ISD::AND, MVT::v8i8, Expand);
893 setOperationAction(ISD::AND, MVT::v4i16, Expand);
894 setOperationAction(ISD::AND, MVT::v2i32, Expand);
895 setOperationAction(ISD::AND, MVT::v1i64, Expand);
896 setOperationAction(ISD::OR, MVT::v8i8, Expand);
897 setOperationAction(ISD::OR, MVT::v4i16, Expand);
898 setOperationAction(ISD::OR, MVT::v2i32, Expand);
899 setOperationAction(ISD::OR, MVT::v1i64, Expand);
900 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
901 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
902 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
903 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
904 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
905 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
906 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
907 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
908 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
909 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
910 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
911 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
912 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
913 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
914 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
915 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
916 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
918 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
919 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
921 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
922 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
923 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
924 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
925 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
926 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
927 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
928 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
929 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
930 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
931 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
932 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
935 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
936 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
938 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
939 // registers cannot be used even for integer operations.
940 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
941 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
942 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
943 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
945 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
946 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
947 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
948 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
949 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
950 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
951 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
952 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
953 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
954 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
955 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
956 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
957 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
958 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
959 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
960 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
961 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
962 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
963 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
964 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
965 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
966 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
968 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
969 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
970 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
971 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
973 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
974 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
975 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
976 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
977 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
979 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
980 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
981 MVT VT = (MVT::SimpleValueType)i;
982 // Do not attempt to custom lower non-power-of-2 vectors
983 if (!isPowerOf2_32(VT.getVectorNumElements()))
985 // Do not attempt to custom lower non-128-bit vectors
986 if (!VT.is128BitVector())
988 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
993 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
994 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
995 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
996 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1000 if (Subtarget->is64Bit()) {
1001 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1005 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1006 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1007 MVT VT = (MVT::SimpleValueType)i;
1009 // Do not attempt to promote non-128-bit vectors
1010 if (!VT.is128BitVector())
1013 setOperationAction(ISD::AND, VT, Promote);
1014 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1015 setOperationAction(ISD::OR, VT, Promote);
1016 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1017 setOperationAction(ISD::XOR, VT, Promote);
1018 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1019 setOperationAction(ISD::LOAD, VT, Promote);
1020 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1021 setOperationAction(ISD::SELECT, VT, Promote);
1022 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1025 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1027 // Custom lower v2i64 and v2f64 selects.
1028 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1029 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1030 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1031 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1033 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1034 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1036 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1037 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1038 // As there is no 64-bit GPR available, we need build a special custom
1039 // sequence to convert from v2i32 to v2f32.
1040 if (!Subtarget->is64Bit())
1041 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1043 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1044 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1046 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1048 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1049 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1050 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1053 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1054 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1055 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1056 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1057 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1058 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1059 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1060 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1061 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1062 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1063 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1065 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1066 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1067 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1068 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1069 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1070 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1071 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1072 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1073 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1074 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1076 // FIXME: Do we need to handle scalar-to-vector here?
1077 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1079 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1080 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1081 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1082 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1083 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1084 // There is no BLENDI for byte vectors. We don't need to custom lower
1085 // some vselects for now.
1086 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1088 // i8 and i16 vectors are custom , because the source register and source
1089 // source memory operand types are not the same width. f32 vectors are
1090 // custom since the immediate controlling the insert encodes additional
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1093 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1094 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1095 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1098 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1099 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1100 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1102 // FIXME: these should be Legal but thats only for the case where
1103 // the index is constant. For now custom expand to deal with that.
1104 if (Subtarget->is64Bit()) {
1105 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1106 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1110 if (Subtarget->hasSSE2()) {
1111 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1112 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1114 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1115 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1117 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1118 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1120 // In the customized shift lowering, the legal cases in AVX2 will be
1122 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1123 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1125 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1126 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1128 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1131 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1132 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1133 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1134 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1135 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1136 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1137 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1139 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1140 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1141 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1143 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1148 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1152 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1153 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1154 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1156 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1161 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1165 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1167 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1169 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1170 // even though v8i16 is a legal type.
1171 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1172 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1173 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1175 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1176 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1177 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1179 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1180 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1182 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1184 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1185 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1187 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1188 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1190 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1191 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1193 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1194 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1195 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1196 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1198 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1199 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1200 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1202 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1203 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1204 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1205 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1207 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1208 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1209 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1210 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1211 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1212 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1213 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1214 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1215 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1216 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1217 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1218 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1220 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1221 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1222 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1223 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1224 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1225 setOperationAction(ISD::FMA, MVT::f32, Legal);
1226 setOperationAction(ISD::FMA, MVT::f64, Legal);
1229 if (Subtarget->hasInt256()) {
1230 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1231 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1232 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1233 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1235 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1236 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1237 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1238 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1240 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1241 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1242 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1243 // Don't lower v32i8 because there is no 128-bit byte mul
1245 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1247 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1248 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1250 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1251 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1253 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1254 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1255 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1256 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1258 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1259 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1260 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1261 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1263 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1264 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1265 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1266 // Don't lower v32i8 because there is no 128-bit byte mul
1269 // In the customized shift lowering, the legal cases in AVX2 will be
1271 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1272 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1274 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1275 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1277 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1279 // Custom lower several nodes for 256-bit types.
1280 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1281 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1282 MVT VT = (MVT::SimpleValueType)i;
1284 // Extract subvector is special because the value type
1285 // (result) is 128-bit but the source is 256-bit wide.
1286 if (VT.is128BitVector())
1287 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1289 // Do not attempt to custom lower other non-256-bit vectors
1290 if (!VT.is256BitVector())
1293 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1294 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1295 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1296 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1297 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1298 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1299 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1302 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1303 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1304 MVT VT = (MVT::SimpleValueType)i;
1306 // Do not attempt to promote non-256-bit vectors
1307 if (!VT.is256BitVector())
1310 setOperationAction(ISD::AND, VT, Promote);
1311 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1312 setOperationAction(ISD::OR, VT, Promote);
1313 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1314 setOperationAction(ISD::XOR, VT, Promote);
1315 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1316 setOperationAction(ISD::LOAD, VT, Promote);
1317 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1318 setOperationAction(ISD::SELECT, VT, Promote);
1319 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1323 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1324 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1325 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1326 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1327 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1329 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1330 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1331 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1333 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1334 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1335 setOperationAction(ISD::XOR, MVT::i1, Legal);
1336 setOperationAction(ISD::OR, MVT::i1, Legal);
1337 setOperationAction(ISD::AND, MVT::i1, Legal);
1338 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1341 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1342 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1343 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1345 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1349 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1350 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1352 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1355 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1356 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1357 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1358 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1359 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1361 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1362 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1364 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1365 if (Subtarget->is64Bit()) {
1366 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1367 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1368 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1371 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1373 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1374 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1376 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1377 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1378 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1379 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1380 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1382 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1383 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1384 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1385 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1386 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1387 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1388 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1389 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1390 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1391 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1392 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1393 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1394 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1396 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1397 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1398 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1399 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1400 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1401 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1403 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1404 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1406 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1408 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1409 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1410 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1411 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1412 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1413 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1414 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1415 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1416 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1418 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1419 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1421 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1422 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1424 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1426 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1427 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1429 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1430 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1432 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1435 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1436 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1437 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1438 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1439 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1440 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1442 if (Subtarget->hasCDI()) {
1443 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1444 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1447 // Custom lower several nodes.
1448 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1449 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1450 MVT VT = (MVT::SimpleValueType)i;
1452 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453 // Extract subvector is special because the value type
1454 // (result) is 256/128-bit but the source is 512-bit wide.
1455 if (VT.is128BitVector() || VT.is256BitVector())
1456 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1458 if (VT.getVectorElementType() == MVT::i1)
1459 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1461 // Do not attempt to custom lower other non-512-bit vectors
1462 if (!VT.is512BitVector())
1465 if ( EltSize >= 32) {
1466 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1467 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1468 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1469 setOperationAction(ISD::VSELECT, VT, Legal);
1470 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1471 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1472 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1475 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1476 MVT VT = (MVT::SimpleValueType)i;
1478 // Do not attempt to promote non-256-bit vectors
1479 if (!VT.is512BitVector())
1482 setOperationAction(ISD::SELECT, VT, Promote);
1483 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1487 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1488 // of this type with custom code.
1489 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1490 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1491 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1495 // We want to custom lower some of our intrinsics.
1496 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1497 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1498 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1499 if (!Subtarget->is64Bit())
1500 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1502 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1503 // handle type legalization for these operations here.
1505 // FIXME: We really should do custom legalization for addition and
1506 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1507 // than generic legalization for 64-bit multiplication-with-overflow, though.
1508 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1509 // Add/Sub/Mul with overflow operations are custom lowered.
1511 setOperationAction(ISD::SADDO, VT, Custom);
1512 setOperationAction(ISD::UADDO, VT, Custom);
1513 setOperationAction(ISD::SSUBO, VT, Custom);
1514 setOperationAction(ISD::USUBO, VT, Custom);
1515 setOperationAction(ISD::SMULO, VT, Custom);
1516 setOperationAction(ISD::UMULO, VT, Custom);
1519 // There are no 8-bit 3-address imul/mul instructions
1520 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1521 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1523 if (!Subtarget->is64Bit()) {
1524 // These libcalls are not available in 32-bit.
1525 setLibcallName(RTLIB::SHL_I128, nullptr);
1526 setLibcallName(RTLIB::SRL_I128, nullptr);
1527 setLibcallName(RTLIB::SRA_I128, nullptr);
1530 // Combine sin / cos into one node or libcall if possible.
1531 if (Subtarget->hasSinCos()) {
1532 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1533 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1534 if (Subtarget->isTargetDarwin()) {
1535 // For MacOSX, we don't want to the normal expansion of a libcall to
1536 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1538 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1539 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1543 if (Subtarget->isTargetWin64()) {
1544 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1545 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1546 setOperationAction(ISD::SREM, MVT::i128, Custom);
1547 setOperationAction(ISD::UREM, MVT::i128, Custom);
1548 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1549 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1552 // We have target-specific dag combine patterns for the following nodes:
1553 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1554 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1555 setTargetDAGCombine(ISD::VSELECT);
1556 setTargetDAGCombine(ISD::SELECT);
1557 setTargetDAGCombine(ISD::SHL);
1558 setTargetDAGCombine(ISD::SRA);
1559 setTargetDAGCombine(ISD::SRL);
1560 setTargetDAGCombine(ISD::OR);
1561 setTargetDAGCombine(ISD::AND);
1562 setTargetDAGCombine(ISD::ADD);
1563 setTargetDAGCombine(ISD::FADD);
1564 setTargetDAGCombine(ISD::FSUB);
1565 setTargetDAGCombine(ISD::FMA);
1566 setTargetDAGCombine(ISD::SUB);
1567 setTargetDAGCombine(ISD::LOAD);
1568 setTargetDAGCombine(ISD::STORE);
1569 setTargetDAGCombine(ISD::ZERO_EXTEND);
1570 setTargetDAGCombine(ISD::ANY_EXTEND);
1571 setTargetDAGCombine(ISD::SIGN_EXTEND);
1572 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1573 setTargetDAGCombine(ISD::TRUNCATE);
1574 setTargetDAGCombine(ISD::SINT_TO_FP);
1575 setTargetDAGCombine(ISD::SETCC);
1576 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1577 setTargetDAGCombine(ISD::BUILD_VECTOR);
1578 if (Subtarget->is64Bit())
1579 setTargetDAGCombine(ISD::MUL);
1580 setTargetDAGCombine(ISD::XOR);
1582 computeRegisterProperties();
1584 // On Darwin, -Os means optimize for size without hurting performance,
1585 // do not reduce the limit.
1586 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1587 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1588 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1589 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1590 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1591 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1592 setPrefLoopAlignment(4); // 2^4 bytes.
1594 // Predictable cmov don't hurt on atom because it's in-order.
1595 PredictableSelectIsExpensive = !Subtarget->isAtom();
1597 setPrefFunctionAlignment(4); // 2^4 bytes.
1600 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1602 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1604 if (Subtarget->hasAVX512())
1605 switch(VT.getVectorNumElements()) {
1606 case 8: return MVT::v8i1;
1607 case 16: return MVT::v16i1;
1610 return VT.changeVectorElementTypeToInteger();
1613 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1614 /// the desired ByVal argument alignment.
1615 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1618 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1619 if (VTy->getBitWidth() == 128)
1621 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1622 unsigned EltAlign = 0;
1623 getMaxByValAlign(ATy->getElementType(), EltAlign);
1624 if (EltAlign > MaxAlign)
1625 MaxAlign = EltAlign;
1626 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1627 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1628 unsigned EltAlign = 0;
1629 getMaxByValAlign(STy->getElementType(i), EltAlign);
1630 if (EltAlign > MaxAlign)
1631 MaxAlign = EltAlign;
1638 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1639 /// function arguments in the caller parameter area. For X86, aggregates
1640 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1641 /// are at 4-byte boundaries.
1642 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1643 if (Subtarget->is64Bit()) {
1644 // Max of 8 and alignment of type.
1645 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1652 if (Subtarget->hasSSE1())
1653 getMaxByValAlign(Ty, Align);
1657 /// getOptimalMemOpType - Returns the target specific optimal type for load
1658 /// and store operations as a result of memset, memcpy, and memmove
1659 /// lowering. If DstAlign is zero that means it's safe to destination
1660 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1661 /// means there isn't a need to check it against alignment requirement,
1662 /// probably because the source does not need to be loaded. If 'IsMemset' is
1663 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1664 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1665 /// source is constant so it does not need to be loaded.
1666 /// It returns EVT::Other if the type should be determined using generic
1667 /// target-independent logic.
1669 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1670 unsigned DstAlign, unsigned SrcAlign,
1671 bool IsMemset, bool ZeroMemset,
1673 MachineFunction &MF) const {
1674 const Function *F = MF.getFunction();
1675 if ((!IsMemset || ZeroMemset) &&
1676 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1677 Attribute::NoImplicitFloat)) {
1679 (Subtarget->isUnalignedMemAccessFast() ||
1680 ((DstAlign == 0 || DstAlign >= 16) &&
1681 (SrcAlign == 0 || SrcAlign >= 16)))) {
1683 if (Subtarget->hasInt256())
1685 if (Subtarget->hasFp256())
1688 if (Subtarget->hasSSE2())
1690 if (Subtarget->hasSSE1())
1692 } else if (!MemcpyStrSrc && Size >= 8 &&
1693 !Subtarget->is64Bit() &&
1694 Subtarget->hasSSE2()) {
1695 // Do not use f64 to lower memcpy if source is string constant. It's
1696 // better to use i32 to avoid the loads.
1700 if (Subtarget->is64Bit() && Size >= 8)
1705 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1707 return X86ScalarSSEf32;
1708 else if (VT == MVT::f64)
1709 return X86ScalarSSEf64;
1714 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1718 *Fast = Subtarget->isUnalignedMemAccessFast();
1722 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1723 /// current function. The returned value is a member of the
1724 /// MachineJumpTableInfo::JTEntryKind enum.
1725 unsigned X86TargetLowering::getJumpTableEncoding() const {
1726 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1728 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1729 Subtarget->isPICStyleGOT())
1730 return MachineJumpTableInfo::EK_Custom32;
1732 // Otherwise, use the normal jump table encoding heuristics.
1733 return TargetLowering::getJumpTableEncoding();
1737 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1738 const MachineBasicBlock *MBB,
1739 unsigned uid,MCContext &Ctx) const{
1740 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1741 Subtarget->isPICStyleGOT());
1742 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1744 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1745 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1748 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1750 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1751 SelectionDAG &DAG) const {
1752 if (!Subtarget->is64Bit())
1753 // This doesn't have SDLoc associated with it, but is not really the
1754 // same as a Register.
1755 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1759 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1760 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1762 const MCExpr *X86TargetLowering::
1763 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1764 MCContext &Ctx) const {
1765 // X86-64 uses RIP relative addressing based on the jump table label.
1766 if (Subtarget->isPICStyleRIPRel())
1767 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1769 // Otherwise, the reference is relative to the PIC base.
1770 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1773 // FIXME: Why this routine is here? Move to RegInfo!
1774 std::pair<const TargetRegisterClass*, uint8_t>
1775 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1776 const TargetRegisterClass *RRC = nullptr;
1778 switch (VT.SimpleTy) {
1780 return TargetLowering::findRepresentativeClass(VT);
1781 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1782 RRC = Subtarget->is64Bit() ?
1783 (const TargetRegisterClass*)&X86::GR64RegClass :
1784 (const TargetRegisterClass*)&X86::GR32RegClass;
1787 RRC = &X86::VR64RegClass;
1789 case MVT::f32: case MVT::f64:
1790 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1791 case MVT::v4f32: case MVT::v2f64:
1792 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1794 RRC = &X86::VR128RegClass;
1797 return std::make_pair(RRC, Cost);
1800 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1801 unsigned &Offset) const {
1802 if (!Subtarget->isTargetLinux())
1805 if (Subtarget->is64Bit()) {
1806 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1808 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1820 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1821 unsigned DestAS) const {
1822 assert(SrcAS != DestAS && "Expected different address spaces!");
1824 return SrcAS < 256 && DestAS < 256;
1827 //===----------------------------------------------------------------------===//
1828 // Return Value Calling Convention Implementation
1829 //===----------------------------------------------------------------------===//
1831 #include "X86GenCallingConv.inc"
1834 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1835 MachineFunction &MF, bool isVarArg,
1836 const SmallVectorImpl<ISD::OutputArg> &Outs,
1837 LLVMContext &Context) const {
1838 SmallVector<CCValAssign, 16> RVLocs;
1839 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1841 return CCInfo.CheckReturn(Outs, RetCC_X86);
1844 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1845 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1850 X86TargetLowering::LowerReturn(SDValue Chain,
1851 CallingConv::ID CallConv, bool isVarArg,
1852 const SmallVectorImpl<ISD::OutputArg> &Outs,
1853 const SmallVectorImpl<SDValue> &OutVals,
1854 SDLoc dl, SelectionDAG &DAG) const {
1855 MachineFunction &MF = DAG.getMachineFunction();
1856 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1858 SmallVector<CCValAssign, 16> RVLocs;
1859 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1860 RVLocs, *DAG.getContext());
1861 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1864 SmallVector<SDValue, 6> RetOps;
1865 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1866 // Operand #1 = Bytes To Pop
1867 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1870 // Copy the result values into the output registers.
1871 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1872 CCValAssign &VA = RVLocs[i];
1873 assert(VA.isRegLoc() && "Can only return in registers!");
1874 SDValue ValToCopy = OutVals[i];
1875 EVT ValVT = ValToCopy.getValueType();
1877 // Promote values to the appropriate types
1878 if (VA.getLocInfo() == CCValAssign::SExt)
1879 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1880 else if (VA.getLocInfo() == CCValAssign::ZExt)
1881 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1882 else if (VA.getLocInfo() == CCValAssign::AExt)
1883 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1884 else if (VA.getLocInfo() == CCValAssign::BCvt)
1885 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1887 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1888 "Unexpected FP-extend for return value.");
1890 // If this is x86-64, and we disabled SSE, we can't return FP values,
1891 // or SSE or MMX vectors.
1892 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1893 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1894 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1895 report_fatal_error("SSE register return with SSE disabled");
1897 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1898 // llvm-gcc has never done it right and no one has noticed, so this
1899 // should be OK for now.
1900 if (ValVT == MVT::f64 &&
1901 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1902 report_fatal_error("SSE2 register return with SSE2 disabled");
1904 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1905 // the RET instruction and handled by the FP Stackifier.
1906 if (VA.getLocReg() == X86::ST0 ||
1907 VA.getLocReg() == X86::ST1) {
1908 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1909 // change the value to the FP stack register class.
1910 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1911 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1912 RetOps.push_back(ValToCopy);
1913 // Don't emit a copytoreg.
1917 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1918 // which is returned in RAX / RDX.
1919 if (Subtarget->is64Bit()) {
1920 if (ValVT == MVT::x86mmx) {
1921 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1922 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1923 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1925 // If we don't have SSE2 available, convert to v4f32 so the generated
1926 // register is legal.
1927 if (!Subtarget->hasSSE2())
1928 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1933 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1934 Flag = Chain.getValue(1);
1935 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1938 // The x86-64 ABIs require that for returning structs by value we copy
1939 // the sret argument into %rax/%eax (depending on ABI) for the return.
1940 // Win32 requires us to put the sret argument to %eax as well.
1941 // We saved the argument into a virtual register in the entry block,
1942 // so now we copy the value out and into %rax/%eax.
1943 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1944 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1945 MachineFunction &MF = DAG.getMachineFunction();
1946 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1947 unsigned Reg = FuncInfo->getSRetReturnReg();
1949 "SRetReturnReg should have been set in LowerFormalArguments().");
1950 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1953 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1954 X86::RAX : X86::EAX;
1955 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1956 Flag = Chain.getValue(1);
1958 // RAX/EAX now acts like a return value.
1959 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1962 RetOps[0] = Chain; // Update chain.
1964 // Add the flag if we have it.
1966 RetOps.push_back(Flag);
1968 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1971 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1972 if (N->getNumValues() != 1)
1974 if (!N->hasNUsesOfValue(1, 0))
1977 SDValue TCChain = Chain;
1978 SDNode *Copy = *N->use_begin();
1979 if (Copy->getOpcode() == ISD::CopyToReg) {
1980 // If the copy has a glue operand, we conservatively assume it isn't safe to
1981 // perform a tail call.
1982 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1984 TCChain = Copy->getOperand(0);
1985 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1988 bool HasRet = false;
1989 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1991 if (UI->getOpcode() != X86ISD::RET_FLAG)
2004 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2005 ISD::NodeType ExtendKind) const {
2007 // TODO: Is this also valid on 32-bit?
2008 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2009 ReturnMVT = MVT::i8;
2011 ReturnMVT = MVT::i32;
2013 MVT MinVT = getRegisterType(ReturnMVT);
2014 return VT.bitsLT(MinVT) ? MinVT : VT;
2017 /// LowerCallResult - Lower the result values of a call into the
2018 /// appropriate copies out of appropriate physical registers.
2021 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2022 CallingConv::ID CallConv, bool isVarArg,
2023 const SmallVectorImpl<ISD::InputArg> &Ins,
2024 SDLoc dl, SelectionDAG &DAG,
2025 SmallVectorImpl<SDValue> &InVals) const {
2027 // Assign locations to each value returned by this call.
2028 SmallVector<CCValAssign, 16> RVLocs;
2029 bool Is64Bit = Subtarget->is64Bit();
2030 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2031 DAG.getTarget(), RVLocs, *DAG.getContext());
2032 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2034 // Copy all of the result registers out of their specified physreg.
2035 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2036 CCValAssign &VA = RVLocs[i];
2037 EVT CopyVT = VA.getValVT();
2039 // If this is x86-64, and we disabled SSE, we can't return FP values
2040 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2041 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2042 report_fatal_error("SSE register return with SSE disabled");
2047 // If this is a call to a function that returns an fp value on the floating
2048 // point stack, we must guarantee the value is popped from the stack, so
2049 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2050 // if the return value is not used. We use the FpPOP_RETVAL instruction
2052 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2053 // If we prefer to use the value in xmm registers, copy it out as f80 and
2054 // use a truncate to move it from fp stack reg to xmm reg.
2055 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2056 SDValue Ops[] = { Chain, InFlag };
2057 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2058 MVT::Other, MVT::Glue, Ops), 1);
2059 Val = Chain.getValue(0);
2061 // Round the f80 to the right size, which also moves it to the appropriate
2063 if (CopyVT != VA.getValVT())
2064 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2065 // This truncation won't change the value.
2066 DAG.getIntPtrConstant(1));
2068 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2069 CopyVT, InFlag).getValue(1);
2070 Val = Chain.getValue(0);
2072 InFlag = Chain.getValue(2);
2073 InVals.push_back(Val);
2079 //===----------------------------------------------------------------------===//
2080 // C & StdCall & Fast Calling Convention implementation
2081 //===----------------------------------------------------------------------===//
2082 // StdCall calling convention seems to be standard for many Windows' API
2083 // routines and around. It differs from C calling convention just a little:
2084 // callee should clean up the stack, not caller. Symbols should be also
2085 // decorated in some fancy way :) It doesn't support any vector arguments.
2086 // For info on fast calling convention see Fast Calling Convention (tail call)
2087 // implementation LowerX86_32FastCCCallTo.
2089 /// CallIsStructReturn - Determines whether a call uses struct return
2091 enum StructReturnType {
2096 static StructReturnType
2097 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2099 return NotStructReturn;
2101 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2102 if (!Flags.isSRet())
2103 return NotStructReturn;
2104 if (Flags.isInReg())
2105 return RegStructReturn;
2106 return StackStructReturn;
2109 /// ArgsAreStructReturn - Determines whether a function uses struct
2110 /// return semantics.
2111 static StructReturnType
2112 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2114 return NotStructReturn;
2116 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2117 if (!Flags.isSRet())
2118 return NotStructReturn;
2119 if (Flags.isInReg())
2120 return RegStructReturn;
2121 return StackStructReturn;
2124 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2125 /// by "Src" to address "Dst" with size and alignment information specified by
2126 /// the specific parameter attribute. The copy will be passed as a byval
2127 /// function parameter.
2129 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2130 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2132 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2134 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2135 /*isVolatile*/false, /*AlwaysInline=*/true,
2136 MachinePointerInfo(), MachinePointerInfo());
2139 /// IsTailCallConvention - Return true if the calling convention is one that
2140 /// supports tail call optimization.
2141 static bool IsTailCallConvention(CallingConv::ID CC) {
2142 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2143 CC == CallingConv::HiPE);
2146 /// \brief Return true if the calling convention is a C calling convention.
2147 static bool IsCCallConvention(CallingConv::ID CC) {
2148 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2149 CC == CallingConv::X86_64_SysV);
2152 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2153 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2157 CallingConv::ID CalleeCC = CS.getCallingConv();
2158 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2164 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2165 /// a tailcall target by changing its ABI.
2166 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2167 bool GuaranteedTailCallOpt) {
2168 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2172 X86TargetLowering::LowerMemArgument(SDValue Chain,
2173 CallingConv::ID CallConv,
2174 const SmallVectorImpl<ISD::InputArg> &Ins,
2175 SDLoc dl, SelectionDAG &DAG,
2176 const CCValAssign &VA,
2177 MachineFrameInfo *MFI,
2179 // Create the nodes corresponding to a load from this parameter slot.
2180 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2181 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2182 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2183 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2186 // If value is passed by pointer we have address passed instead of the value
2188 if (VA.getLocInfo() == CCValAssign::Indirect)
2189 ValVT = VA.getLocVT();
2191 ValVT = VA.getValVT();
2193 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2194 // changed with more analysis.
2195 // In case of tail call optimization mark all arguments mutable. Since they
2196 // could be overwritten by lowering of arguments in case of a tail call.
2197 if (Flags.isByVal()) {
2198 unsigned Bytes = Flags.getByValSize();
2199 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2200 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2201 return DAG.getFrameIndex(FI, getPointerTy());
2203 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2204 VA.getLocMemOffset(), isImmutable);
2205 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2206 return DAG.getLoad(ValVT, dl, Chain, FIN,
2207 MachinePointerInfo::getFixedStack(FI),
2208 false, false, false, 0);
2213 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2214 CallingConv::ID CallConv,
2216 const SmallVectorImpl<ISD::InputArg> &Ins,
2219 SmallVectorImpl<SDValue> &InVals)
2221 MachineFunction &MF = DAG.getMachineFunction();
2222 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2224 const Function* Fn = MF.getFunction();
2225 if (Fn->hasExternalLinkage() &&
2226 Subtarget->isTargetCygMing() &&
2227 Fn->getName() == "main")
2228 FuncInfo->setForceFramePointer(true);
2230 MachineFrameInfo *MFI = MF.getFrameInfo();
2231 bool Is64Bit = Subtarget->is64Bit();
2232 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2234 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2235 "Var args not supported with calling convention fastcc, ghc or hipe");
2237 // Assign locations to all of the incoming arguments.
2238 SmallVector<CCValAssign, 16> ArgLocs;
2239 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2240 ArgLocs, *DAG.getContext());
2242 // Allocate shadow area for Win64
2244 CCInfo.AllocateStack(32, 8);
2246 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2248 unsigned LastVal = ~0U;
2250 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2251 CCValAssign &VA = ArgLocs[i];
2252 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2254 assert(VA.getValNo() != LastVal &&
2255 "Don't support value assigned to multiple locs yet");
2257 LastVal = VA.getValNo();
2259 if (VA.isRegLoc()) {
2260 EVT RegVT = VA.getLocVT();
2261 const TargetRegisterClass *RC;
2262 if (RegVT == MVT::i32)
2263 RC = &X86::GR32RegClass;
2264 else if (Is64Bit && RegVT == MVT::i64)
2265 RC = &X86::GR64RegClass;
2266 else if (RegVT == MVT::f32)
2267 RC = &X86::FR32RegClass;
2268 else if (RegVT == MVT::f64)
2269 RC = &X86::FR64RegClass;
2270 else if (RegVT.is512BitVector())
2271 RC = &X86::VR512RegClass;
2272 else if (RegVT.is256BitVector())
2273 RC = &X86::VR256RegClass;
2274 else if (RegVT.is128BitVector())
2275 RC = &X86::VR128RegClass;
2276 else if (RegVT == MVT::x86mmx)
2277 RC = &X86::VR64RegClass;
2278 else if (RegVT == MVT::i1)
2279 RC = &X86::VK1RegClass;
2280 else if (RegVT == MVT::v8i1)
2281 RC = &X86::VK8RegClass;
2282 else if (RegVT == MVT::v16i1)
2283 RC = &X86::VK16RegClass;
2285 llvm_unreachable("Unknown argument type!");
2287 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2288 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2290 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2291 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2293 if (VA.getLocInfo() == CCValAssign::SExt)
2294 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2295 DAG.getValueType(VA.getValVT()));
2296 else if (VA.getLocInfo() == CCValAssign::ZExt)
2297 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2298 DAG.getValueType(VA.getValVT()));
2299 else if (VA.getLocInfo() == CCValAssign::BCvt)
2300 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2302 if (VA.isExtInLoc()) {
2303 // Handle MMX values passed in XMM regs.
2304 if (RegVT.isVector())
2305 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2307 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2310 assert(VA.isMemLoc());
2311 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2314 // If value is passed via pointer - do a load.
2315 if (VA.getLocInfo() == CCValAssign::Indirect)
2316 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2317 MachinePointerInfo(), false, false, false, 0);
2319 InVals.push_back(ArgValue);
2322 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2323 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2324 // The x86-64 ABIs require that for returning structs by value we copy
2325 // the sret argument into %rax/%eax (depending on ABI) for the return.
2326 // Win32 requires us to put the sret argument to %eax as well.
2327 // Save the argument into a virtual register so that we can access it
2328 // from the return points.
2329 if (Ins[i].Flags.isSRet()) {
2330 unsigned Reg = FuncInfo->getSRetReturnReg();
2332 MVT PtrTy = getPointerTy();
2333 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2334 FuncInfo->setSRetReturnReg(Reg);
2336 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2337 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2343 unsigned StackSize = CCInfo.getNextStackOffset();
2344 // Align stack specially for tail calls.
2345 if (FuncIsMadeTailCallSafe(CallConv,
2346 MF.getTarget().Options.GuaranteedTailCallOpt))
2347 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2349 // If the function takes variable number of arguments, make a frame index for
2350 // the start of the first vararg value... for expansion of llvm.va_start.
2352 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2353 CallConv != CallingConv::X86_ThisCall)) {
2354 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2357 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2359 // FIXME: We should really autogenerate these arrays
2360 static const MCPhysReg GPR64ArgRegsWin64[] = {
2361 X86::RCX, X86::RDX, X86::R8, X86::R9
2363 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2364 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2366 static const MCPhysReg XMMArgRegs64Bit[] = {
2367 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2368 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2370 const MCPhysReg *GPR64ArgRegs;
2371 unsigned NumXMMRegs = 0;
2374 // The XMM registers which might contain var arg parameters are shadowed
2375 // in their paired GPR. So we only need to save the GPR to their home
2377 TotalNumIntRegs = 4;
2378 GPR64ArgRegs = GPR64ArgRegsWin64;
2380 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2381 GPR64ArgRegs = GPR64ArgRegs64Bit;
2383 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2386 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2389 bool NoImplicitFloatOps = Fn->getAttributes().
2390 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2391 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2392 "SSE register cannot be used when SSE is disabled!");
2393 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2394 NoImplicitFloatOps) &&
2395 "SSE register cannot be used when SSE is disabled!");
2396 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2397 !Subtarget->hasSSE1())
2398 // Kernel mode asks for SSE to be disabled, so don't push them
2400 TotalNumXMMRegs = 0;
2403 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2404 // Get to the caller-allocated home save location. Add 8 to account
2405 // for the return address.
2406 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2407 FuncInfo->setRegSaveFrameIndex(
2408 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2409 // Fixup to set vararg frame on shadow area (4 x i64).
2411 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2413 // For X86-64, if there are vararg parameters that are passed via
2414 // registers, then we must store them to their spots on the stack so
2415 // they may be loaded by deferencing the result of va_next.
2416 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2417 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2418 FuncInfo->setRegSaveFrameIndex(
2419 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2423 // Store the integer parameter registers.
2424 SmallVector<SDValue, 8> MemOps;
2425 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2427 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2428 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2429 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2430 DAG.getIntPtrConstant(Offset));
2431 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2432 &X86::GR64RegClass);
2433 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2435 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2436 MachinePointerInfo::getFixedStack(
2437 FuncInfo->getRegSaveFrameIndex(), Offset),
2439 MemOps.push_back(Store);
2443 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2444 // Now store the XMM (fp + vector) parameter registers.
2445 SmallVector<SDValue, 11> SaveXMMOps;
2446 SaveXMMOps.push_back(Chain);
2448 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2449 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2450 SaveXMMOps.push_back(ALVal);
2452 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2453 FuncInfo->getRegSaveFrameIndex()));
2454 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2455 FuncInfo->getVarArgsFPOffset()));
2457 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2458 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2459 &X86::VR128RegClass);
2460 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2461 SaveXMMOps.push_back(Val);
2463 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2464 MVT::Other, SaveXMMOps));
2467 if (!MemOps.empty())
2468 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2472 // Some CCs need callee pop.
2473 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2474 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2475 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2477 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2478 // If this is an sret function, the return should pop the hidden pointer.
2479 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2480 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2481 argsAreStructReturn(Ins) == StackStructReturn)
2482 FuncInfo->setBytesToPopOnReturn(4);
2486 // RegSaveFrameIndex is X86-64 only.
2487 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2488 if (CallConv == CallingConv::X86_FastCall ||
2489 CallConv == CallingConv::X86_ThisCall)
2490 // fastcc functions can't have varargs.
2491 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2494 FuncInfo->setArgumentStackSize(StackSize);
2500 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2501 SDValue StackPtr, SDValue Arg,
2502 SDLoc dl, SelectionDAG &DAG,
2503 const CCValAssign &VA,
2504 ISD::ArgFlagsTy Flags) const {
2505 unsigned LocMemOffset = VA.getLocMemOffset();
2506 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2507 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2508 if (Flags.isByVal())
2509 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2511 return DAG.getStore(Chain, dl, Arg, PtrOff,
2512 MachinePointerInfo::getStack(LocMemOffset),
2516 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2517 /// optimization is performed and it is required.
2519 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2520 SDValue &OutRetAddr, SDValue Chain,
2521 bool IsTailCall, bool Is64Bit,
2522 int FPDiff, SDLoc dl) const {
2523 // Adjust the Return address stack slot.
2524 EVT VT = getPointerTy();
2525 OutRetAddr = getReturnAddressFrameIndex(DAG);
2527 // Load the "old" Return address.
2528 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2529 false, false, false, 0);
2530 return SDValue(OutRetAddr.getNode(), 1);
2533 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2534 /// optimization is performed and it is required (FPDiff!=0).
2535 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2536 SDValue Chain, SDValue RetAddrFrIdx,
2537 EVT PtrVT, unsigned SlotSize,
2538 int FPDiff, SDLoc dl) {
2539 // Store the return address to the appropriate stack slot.
2540 if (!FPDiff) return Chain;
2541 // Calculate the new stack slot for the return address.
2542 int NewReturnAddrFI =
2543 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2545 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2546 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2547 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2553 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2554 SmallVectorImpl<SDValue> &InVals) const {
2555 SelectionDAG &DAG = CLI.DAG;
2557 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2558 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2559 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2560 SDValue Chain = CLI.Chain;
2561 SDValue Callee = CLI.Callee;
2562 CallingConv::ID CallConv = CLI.CallConv;
2563 bool &isTailCall = CLI.IsTailCall;
2564 bool isVarArg = CLI.IsVarArg;
2566 MachineFunction &MF = DAG.getMachineFunction();
2567 bool Is64Bit = Subtarget->is64Bit();
2568 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2569 StructReturnType SR = callIsStructReturn(Outs);
2570 bool IsSibcall = false;
2572 if (MF.getTarget().Options.DisableTailCalls)
2575 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2577 // Force this to be a tail call. The verifier rules are enough to ensure
2578 // that we can lower this successfully without moving the return address
2581 } else if (isTailCall) {
2582 // Check if it's really possible to do a tail call.
2583 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2584 isVarArg, SR != NotStructReturn,
2585 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2586 Outs, OutVals, Ins, DAG);
2588 // Sibcalls are automatically detected tailcalls which do not require
2590 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2597 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2598 "Var args not supported with calling convention fastcc, ghc or hipe");
2600 // Analyze operands of the call, assigning locations to each operand.
2601 SmallVector<CCValAssign, 16> ArgLocs;
2602 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2603 ArgLocs, *DAG.getContext());
2605 // Allocate shadow area for Win64
2607 CCInfo.AllocateStack(32, 8);
2609 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2611 // Get a count of how many bytes are to be pushed on the stack.
2612 unsigned NumBytes = CCInfo.getNextStackOffset();
2614 // This is a sibcall. The memory operands are available in caller's
2615 // own caller's stack.
2617 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2618 IsTailCallConvention(CallConv))
2619 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2622 if (isTailCall && !IsSibcall && !IsMustTail) {
2623 // Lower arguments at fp - stackoffset + fpdiff.
2624 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2625 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2627 FPDiff = NumBytesCallerPushed - NumBytes;
2629 // Set the delta of movement of the returnaddr stackslot.
2630 // But only set if delta is greater than previous delta.
2631 if (FPDiff < X86Info->getTCReturnAddrDelta())
2632 X86Info->setTCReturnAddrDelta(FPDiff);
2635 unsigned NumBytesToPush = NumBytes;
2636 unsigned NumBytesToPop = NumBytes;
2638 // If we have an inalloca argument, all stack space has already been allocated
2639 // for us and be right at the top of the stack. We don't support multiple
2640 // arguments passed in memory when using inalloca.
2641 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2643 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2644 "an inalloca argument must be the only memory argument");
2648 Chain = DAG.getCALLSEQ_START(
2649 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2651 SDValue RetAddrFrIdx;
2652 // Load return address for tail calls.
2653 if (isTailCall && FPDiff)
2654 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2655 Is64Bit, FPDiff, dl);
2657 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2658 SmallVector<SDValue, 8> MemOpChains;
2661 // Walk the register/memloc assignments, inserting copies/loads. In the case
2662 // of tail call optimization arguments are handle later.
2663 const X86RegisterInfo *RegInfo =
2664 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2665 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2666 // Skip inalloca arguments, they have already been written.
2667 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2668 if (Flags.isInAlloca())
2671 CCValAssign &VA = ArgLocs[i];
2672 EVT RegVT = VA.getLocVT();
2673 SDValue Arg = OutVals[i];
2674 bool isByVal = Flags.isByVal();
2676 // Promote the value if needed.
2677 switch (VA.getLocInfo()) {
2678 default: llvm_unreachable("Unknown loc info!");
2679 case CCValAssign::Full: break;
2680 case CCValAssign::SExt:
2681 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2683 case CCValAssign::ZExt:
2684 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2686 case CCValAssign::AExt:
2687 if (RegVT.is128BitVector()) {
2688 // Special case: passing MMX values in XMM registers.
2689 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2690 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2691 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2693 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2695 case CCValAssign::BCvt:
2696 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2698 case CCValAssign::Indirect: {
2699 // Store the argument.
2700 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2701 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2702 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2703 MachinePointerInfo::getFixedStack(FI),
2710 if (VA.isRegLoc()) {
2711 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2712 if (isVarArg && IsWin64) {
2713 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2714 // shadow reg if callee is a varargs function.
2715 unsigned ShadowReg = 0;
2716 switch (VA.getLocReg()) {
2717 case X86::XMM0: ShadowReg = X86::RCX; break;
2718 case X86::XMM1: ShadowReg = X86::RDX; break;
2719 case X86::XMM2: ShadowReg = X86::R8; break;
2720 case X86::XMM3: ShadowReg = X86::R9; break;
2723 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2725 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2726 assert(VA.isMemLoc());
2727 if (!StackPtr.getNode())
2728 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2730 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2731 dl, DAG, VA, Flags));
2735 if (!MemOpChains.empty())
2736 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2738 if (Subtarget->isPICStyleGOT()) {
2739 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2742 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2743 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2745 // If we are tail calling and generating PIC/GOT style code load the
2746 // address of the callee into ECX. The value in ecx is used as target of
2747 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2748 // for tail calls on PIC/GOT architectures. Normally we would just put the
2749 // address of GOT into ebx and then call target@PLT. But for tail calls
2750 // ebx would be restored (since ebx is callee saved) before jumping to the
2753 // Note: The actual moving to ECX is done further down.
2754 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2755 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2756 !G->getGlobal()->hasProtectedVisibility())
2757 Callee = LowerGlobalAddress(Callee, DAG);
2758 else if (isa<ExternalSymbolSDNode>(Callee))
2759 Callee = LowerExternalSymbol(Callee, DAG);
2763 if (Is64Bit && isVarArg && !IsWin64) {
2764 // From AMD64 ABI document:
2765 // For calls that may call functions that use varargs or stdargs
2766 // (prototype-less calls or calls to functions containing ellipsis (...) in
2767 // the declaration) %al is used as hidden argument to specify the number
2768 // of SSE registers used. The contents of %al do not need to match exactly
2769 // the number of registers, but must be an ubound on the number of SSE
2770 // registers used and is in the range 0 - 8 inclusive.
2772 // Count the number of XMM registers allocated.
2773 static const MCPhysReg XMMArgRegs[] = {
2774 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2775 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2777 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2778 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2779 && "SSE registers cannot be used when SSE is disabled");
2781 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2782 DAG.getConstant(NumXMMRegs, MVT::i8)));
2785 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2786 // don't need this because the eligibility check rejects calls that require
2787 // shuffling arguments passed in memory.
2788 if (!IsSibcall && isTailCall) {
2789 // Force all the incoming stack arguments to be loaded from the stack
2790 // before any new outgoing arguments are stored to the stack, because the
2791 // outgoing stack slots may alias the incoming argument stack slots, and
2792 // the alias isn't otherwise explicit. This is slightly more conservative
2793 // than necessary, because it means that each store effectively depends
2794 // on every argument instead of just those arguments it would clobber.
2795 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2797 SmallVector<SDValue, 8> MemOpChains2;
2800 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2801 CCValAssign &VA = ArgLocs[i];
2804 assert(VA.isMemLoc());
2805 SDValue Arg = OutVals[i];
2806 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2807 // Skip inalloca arguments. They don't require any work.
2808 if (Flags.isInAlloca())
2810 // Create frame index.
2811 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2812 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2813 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2814 FIN = DAG.getFrameIndex(FI, getPointerTy());
2816 if (Flags.isByVal()) {
2817 // Copy relative to framepointer.
2818 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2819 if (!StackPtr.getNode())
2820 StackPtr = DAG.getCopyFromReg(Chain, dl,
2821 RegInfo->getStackRegister(),
2823 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2825 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2829 // Store relative to framepointer.
2830 MemOpChains2.push_back(
2831 DAG.getStore(ArgChain, dl, Arg, FIN,
2832 MachinePointerInfo::getFixedStack(FI),
2837 if (!MemOpChains2.empty())
2838 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2840 // Store the return address to the appropriate stack slot.
2841 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2842 getPointerTy(), RegInfo->getSlotSize(),
2846 // Build a sequence of copy-to-reg nodes chained together with token chain
2847 // and flag operands which copy the outgoing args into registers.
2849 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2850 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2851 RegsToPass[i].second, InFlag);
2852 InFlag = Chain.getValue(1);
2855 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2856 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2857 // In the 64-bit large code model, we have to make all calls
2858 // through a register, since the call instruction's 32-bit
2859 // pc-relative offset may not be large enough to hold the whole
2861 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2862 // If the callee is a GlobalAddress node (quite common, every direct call
2863 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2866 // We should use extra load for direct calls to dllimported functions in
2868 const GlobalValue *GV = G->getGlobal();
2869 if (!GV->hasDLLImportStorageClass()) {
2870 unsigned char OpFlags = 0;
2871 bool ExtraLoad = false;
2872 unsigned WrapperKind = ISD::DELETED_NODE;
2874 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2875 // external symbols most go through the PLT in PIC mode. If the symbol
2876 // has hidden or protected visibility, or if it is static or local, then
2877 // we don't need to use the PLT - we can directly call it.
2878 if (Subtarget->isTargetELF() &&
2879 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2880 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2881 OpFlags = X86II::MO_PLT;
2882 } else if (Subtarget->isPICStyleStubAny() &&
2883 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2884 (!Subtarget->getTargetTriple().isMacOSX() ||
2885 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2886 // PC-relative references to external symbols should go through $stub,
2887 // unless we're building with the leopard linker or later, which
2888 // automatically synthesizes these stubs.
2889 OpFlags = X86II::MO_DARWIN_STUB;
2890 } else if (Subtarget->isPICStyleRIPRel() &&
2891 isa<Function>(GV) &&
2892 cast<Function>(GV)->getAttributes().
2893 hasAttribute(AttributeSet::FunctionIndex,
2894 Attribute::NonLazyBind)) {
2895 // If the function is marked as non-lazy, generate an indirect call
2896 // which loads from the GOT directly. This avoids runtime overhead
2897 // at the cost of eager binding (and one extra byte of encoding).
2898 OpFlags = X86II::MO_GOTPCREL;
2899 WrapperKind = X86ISD::WrapperRIP;
2903 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2904 G->getOffset(), OpFlags);
2906 // Add a wrapper if needed.
2907 if (WrapperKind != ISD::DELETED_NODE)
2908 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2909 // Add extra indirection if needed.
2911 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2912 MachinePointerInfo::getGOT(),
2913 false, false, false, 0);
2915 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2916 unsigned char OpFlags = 0;
2918 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2919 // external symbols should go through the PLT.
2920 if (Subtarget->isTargetELF() &&
2921 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2922 OpFlags = X86II::MO_PLT;
2923 } else if (Subtarget->isPICStyleStubAny() &&
2924 (!Subtarget->getTargetTriple().isMacOSX() ||
2925 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2926 // PC-relative references to external symbols should go through $stub,
2927 // unless we're building with the leopard linker or later, which
2928 // automatically synthesizes these stubs.
2929 OpFlags = X86II::MO_DARWIN_STUB;
2932 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2936 // Returns a chain & a flag for retval copy to use.
2937 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2938 SmallVector<SDValue, 8> Ops;
2940 if (!IsSibcall && isTailCall) {
2941 Chain = DAG.getCALLSEQ_END(Chain,
2942 DAG.getIntPtrConstant(NumBytesToPop, true),
2943 DAG.getIntPtrConstant(0, true), InFlag, dl);
2944 InFlag = Chain.getValue(1);
2947 Ops.push_back(Chain);
2948 Ops.push_back(Callee);
2951 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2953 // Add argument registers to the end of the list so that they are known live
2955 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2956 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2957 RegsToPass[i].second.getValueType()));
2959 // Add a register mask operand representing the call-preserved registers.
2960 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2961 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2962 assert(Mask && "Missing call preserved mask for calling convention");
2963 Ops.push_back(DAG.getRegisterMask(Mask));
2965 if (InFlag.getNode())
2966 Ops.push_back(InFlag);
2970 //// If this is the first return lowered for this function, add the regs
2971 //// to the liveout set for the function.
2972 // This isn't right, although it's probably harmless on x86; liveouts
2973 // should be computed from returns not tail calls. Consider a void
2974 // function making a tail call to a function returning int.
2975 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2978 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2979 InFlag = Chain.getValue(1);
2981 // Create the CALLSEQ_END node.
2982 unsigned NumBytesForCalleeToPop;
2983 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2984 DAG.getTarget().Options.GuaranteedTailCallOpt))
2985 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2986 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2987 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2988 SR == StackStructReturn)
2989 // If this is a call to a struct-return function, the callee
2990 // pops the hidden struct pointer, so we have to push it back.
2991 // This is common for Darwin/X86, Linux & Mingw32 targets.
2992 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2993 NumBytesForCalleeToPop = 4;
2995 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2997 // Returns a flag for retval copy to use.
2999 Chain = DAG.getCALLSEQ_END(Chain,
3000 DAG.getIntPtrConstant(NumBytesToPop, true),
3001 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3004 InFlag = Chain.getValue(1);
3007 // Handle result values, copying them out of physregs into vregs that we
3009 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3010 Ins, dl, DAG, InVals);
3013 //===----------------------------------------------------------------------===//
3014 // Fast Calling Convention (tail call) implementation
3015 //===----------------------------------------------------------------------===//
3017 // Like std call, callee cleans arguments, convention except that ECX is
3018 // reserved for storing the tail called function address. Only 2 registers are
3019 // free for argument passing (inreg). Tail call optimization is performed
3021 // * tailcallopt is enabled
3022 // * caller/callee are fastcc
3023 // On X86_64 architecture with GOT-style position independent code only local
3024 // (within module) calls are supported at the moment.
3025 // To keep the stack aligned according to platform abi the function
3026 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3027 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3028 // If a tail called function callee has more arguments than the caller the
3029 // caller needs to make sure that there is room to move the RETADDR to. This is
3030 // achieved by reserving an area the size of the argument delta right after the
3031 // original REtADDR, but before the saved framepointer or the spilled registers
3032 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3044 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3045 /// for a 16 byte align requirement.
3047 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3048 SelectionDAG& DAG) const {
3049 MachineFunction &MF = DAG.getMachineFunction();
3050 const TargetMachine &TM = MF.getTarget();
3051 const X86RegisterInfo *RegInfo =
3052 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3053 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3054 unsigned StackAlignment = TFI.getStackAlignment();
3055 uint64_t AlignMask = StackAlignment - 1;
3056 int64_t Offset = StackSize;
3057 unsigned SlotSize = RegInfo->getSlotSize();
3058 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3059 // Number smaller than 12 so just add the difference.
3060 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3062 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3063 Offset = ((~AlignMask) & Offset) + StackAlignment +
3064 (StackAlignment-SlotSize);
3069 /// MatchingStackOffset - Return true if the given stack call argument is
3070 /// already available in the same position (relatively) of the caller's
3071 /// incoming argument stack.
3073 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3074 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3075 const X86InstrInfo *TII) {
3076 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3078 if (Arg.getOpcode() == ISD::CopyFromReg) {
3079 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3080 if (!TargetRegisterInfo::isVirtualRegister(VR))
3082 MachineInstr *Def = MRI->getVRegDef(VR);
3085 if (!Flags.isByVal()) {
3086 if (!TII->isLoadFromStackSlot(Def, FI))
3089 unsigned Opcode = Def->getOpcode();
3090 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3091 Def->getOperand(1).isFI()) {
3092 FI = Def->getOperand(1).getIndex();
3093 Bytes = Flags.getByValSize();
3097 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3098 if (Flags.isByVal())
3099 // ByVal argument is passed in as a pointer but it's now being
3100 // dereferenced. e.g.
3101 // define @foo(%struct.X* %A) {
3102 // tail call @bar(%struct.X* byval %A)
3105 SDValue Ptr = Ld->getBasePtr();
3106 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3109 FI = FINode->getIndex();
3110 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3111 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3112 FI = FINode->getIndex();
3113 Bytes = Flags.getByValSize();
3117 assert(FI != INT_MAX);
3118 if (!MFI->isFixedObjectIndex(FI))
3120 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3123 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3124 /// for tail call optimization. Targets which want to do tail call
3125 /// optimization should implement this function.
3127 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3128 CallingConv::ID CalleeCC,
3130 bool isCalleeStructRet,
3131 bool isCallerStructRet,
3133 const SmallVectorImpl<ISD::OutputArg> &Outs,
3134 const SmallVectorImpl<SDValue> &OutVals,
3135 const SmallVectorImpl<ISD::InputArg> &Ins,
3136 SelectionDAG &DAG) const {
3137 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3140 // If -tailcallopt is specified, make fastcc functions tail-callable.
3141 const MachineFunction &MF = DAG.getMachineFunction();
3142 const Function *CallerF = MF.getFunction();
3144 // If the function return type is x86_fp80 and the callee return type is not,
3145 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3146 // perform a tailcall optimization here.
3147 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3150 CallingConv::ID CallerCC = CallerF->getCallingConv();
3151 bool CCMatch = CallerCC == CalleeCC;
3152 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3153 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3155 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3156 if (IsTailCallConvention(CalleeCC) && CCMatch)
3161 // Look for obvious safe cases to perform tail call optimization that do not
3162 // require ABI changes. This is what gcc calls sibcall.
3164 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3165 // emit a special epilogue.
3166 const X86RegisterInfo *RegInfo =
3167 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3168 if (RegInfo->needsStackRealignment(MF))
3171 // Also avoid sibcall optimization if either caller or callee uses struct
3172 // return semantics.
3173 if (isCalleeStructRet || isCallerStructRet)
3176 // An stdcall/thiscall caller is expected to clean up its arguments; the
3177 // callee isn't going to do that.
3178 // FIXME: this is more restrictive than needed. We could produce a tailcall
3179 // when the stack adjustment matches. For example, with a thiscall that takes
3180 // only one argument.
3181 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3182 CallerCC == CallingConv::X86_ThisCall))
3185 // Do not sibcall optimize vararg calls unless all arguments are passed via
3187 if (isVarArg && !Outs.empty()) {
3189 // Optimizing for varargs on Win64 is unlikely to be safe without
3190 // additional testing.
3191 if (IsCalleeWin64 || IsCallerWin64)
3194 SmallVector<CCValAssign, 16> ArgLocs;
3195 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3196 DAG.getTarget(), ArgLocs, *DAG.getContext());
3198 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3199 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3200 if (!ArgLocs[i].isRegLoc())
3204 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3205 // stack. Therefore, if it's not used by the call it is not safe to optimize
3206 // this into a sibcall.
3207 bool Unused = false;
3208 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3215 SmallVector<CCValAssign, 16> RVLocs;
3216 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3217 DAG.getTarget(), RVLocs, *DAG.getContext());
3218 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3219 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3220 CCValAssign &VA = RVLocs[i];
3221 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3226 // If the calling conventions do not match, then we'd better make sure the
3227 // results are returned in the same way as what the caller expects.
3229 SmallVector<CCValAssign, 16> RVLocs1;
3230 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3231 DAG.getTarget(), RVLocs1, *DAG.getContext());
3232 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3234 SmallVector<CCValAssign, 16> RVLocs2;
3235 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3236 DAG.getTarget(), RVLocs2, *DAG.getContext());
3237 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3239 if (RVLocs1.size() != RVLocs2.size())
3241 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3242 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3244 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3246 if (RVLocs1[i].isRegLoc()) {
3247 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3250 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3256 // If the callee takes no arguments then go on to check the results of the
3258 if (!Outs.empty()) {
3259 // Check if stack adjustment is needed. For now, do not do this if any
3260 // argument is passed on the stack.
3261 SmallVector<CCValAssign, 16> ArgLocs;
3262 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3263 DAG.getTarget(), ArgLocs, *DAG.getContext());
3265 // Allocate shadow area for Win64
3267 CCInfo.AllocateStack(32, 8);
3269 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3270 if (CCInfo.getNextStackOffset()) {
3271 MachineFunction &MF = DAG.getMachineFunction();
3272 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3275 // Check if the arguments are already laid out in the right way as
3276 // the caller's fixed stack objects.
3277 MachineFrameInfo *MFI = MF.getFrameInfo();
3278 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3279 const X86InstrInfo *TII =
3280 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3281 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3282 CCValAssign &VA = ArgLocs[i];
3283 SDValue Arg = OutVals[i];
3284 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3285 if (VA.getLocInfo() == CCValAssign::Indirect)
3287 if (!VA.isRegLoc()) {
3288 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3295 // If the tailcall address may be in a register, then make sure it's
3296 // possible to register allocate for it. In 32-bit, the call address can
3297 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3298 // callee-saved registers are restored. These happen to be the same
3299 // registers used to pass 'inreg' arguments so watch out for those.
3300 if (!Subtarget->is64Bit() &&
3301 ((!isa<GlobalAddressSDNode>(Callee) &&
3302 !isa<ExternalSymbolSDNode>(Callee)) ||
3303 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3304 unsigned NumInRegs = 0;
3305 // In PIC we need an extra register to formulate the address computation
3307 unsigned MaxInRegs =
3308 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3310 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3311 CCValAssign &VA = ArgLocs[i];
3314 unsigned Reg = VA.getLocReg();
3317 case X86::EAX: case X86::EDX: case X86::ECX:
3318 if (++NumInRegs == MaxInRegs)
3330 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3331 const TargetLibraryInfo *libInfo) const {
3332 return X86::createFastISel(funcInfo, libInfo);
3335 //===----------------------------------------------------------------------===//
3336 // Other Lowering Hooks
3337 //===----------------------------------------------------------------------===//
3339 static bool MayFoldLoad(SDValue Op) {
3340 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3343 static bool MayFoldIntoStore(SDValue Op) {
3344 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3347 static bool isTargetShuffle(unsigned Opcode) {
3349 default: return false;
3350 case X86ISD::PSHUFD:
3351 case X86ISD::PSHUFHW:
3352 case X86ISD::PSHUFLW:
3354 case X86ISD::PALIGNR:
3355 case X86ISD::MOVLHPS:
3356 case X86ISD::MOVLHPD:
3357 case X86ISD::MOVHLPS:
3358 case X86ISD::MOVLPS:
3359 case X86ISD::MOVLPD:
3360 case X86ISD::MOVSHDUP:
3361 case X86ISD::MOVSLDUP:
3362 case X86ISD::MOVDDUP:
3365 case X86ISD::UNPCKL:
3366 case X86ISD::UNPCKH:
3367 case X86ISD::VPERMILP:
3368 case X86ISD::VPERM2X128:
3369 case X86ISD::VPERMI:
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375 SDValue V1, SelectionDAG &DAG) {
3377 default: llvm_unreachable("Unknown x86 shuffle node");
3378 case X86ISD::MOVSHDUP:
3379 case X86ISD::MOVSLDUP:
3380 case X86ISD::MOVDDUP:
3381 return DAG.getNode(Opc, dl, VT, V1);
3385 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3386 SDValue V1, unsigned TargetMask,
3387 SelectionDAG &DAG) {
3389 default: llvm_unreachable("Unknown x86 shuffle node");
3390 case X86ISD::PSHUFD:
3391 case X86ISD::PSHUFHW:
3392 case X86ISD::PSHUFLW:
3393 case X86ISD::VPERMILP:
3394 case X86ISD::VPERMI:
3395 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3399 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3400 SDValue V1, SDValue V2, unsigned TargetMask,
3401 SelectionDAG &DAG) {
3403 default: llvm_unreachable("Unknown x86 shuffle node");
3404 case X86ISD::PALIGNR:
3406 case X86ISD::VPERM2X128:
3407 return DAG.getNode(Opc, dl, VT, V1, V2,
3408 DAG.getConstant(TargetMask, MVT::i8));
3412 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3413 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3415 default: llvm_unreachable("Unknown x86 shuffle node");
3416 case X86ISD::MOVLHPS:
3417 case X86ISD::MOVLHPD:
3418 case X86ISD::MOVHLPS:
3419 case X86ISD::MOVLPS:
3420 case X86ISD::MOVLPD:
3423 case X86ISD::UNPCKL:
3424 case X86ISD::UNPCKH:
3425 return DAG.getNode(Opc, dl, VT, V1, V2);
3429 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3430 MachineFunction &MF = DAG.getMachineFunction();
3431 const X86RegisterInfo *RegInfo =
3432 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3433 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3434 int ReturnAddrIndex = FuncInfo->getRAIndex();
3436 if (ReturnAddrIndex == 0) {
3437 // Set up a frame object for the return address.
3438 unsigned SlotSize = RegInfo->getSlotSize();
3439 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3442 FuncInfo->setRAIndex(ReturnAddrIndex);
3445 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3448 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3449 bool hasSymbolicDisplacement) {
3450 // Offset should fit into 32 bit immediate field.
3451 if (!isInt<32>(Offset))
3454 // If we don't have a symbolic displacement - we don't have any extra
3456 if (!hasSymbolicDisplacement)
3459 // FIXME: Some tweaks might be needed for medium code model.
3460 if (M != CodeModel::Small && M != CodeModel::Kernel)
3463 // For small code model we assume that latest object is 16MB before end of 31
3464 // bits boundary. We may also accept pretty large negative constants knowing
3465 // that all objects are in the positive half of address space.
3466 if (M == CodeModel::Small && Offset < 16*1024*1024)
3469 // For kernel code model we know that all object resist in the negative half
3470 // of 32bits address space. We may not accept negative offsets, since they may
3471 // be just off and we may accept pretty large positive ones.
3472 if (M == CodeModel::Kernel && Offset > 0)
3478 /// isCalleePop - Determines whether the callee is required to pop its
3479 /// own arguments. Callee pop is necessary to support tail calls.
3480 bool X86::isCalleePop(CallingConv::ID CallingConv,
3481 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3485 switch (CallingConv) {
3488 case CallingConv::X86_StdCall:
3490 case CallingConv::X86_FastCall:
3492 case CallingConv::X86_ThisCall:
3494 case CallingConv::Fast:
3496 case CallingConv::GHC:
3498 case CallingConv::HiPE:
3503 /// \brief Return true if the condition is an unsigned comparison operation.
3504 static bool isX86CCUnsigned(unsigned X86CC) {
3506 default: llvm_unreachable("Invalid integer condition!");
3507 case X86::COND_E: return true;
3508 case X86::COND_G: return false;
3509 case X86::COND_GE: return false;
3510 case X86::COND_L: return false;
3511 case X86::COND_LE: return false;
3512 case X86::COND_NE: return true;
3513 case X86::COND_B: return true;
3514 case X86::COND_A: return true;
3515 case X86::COND_BE: return true;
3516 case X86::COND_AE: return true;
3518 llvm_unreachable("covered switch fell through?!");
3521 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3522 /// specific condition code, returning the condition code and the LHS/RHS of the
3523 /// comparison to make.
3524 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3525 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3527 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3528 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3529 // X > -1 -> X == 0, jump !sign.
3530 RHS = DAG.getConstant(0, RHS.getValueType());
3531 return X86::COND_NS;
3533 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3534 // X < 0 -> X == 0, jump on sign.
3537 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3539 RHS = DAG.getConstant(0, RHS.getValueType());
3540 return X86::COND_LE;
3544 switch (SetCCOpcode) {
3545 default: llvm_unreachable("Invalid integer condition!");
3546 case ISD::SETEQ: return X86::COND_E;
3547 case ISD::SETGT: return X86::COND_G;
3548 case ISD::SETGE: return X86::COND_GE;
3549 case ISD::SETLT: return X86::COND_L;
3550 case ISD::SETLE: return X86::COND_LE;
3551 case ISD::SETNE: return X86::COND_NE;
3552 case ISD::SETULT: return X86::COND_B;
3553 case ISD::SETUGT: return X86::COND_A;
3554 case ISD::SETULE: return X86::COND_BE;
3555 case ISD::SETUGE: return X86::COND_AE;
3559 // First determine if it is required or is profitable to flip the operands.
3561 // If LHS is a foldable load, but RHS is not, flip the condition.
3562 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3563 !ISD::isNON_EXTLoad(RHS.getNode())) {
3564 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3565 std::swap(LHS, RHS);
3568 switch (SetCCOpcode) {
3574 std::swap(LHS, RHS);
3578 // On a floating point condition, the flags are set as follows:
3580 // 0 | 0 | 0 | X > Y
3581 // 0 | 0 | 1 | X < Y
3582 // 1 | 0 | 0 | X == Y
3583 // 1 | 1 | 1 | unordered
3584 switch (SetCCOpcode) {
3585 default: llvm_unreachable("Condcode should be pre-legalized away");
3587 case ISD::SETEQ: return X86::COND_E;
3588 case ISD::SETOLT: // flipped
3590 case ISD::SETGT: return X86::COND_A;
3591 case ISD::SETOLE: // flipped
3593 case ISD::SETGE: return X86::COND_AE;
3594 case ISD::SETUGT: // flipped
3596 case ISD::SETLT: return X86::COND_B;
3597 case ISD::SETUGE: // flipped
3599 case ISD::SETLE: return X86::COND_BE;
3601 case ISD::SETNE: return X86::COND_NE;
3602 case ISD::SETUO: return X86::COND_P;
3603 case ISD::SETO: return X86::COND_NP;
3605 case ISD::SETUNE: return X86::COND_INVALID;
3609 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3610 /// code. Current x86 isa includes the following FP cmov instructions:
3611 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3612 static bool hasFPCMov(unsigned X86CC) {
3628 /// isFPImmLegal - Returns true if the target can instruction select the
3629 /// specified FP immediate natively. If false, the legalizer will
3630 /// materialize the FP immediate as a load from a constant pool.
3631 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3632 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3633 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3639 /// \brief Returns true if it is beneficial to convert a load of a constant
3640 /// to just the constant itself.
3641 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3643 assert(Ty->isIntegerTy());
3645 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3646 if (BitSize == 0 || BitSize > 64)
3651 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3652 /// the specified range (L, H].
3653 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3654 return (Val < 0) || (Val >= Low && Val < Hi);
3657 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3658 /// specified value.
3659 static bool isUndefOrEqual(int Val, int CmpVal) {
3660 return (Val < 0 || Val == CmpVal);
3663 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3664 /// from position Pos and ending in Pos+Size, falls within the specified
3665 /// sequential range (L, L+Pos]. or is undef.
3666 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3667 unsigned Pos, unsigned Size, int Low) {
3668 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3669 if (!isUndefOrEqual(Mask[i], Low))
3674 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3675 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3676 /// the second operand.
3677 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3678 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3679 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3680 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3681 return (Mask[0] < 2 && Mask[1] < 2);
3685 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3686 /// is suitable for input to PSHUFHW.
3687 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3688 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3691 // Lower quadword copied in order or undef.
3692 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3695 // Upper quadword shuffled.
3696 for (unsigned i = 4; i != 8; ++i)
3697 if (!isUndefOrInRange(Mask[i], 4, 8))
3700 if (VT == MVT::v16i16) {
3701 // Lower quadword copied in order or undef.
3702 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3705 // Upper quadword shuffled.
3706 for (unsigned i = 12; i != 16; ++i)
3707 if (!isUndefOrInRange(Mask[i], 12, 16))
3714 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3715 /// is suitable for input to PSHUFLW.
3716 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3717 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3720 // Upper quadword copied in order.
3721 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3724 // Lower quadword shuffled.
3725 for (unsigned i = 0; i != 4; ++i)
3726 if (!isUndefOrInRange(Mask[i], 0, 4))
3729 if (VT == MVT::v16i16) {
3730 // Upper quadword copied in order.
3731 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3734 // Lower quadword shuffled.
3735 for (unsigned i = 8; i != 12; ++i)
3736 if (!isUndefOrInRange(Mask[i], 8, 12))
3743 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3744 /// is suitable for input to PALIGNR.
3745 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3746 const X86Subtarget *Subtarget) {
3747 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3748 (VT.is256BitVector() && !Subtarget->hasInt256()))
3751 unsigned NumElts = VT.getVectorNumElements();
3752 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3753 unsigned NumLaneElts = NumElts/NumLanes;
3755 // Do not handle 64-bit element shuffles with palignr.
3756 if (NumLaneElts == 2)
3759 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3761 for (i = 0; i != NumLaneElts; ++i) {
3766 // Lane is all undef, go to next lane
3767 if (i == NumLaneElts)
3770 int Start = Mask[i+l];
3772 // Make sure its in this lane in one of the sources
3773 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3774 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3777 // If not lane 0, then we must match lane 0
3778 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3781 // Correct second source to be contiguous with first source
3782 if (Start >= (int)NumElts)
3783 Start -= NumElts - NumLaneElts;
3785 // Make sure we're shifting in the right direction.
3786 if (Start <= (int)(i+l))
3791 // Check the rest of the elements to see if they are consecutive.
3792 for (++i; i != NumLaneElts; ++i) {
3793 int Idx = Mask[i+l];
3795 // Make sure its in this lane
3796 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3797 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3800 // If not lane 0, then we must match lane 0
3801 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3804 if (Idx >= (int)NumElts)
3805 Idx -= NumElts - NumLaneElts;
3807 if (!isUndefOrEqual(Idx, Start+i))
3816 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3817 /// the two vector operands have swapped position.
3818 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3819 unsigned NumElems) {
3820 for (unsigned i = 0; i != NumElems; ++i) {
3824 else if (idx < (int)NumElems)
3825 Mask[i] = idx + NumElems;
3827 Mask[i] = idx - NumElems;
3831 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3832 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3833 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3834 /// reverse of what x86 shuffles want.
3835 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3837 unsigned NumElems = VT.getVectorNumElements();
3838 unsigned NumLanes = VT.getSizeInBits()/128;
3839 unsigned NumLaneElems = NumElems/NumLanes;
3841 if (NumLaneElems != 2 && NumLaneElems != 4)
3844 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3845 bool symetricMaskRequired =
3846 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3848 // VSHUFPSY divides the resulting vector into 4 chunks.
3849 // The sources are also splitted into 4 chunks, and each destination
3850 // chunk must come from a different source chunk.
3852 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3853 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3855 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3856 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3858 // VSHUFPDY divides the resulting vector into 4 chunks.
3859 // The sources are also splitted into 4 chunks, and each destination
3860 // chunk must come from a different source chunk.
3862 // SRC1 => X3 X2 X1 X0
3863 // SRC2 => Y3 Y2 Y1 Y0
3865 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3867 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3868 unsigned HalfLaneElems = NumLaneElems/2;
3869 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3870 for (unsigned i = 0; i != NumLaneElems; ++i) {
3871 int Idx = Mask[i+l];
3872 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3873 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3875 // For VSHUFPSY, the mask of the second half must be the same as the
3876 // first but with the appropriate offsets. This works in the same way as
3877 // VPERMILPS works with masks.
3878 if (!symetricMaskRequired || Idx < 0)
3880 if (MaskVal[i] < 0) {
3881 MaskVal[i] = Idx - l;
3884 if ((signed)(Idx - l) != MaskVal[i])
3892 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3893 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3894 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3895 if (!VT.is128BitVector())
3898 unsigned NumElems = VT.getVectorNumElements();
3903 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3904 return isUndefOrEqual(Mask[0], 6) &&
3905 isUndefOrEqual(Mask[1], 7) &&
3906 isUndefOrEqual(Mask[2], 2) &&
3907 isUndefOrEqual(Mask[3], 3);
3910 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3911 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3913 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3914 if (!VT.is128BitVector())
3917 unsigned NumElems = VT.getVectorNumElements();
3922 return isUndefOrEqual(Mask[0], 2) &&
3923 isUndefOrEqual(Mask[1], 3) &&
3924 isUndefOrEqual(Mask[2], 2) &&
3925 isUndefOrEqual(Mask[3], 3);
3928 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3929 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3930 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3931 if (!VT.is128BitVector())
3934 unsigned NumElems = VT.getVectorNumElements();
3936 if (NumElems != 2 && NumElems != 4)
3939 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3940 if (!isUndefOrEqual(Mask[i], i + NumElems))
3943 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3944 if (!isUndefOrEqual(Mask[i], i))
3950 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3951 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3952 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3953 if (!VT.is128BitVector())
3956 unsigned NumElems = VT.getVectorNumElements();
3958 if (NumElems != 2 && NumElems != 4)
3961 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3962 if (!isUndefOrEqual(Mask[i], i))
3965 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3966 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3972 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3973 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3974 /// i. e: If all but one element come from the same vector.
3975 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3976 // TODO: Deal with AVX's VINSERTPS
3977 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3980 unsigned CorrectPosV1 = 0;
3981 unsigned CorrectPosV2 = 0;
3982 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3983 if (Mask[i] == -1) {
3991 else if (Mask[i] == i + 4)
3995 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3996 // We have 3 elements (undefs count as elements from any vector) from one
3997 // vector, and one from another.
4004 // Some special combinations that can be optimized.
4007 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4008 SelectionDAG &DAG) {
4009 MVT VT = SVOp->getSimpleValueType(0);
4012 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4015 ArrayRef<int> Mask = SVOp->getMask();
4017 // These are the special masks that may be optimized.
4018 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4019 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4020 bool MatchEvenMask = true;
4021 bool MatchOddMask = true;
4022 for (int i=0; i<8; ++i) {
4023 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4024 MatchEvenMask = false;
4025 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4026 MatchOddMask = false;
4029 if (!MatchEvenMask && !MatchOddMask)
4032 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4034 SDValue Op0 = SVOp->getOperand(0);
4035 SDValue Op1 = SVOp->getOperand(1);
4037 if (MatchEvenMask) {
4038 // Shift the second operand right to 32 bits.
4039 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4040 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4042 // Shift the first operand left to 32 bits.
4043 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4044 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4046 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4047 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4050 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4051 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4052 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4053 bool HasInt256, bool V2IsSplat = false) {
4055 assert(VT.getSizeInBits() >= 128 &&
4056 "Unsupported vector type for unpckl");
4058 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4060 unsigned NumOf256BitLanes;
4061 unsigned NumElts = VT.getVectorNumElements();
4062 if (VT.is256BitVector()) {
4063 if (NumElts != 4 && NumElts != 8 &&
4064 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4067 NumOf256BitLanes = 1;
4068 } else if (VT.is512BitVector()) {
4069 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4070 "Unsupported vector type for unpckh");
4072 NumOf256BitLanes = 2;
4075 NumOf256BitLanes = 1;
4078 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4079 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4081 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4082 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4083 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4084 int BitI = Mask[l256*NumEltsInStride+l+i];
4085 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4086 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4088 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4090 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4098 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4099 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4100 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4101 bool HasInt256, bool V2IsSplat = false) {
4102 assert(VT.getSizeInBits() >= 128 &&
4103 "Unsupported vector type for unpckh");
4105 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4107 unsigned NumOf256BitLanes;
4108 unsigned NumElts = VT.getVectorNumElements();
4109 if (VT.is256BitVector()) {
4110 if (NumElts != 4 && NumElts != 8 &&
4111 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4114 NumOf256BitLanes = 1;
4115 } else if (VT.is512BitVector()) {
4116 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4117 "Unsupported vector type for unpckh");
4119 NumOf256BitLanes = 2;
4122 NumOf256BitLanes = 1;
4125 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4126 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4128 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4129 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4130 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4131 int BitI = Mask[l256*NumEltsInStride+l+i];
4132 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4133 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4135 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4137 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4145 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4146 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4148 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4149 unsigned NumElts = VT.getVectorNumElements();
4150 bool Is256BitVec = VT.is256BitVector();
4152 if (VT.is512BitVector())
4154 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4155 "Unsupported vector type for unpckh");
4157 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4158 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4161 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4162 // FIXME: Need a better way to get rid of this, there's no latency difference
4163 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4164 // the former later. We should also remove the "_undef" special mask.
4165 if (NumElts == 4 && Is256BitVec)
4168 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4169 // independently on 128-bit lanes.
4170 unsigned NumLanes = VT.getSizeInBits()/128;
4171 unsigned NumLaneElts = NumElts/NumLanes;
4173 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4174 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4175 int BitI = Mask[l+i];
4176 int BitI1 = Mask[l+i+1];
4178 if (!isUndefOrEqual(BitI, j))
4180 if (!isUndefOrEqual(BitI1, j))
4188 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4189 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4191 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4192 unsigned NumElts = VT.getVectorNumElements();
4194 if (VT.is512BitVector())
4197 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4198 "Unsupported vector type for unpckh");
4200 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4201 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4204 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4205 // independently on 128-bit lanes.
4206 unsigned NumLanes = VT.getSizeInBits()/128;
4207 unsigned NumLaneElts = NumElts/NumLanes;
4209 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4210 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4211 int BitI = Mask[l+i];
4212 int BitI1 = Mask[l+i+1];
4213 if (!isUndefOrEqual(BitI, j))
4215 if (!isUndefOrEqual(BitI1, j))
4222 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4223 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4224 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4225 if (!VT.is512BitVector())
4228 unsigned NumElts = VT.getVectorNumElements();
4229 unsigned HalfSize = NumElts/2;
4230 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4231 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4236 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4237 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4245 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4246 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4247 /// MOVSD, and MOVD, i.e. setting the lowest element.
4248 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4249 if (VT.getVectorElementType().getSizeInBits() < 32)
4251 if (!VT.is128BitVector())
4254 unsigned NumElts = VT.getVectorNumElements();
4256 if (!isUndefOrEqual(Mask[0], NumElts))
4259 for (unsigned i = 1; i != NumElts; ++i)
4260 if (!isUndefOrEqual(Mask[i], i))
4266 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4267 /// as permutations between 128-bit chunks or halves. As an example: this
4269 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4270 /// The first half comes from the second half of V1 and the second half from the
4271 /// the second half of V2.
4272 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4273 if (!HasFp256 || !VT.is256BitVector())
4276 // The shuffle result is divided into half A and half B. In total the two
4277 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4278 // B must come from C, D, E or F.
4279 unsigned HalfSize = VT.getVectorNumElements()/2;
4280 bool MatchA = false, MatchB = false;
4282 // Check if A comes from one of C, D, E, F.
4283 for (unsigned Half = 0; Half != 4; ++Half) {
4284 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4290 // Check if B comes from one of C, D, E, F.
4291 for (unsigned Half = 0; Half != 4; ++Half) {
4292 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4298 return MatchA && MatchB;
4301 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4302 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4303 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4304 MVT VT = SVOp->getSimpleValueType(0);
4306 unsigned HalfSize = VT.getVectorNumElements()/2;
4308 unsigned FstHalf = 0, SndHalf = 0;
4309 for (unsigned i = 0; i < HalfSize; ++i) {
4310 if (SVOp->getMaskElt(i) > 0) {
4311 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4315 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4316 if (SVOp->getMaskElt(i) > 0) {
4317 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4322 return (FstHalf | (SndHalf << 4));
4325 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4326 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4327 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4331 unsigned NumElts = VT.getVectorNumElements();
4333 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4334 for (unsigned i = 0; i != NumElts; ++i) {
4337 Imm8 |= Mask[i] << (i*2);
4342 unsigned LaneSize = 4;
4343 SmallVector<int, 4> MaskVal(LaneSize, -1);
4345 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4346 for (unsigned i = 0; i != LaneSize; ++i) {
4347 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4351 if (MaskVal[i] < 0) {
4352 MaskVal[i] = Mask[i+l] - l;
4353 Imm8 |= MaskVal[i] << (i*2);
4356 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4363 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4364 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4365 /// Note that VPERMIL mask matching is different depending whether theunderlying
4366 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4367 /// to the same elements of the low, but to the higher half of the source.
4368 /// In VPERMILPD the two lanes could be shuffled independently of each other
4369 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4370 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4371 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4372 if (VT.getSizeInBits() < 256 || EltSize < 32)
4374 bool symetricMaskRequired = (EltSize == 32);
4375 unsigned NumElts = VT.getVectorNumElements();
4377 unsigned NumLanes = VT.getSizeInBits()/128;
4378 unsigned LaneSize = NumElts/NumLanes;
4379 // 2 or 4 elements in one lane
4381 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4382 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4383 for (unsigned i = 0; i != LaneSize; ++i) {
4384 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4386 if (symetricMaskRequired) {
4387 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4388 ExpectedMaskVal[i] = Mask[i+l] - l;
4391 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4399 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4400 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4401 /// element of vector 2 and the other elements to come from vector 1 in order.
4402 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4403 bool V2IsSplat = false, bool V2IsUndef = false) {
4404 if (!VT.is128BitVector())
4407 unsigned NumOps = VT.getVectorNumElements();
4408 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4411 if (!isUndefOrEqual(Mask[0], 0))
4414 for (unsigned i = 1; i != NumOps; ++i)
4415 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4416 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4417 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4423 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4424 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4425 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4426 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4427 const X86Subtarget *Subtarget) {
4428 if (!Subtarget->hasSSE3())
4431 unsigned NumElems = VT.getVectorNumElements();
4433 if ((VT.is128BitVector() && NumElems != 4) ||
4434 (VT.is256BitVector() && NumElems != 8) ||
4435 (VT.is512BitVector() && NumElems != 16))
4438 // "i+1" is the value the indexed mask element must have
4439 for (unsigned i = 0; i != NumElems; i += 2)
4440 if (!isUndefOrEqual(Mask[i], i+1) ||
4441 !isUndefOrEqual(Mask[i+1], i+1))
4447 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4448 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4449 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4450 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4451 const X86Subtarget *Subtarget) {
4452 if (!Subtarget->hasSSE3())
4455 unsigned NumElems = VT.getVectorNumElements();
4457 if ((VT.is128BitVector() && NumElems != 4) ||
4458 (VT.is256BitVector() && NumElems != 8) ||
4459 (VT.is512BitVector() && NumElems != 16))
4462 // "i" is the value the indexed mask element must have
4463 for (unsigned i = 0; i != NumElems; i += 2)
4464 if (!isUndefOrEqual(Mask[i], i) ||
4465 !isUndefOrEqual(Mask[i+1], i))
4471 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4472 /// specifies a shuffle of elements that is suitable for input to 256-bit
4473 /// version of MOVDDUP.
4474 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4475 if (!HasFp256 || !VT.is256BitVector())
4478 unsigned NumElts = VT.getVectorNumElements();
4482 for (unsigned i = 0; i != NumElts/2; ++i)
4483 if (!isUndefOrEqual(Mask[i], 0))
4485 for (unsigned i = NumElts/2; i != NumElts; ++i)
4486 if (!isUndefOrEqual(Mask[i], NumElts/2))
4491 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4492 /// specifies a shuffle of elements that is suitable for input to 128-bit
4493 /// version of MOVDDUP.
4494 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4495 if (!VT.is128BitVector())
4498 unsigned e = VT.getVectorNumElements() / 2;
4499 for (unsigned i = 0; i != e; ++i)
4500 if (!isUndefOrEqual(Mask[i], i))
4502 for (unsigned i = 0; i != e; ++i)
4503 if (!isUndefOrEqual(Mask[e+i], i))
4508 /// isVEXTRACTIndex - Return true if the specified
4509 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4510 /// suitable for instruction that extract 128 or 256 bit vectors
4511 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4512 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4513 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4516 // The index should be aligned on a vecWidth-bit boundary.
4518 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4520 MVT VT = N->getSimpleValueType(0);
4521 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4522 bool Result = (Index * ElSize) % vecWidth == 0;
4527 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4528 /// operand specifies a subvector insert that is suitable for input to
4529 /// insertion of 128 or 256-bit subvectors
4530 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4531 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4532 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4534 // The index should be aligned on a vecWidth-bit boundary.
4536 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4538 MVT VT = N->getSimpleValueType(0);
4539 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4540 bool Result = (Index * ElSize) % vecWidth == 0;
4545 bool X86::isVINSERT128Index(SDNode *N) {
4546 return isVINSERTIndex(N, 128);
4549 bool X86::isVINSERT256Index(SDNode *N) {
4550 return isVINSERTIndex(N, 256);
4553 bool X86::isVEXTRACT128Index(SDNode *N) {
4554 return isVEXTRACTIndex(N, 128);
4557 bool X86::isVEXTRACT256Index(SDNode *N) {
4558 return isVEXTRACTIndex(N, 256);
4561 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4562 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4563 /// Handles 128-bit and 256-bit.
4564 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4565 MVT VT = N->getSimpleValueType(0);
4567 assert((VT.getSizeInBits() >= 128) &&
4568 "Unsupported vector type for PSHUF/SHUFP");
4570 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4571 // independently on 128-bit lanes.
4572 unsigned NumElts = VT.getVectorNumElements();
4573 unsigned NumLanes = VT.getSizeInBits()/128;
4574 unsigned NumLaneElts = NumElts/NumLanes;
4576 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4577 "Only supports 2, 4 or 8 elements per lane");
4579 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4581 for (unsigned i = 0; i != NumElts; ++i) {
4582 int Elt = N->getMaskElt(i);
4583 if (Elt < 0) continue;
4584 Elt &= NumLaneElts - 1;
4585 unsigned ShAmt = (i << Shift) % 8;
4586 Mask |= Elt << ShAmt;
4592 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4593 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4594 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4595 MVT VT = N->getSimpleValueType(0);
4597 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4598 "Unsupported vector type for PSHUFHW");
4600 unsigned NumElts = VT.getVectorNumElements();
4603 for (unsigned l = 0; l != NumElts; l += 8) {
4604 // 8 nodes per lane, but we only care about the last 4.
4605 for (unsigned i = 0; i < 4; ++i) {
4606 int Elt = N->getMaskElt(l+i+4);
4607 if (Elt < 0) continue;
4608 Elt &= 0x3; // only 2-bits.
4609 Mask |= Elt << (i * 2);
4616 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4617 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4618 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4619 MVT VT = N->getSimpleValueType(0);
4621 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4622 "Unsupported vector type for PSHUFHW");
4624 unsigned NumElts = VT.getVectorNumElements();
4627 for (unsigned l = 0; l != NumElts; l += 8) {
4628 // 8 nodes per lane, but we only care about the first 4.
4629 for (unsigned i = 0; i < 4; ++i) {
4630 int Elt = N->getMaskElt(l+i);
4631 if (Elt < 0) continue;
4632 Elt &= 0x3; // only 2-bits
4633 Mask |= Elt << (i * 2);
4640 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4641 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4642 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4643 MVT VT = SVOp->getSimpleValueType(0);
4644 unsigned EltSize = VT.is512BitVector() ? 1 :
4645 VT.getVectorElementType().getSizeInBits() >> 3;
4647 unsigned NumElts = VT.getVectorNumElements();
4648 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4649 unsigned NumLaneElts = NumElts/NumLanes;
4653 for (i = 0; i != NumElts; ++i) {
4654 Val = SVOp->getMaskElt(i);
4658 if (Val >= (int)NumElts)
4659 Val -= NumElts - NumLaneElts;
4661 assert(Val - i > 0 && "PALIGNR imm should be positive");
4662 return (Val - i) * EltSize;
4665 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4666 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4667 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4668 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4671 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4673 MVT VecVT = N->getOperand(0).getSimpleValueType();
4674 MVT ElVT = VecVT.getVectorElementType();
4676 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4677 return Index / NumElemsPerChunk;
4680 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4681 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4682 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4683 llvm_unreachable("Illegal insert subvector for VINSERT");
4686 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4688 MVT VecVT = N->getSimpleValueType(0);
4689 MVT ElVT = VecVT.getVectorElementType();
4691 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4692 return Index / NumElemsPerChunk;
4695 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4696 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4697 /// and VINSERTI128 instructions.
4698 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4699 return getExtractVEXTRACTImmediate(N, 128);
4702 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4703 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4704 /// and VINSERTI64x4 instructions.
4705 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4706 return getExtractVEXTRACTImmediate(N, 256);
4709 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4710 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4711 /// and VINSERTI128 instructions.
4712 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4713 return getInsertVINSERTImmediate(N, 128);
4716 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4717 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4718 /// and VINSERTI64x4 instructions.
4719 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4720 return getInsertVINSERTImmediate(N, 256);
4723 /// isZero - Returns true if Elt is a constant integer zero
4724 static bool isZero(SDValue V) {
4725 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4726 return C && C->isNullValue();
4729 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4731 bool X86::isZeroNode(SDValue Elt) {
4734 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4735 return CFP->getValueAPF().isPosZero();
4739 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4740 /// their permute mask.
4741 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4742 SelectionDAG &DAG) {
4743 MVT VT = SVOp->getSimpleValueType(0);
4744 unsigned NumElems = VT.getVectorNumElements();
4745 SmallVector<int, 8> MaskVec;
4747 for (unsigned i = 0; i != NumElems; ++i) {
4748 int Idx = SVOp->getMaskElt(i);
4750 if (Idx < (int)NumElems)
4755 MaskVec.push_back(Idx);
4757 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4758 SVOp->getOperand(0), &MaskVec[0]);
4761 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4762 /// match movhlps. The lower half elements should come from upper half of
4763 /// V1 (and in order), and the upper half elements should come from the upper
4764 /// half of V2 (and in order).
4765 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4766 if (!VT.is128BitVector())
4768 if (VT.getVectorNumElements() != 4)
4770 for (unsigned i = 0, e = 2; i != e; ++i)
4771 if (!isUndefOrEqual(Mask[i], i+2))
4773 for (unsigned i = 2; i != 4; ++i)
4774 if (!isUndefOrEqual(Mask[i], i+4))
4779 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4780 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4782 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4783 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4785 N = N->getOperand(0).getNode();
4786 if (!ISD::isNON_EXTLoad(N))
4789 *LD = cast<LoadSDNode>(N);
4793 // Test whether the given value is a vector value which will be legalized
4795 static bool WillBeConstantPoolLoad(SDNode *N) {
4796 if (N->getOpcode() != ISD::BUILD_VECTOR)
4799 // Check for any non-constant elements.
4800 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4801 switch (N->getOperand(i).getNode()->getOpcode()) {
4803 case ISD::ConstantFP:
4810 // Vectors of all-zeros and all-ones are materialized with special
4811 // instructions rather than being loaded.
4812 return !ISD::isBuildVectorAllZeros(N) &&
4813 !ISD::isBuildVectorAllOnes(N);
4816 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4817 /// match movlp{s|d}. The lower half elements should come from lower half of
4818 /// V1 (and in order), and the upper half elements should come from the upper
4819 /// half of V2 (and in order). And since V1 will become the source of the
4820 /// MOVLP, it must be either a vector load or a scalar load to vector.
4821 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4822 ArrayRef<int> Mask, MVT VT) {
4823 if (!VT.is128BitVector())
4826 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4828 // Is V2 is a vector load, don't do this transformation. We will try to use
4829 // load folding shufps op.
4830 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4833 unsigned NumElems = VT.getVectorNumElements();
4835 if (NumElems != 2 && NumElems != 4)
4837 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4838 if (!isUndefOrEqual(Mask[i], i))
4840 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4841 if (!isUndefOrEqual(Mask[i], i+NumElems))
4846 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4848 static bool isSplatVector(SDNode *N) {
4849 if (N->getOpcode() != ISD::BUILD_VECTOR)
4852 SDValue SplatValue = N->getOperand(0);
4853 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4854 if (N->getOperand(i) != SplatValue)
4859 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4860 /// to an zero vector.
4861 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4862 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4863 SDValue V1 = N->getOperand(0);
4864 SDValue V2 = N->getOperand(1);
4865 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4866 for (unsigned i = 0; i != NumElems; ++i) {
4867 int Idx = N->getMaskElt(i);
4868 if (Idx >= (int)NumElems) {
4869 unsigned Opc = V2.getOpcode();
4870 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4872 if (Opc != ISD::BUILD_VECTOR ||
4873 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4875 } else if (Idx >= 0) {
4876 unsigned Opc = V1.getOpcode();
4877 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4879 if (Opc != ISD::BUILD_VECTOR ||
4880 !X86::isZeroNode(V1.getOperand(Idx)))
4887 /// getZeroVector - Returns a vector of specified type with all zero elements.
4889 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4890 SelectionDAG &DAG, SDLoc dl) {
4891 assert(VT.isVector() && "Expected a vector type");
4893 // Always build SSE zero vectors as <4 x i32> bitcasted
4894 // to their dest type. This ensures they get CSE'd.
4896 if (VT.is128BitVector()) { // SSE
4897 if (Subtarget->hasSSE2()) { // SSE2
4898 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4899 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4901 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4902 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4904 } else if (VT.is256BitVector()) { // AVX
4905 if (Subtarget->hasInt256()) { // AVX2
4906 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4907 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4908 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4910 // 256-bit logic and arithmetic instructions in AVX are all
4911 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4912 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4913 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4914 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4916 } else if (VT.is512BitVector()) { // AVX-512
4917 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4918 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4919 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4920 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4921 } else if (VT.getScalarType() == MVT::i1) {
4922 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4923 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4924 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4925 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4927 llvm_unreachable("Unexpected vector type");
4929 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4932 /// getOnesVector - Returns a vector of specified type with all bits set.
4933 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4934 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4935 /// Then bitcast to their original type, ensuring they get CSE'd.
4936 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4938 assert(VT.isVector() && "Expected a vector type");
4940 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4942 if (VT.is256BitVector()) {
4943 if (HasInt256) { // AVX2
4944 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4945 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4947 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4948 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4950 } else if (VT.is128BitVector()) {
4951 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4953 llvm_unreachable("Unexpected vector type");
4955 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4958 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4959 /// that point to V2 points to its first element.
4960 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4961 for (unsigned i = 0; i != NumElems; ++i) {
4962 if (Mask[i] > (int)NumElems) {
4968 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4969 /// operation of specified width.
4970 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4972 unsigned NumElems = VT.getVectorNumElements();
4973 SmallVector<int, 8> Mask;
4974 Mask.push_back(NumElems);
4975 for (unsigned i = 1; i != NumElems; ++i)
4977 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4980 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4981 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4983 unsigned NumElems = VT.getVectorNumElements();
4984 SmallVector<int, 8> Mask;
4985 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4987 Mask.push_back(i + NumElems);
4989 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4992 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4993 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4995 unsigned NumElems = VT.getVectorNumElements();
4996 SmallVector<int, 8> Mask;
4997 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4998 Mask.push_back(i + Half);
4999 Mask.push_back(i + NumElems + Half);
5001 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5004 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5005 // a generic shuffle instruction because the target has no such instructions.
5006 // Generate shuffles which repeat i16 and i8 several times until they can be
5007 // represented by v4f32 and then be manipulated by target suported shuffles.
5008 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5009 MVT VT = V.getSimpleValueType();
5010 int NumElems = VT.getVectorNumElements();
5013 while (NumElems > 4) {
5014 if (EltNo < NumElems/2) {
5015 V = getUnpackl(DAG, dl, VT, V, V);
5017 V = getUnpackh(DAG, dl, VT, V, V);
5018 EltNo -= NumElems/2;
5025 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5026 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5027 MVT VT = V.getSimpleValueType();
5030 if (VT.is128BitVector()) {
5031 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5032 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5033 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5035 } else if (VT.is256BitVector()) {
5036 // To use VPERMILPS to splat scalars, the second half of indicies must
5037 // refer to the higher part, which is a duplication of the lower one,
5038 // because VPERMILPS can only handle in-lane permutations.
5039 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5040 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5042 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5043 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5046 llvm_unreachable("Vector size not supported");
5048 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5051 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5052 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5053 MVT SrcVT = SV->getSimpleValueType(0);
5054 SDValue V1 = SV->getOperand(0);
5057 int EltNo = SV->getSplatIndex();
5058 int NumElems = SrcVT.getVectorNumElements();
5059 bool Is256BitVec = SrcVT.is256BitVector();
5061 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5062 "Unknown how to promote splat for type");
5064 // Extract the 128-bit part containing the splat element and update
5065 // the splat element index when it refers to the higher register.
5067 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5068 if (EltNo >= NumElems/2)
5069 EltNo -= NumElems/2;
5072 // All i16 and i8 vector types can't be used directly by a generic shuffle
5073 // instruction because the target has no such instruction. Generate shuffles
5074 // which repeat i16 and i8 several times until they fit in i32, and then can
5075 // be manipulated by target suported shuffles.
5076 MVT EltVT = SrcVT.getVectorElementType();
5077 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5078 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5080 // Recreate the 256-bit vector and place the same 128-bit vector
5081 // into the low and high part. This is necessary because we want
5082 // to use VPERM* to shuffle the vectors
5084 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5087 return getLegalSplat(DAG, V1, EltNo);
5090 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5091 /// vector of zero or undef vector. This produces a shuffle where the low
5092 /// element of V2 is swizzled into the zero/undef vector, landing at element
5093 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5094 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5096 const X86Subtarget *Subtarget,
5097 SelectionDAG &DAG) {
5098 MVT VT = V2.getSimpleValueType();
5100 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5101 unsigned NumElems = VT.getVectorNumElements();
5102 SmallVector<int, 16> MaskVec;
5103 for (unsigned i = 0; i != NumElems; ++i)
5104 // If this is the insertion idx, put the low elt of V2 here.
5105 MaskVec.push_back(i == Idx ? NumElems : i);
5106 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5109 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5110 /// target specific opcode. Returns true if the Mask could be calculated.
5111 /// Sets IsUnary to true if only uses one source.
5112 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5113 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5114 unsigned NumElems = VT.getVectorNumElements();
5118 switch(N->getOpcode()) {
5120 ImmN = N->getOperand(N->getNumOperands()-1);
5121 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5123 case X86ISD::UNPCKH:
5124 DecodeUNPCKHMask(VT, Mask);
5126 case X86ISD::UNPCKL:
5127 DecodeUNPCKLMask(VT, Mask);
5129 case X86ISD::MOVHLPS:
5130 DecodeMOVHLPSMask(NumElems, Mask);
5132 case X86ISD::MOVLHPS:
5133 DecodeMOVLHPSMask(NumElems, Mask);
5135 case X86ISD::PALIGNR:
5136 ImmN = N->getOperand(N->getNumOperands()-1);
5137 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5139 case X86ISD::PSHUFD:
5140 case X86ISD::VPERMILP:
5141 ImmN = N->getOperand(N->getNumOperands()-1);
5142 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5145 case X86ISD::PSHUFHW:
5146 ImmN = N->getOperand(N->getNumOperands()-1);
5147 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5150 case X86ISD::PSHUFLW:
5151 ImmN = N->getOperand(N->getNumOperands()-1);
5152 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5155 case X86ISD::VPERMI:
5156 ImmN = N->getOperand(N->getNumOperands()-1);
5157 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5161 case X86ISD::MOVSD: {
5162 // The index 0 always comes from the first element of the second source,
5163 // this is why MOVSS and MOVSD are used in the first place. The other
5164 // elements come from the other positions of the first source vector
5165 Mask.push_back(NumElems);
5166 for (unsigned i = 1; i != NumElems; ++i) {
5171 case X86ISD::VPERM2X128:
5172 ImmN = N->getOperand(N->getNumOperands()-1);
5173 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5174 if (Mask.empty()) return false;
5176 case X86ISD::MOVDDUP:
5177 case X86ISD::MOVLHPD:
5178 case X86ISD::MOVLPD:
5179 case X86ISD::MOVLPS:
5180 case X86ISD::MOVSHDUP:
5181 case X86ISD::MOVSLDUP:
5182 // Not yet implemented
5184 default: llvm_unreachable("unknown target shuffle node");
5190 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5191 /// element of the result of the vector shuffle.
5192 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5195 return SDValue(); // Limit search depth.
5197 SDValue V = SDValue(N, 0);
5198 EVT VT = V.getValueType();
5199 unsigned Opcode = V.getOpcode();
5201 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5202 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5203 int Elt = SV->getMaskElt(Index);
5206 return DAG.getUNDEF(VT.getVectorElementType());
5208 unsigned NumElems = VT.getVectorNumElements();
5209 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5210 : SV->getOperand(1);
5211 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5214 // Recurse into target specific vector shuffles to find scalars.
5215 if (isTargetShuffle(Opcode)) {
5216 MVT ShufVT = V.getSimpleValueType();
5217 unsigned NumElems = ShufVT.getVectorNumElements();
5218 SmallVector<int, 16> ShuffleMask;
5221 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5224 int Elt = ShuffleMask[Index];
5226 return DAG.getUNDEF(ShufVT.getVectorElementType());
5228 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5230 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5234 // Actual nodes that may contain scalar elements
5235 if (Opcode == ISD::BITCAST) {
5236 V = V.getOperand(0);
5237 EVT SrcVT = V.getValueType();
5238 unsigned NumElems = VT.getVectorNumElements();
5240 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5244 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5245 return (Index == 0) ? V.getOperand(0)
5246 : DAG.getUNDEF(VT.getVectorElementType());
5248 if (V.getOpcode() == ISD::BUILD_VECTOR)
5249 return V.getOperand(Index);
5254 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5255 /// shuffle operation which come from a consecutively from a zero. The
5256 /// search can start in two different directions, from left or right.
5257 /// We count undefs as zeros until PreferredNum is reached.
5258 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5259 unsigned NumElems, bool ZerosFromLeft,
5261 unsigned PreferredNum = -1U) {
5262 unsigned NumZeros = 0;
5263 for (unsigned i = 0; i != NumElems; ++i) {
5264 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5265 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5269 if (X86::isZeroNode(Elt))
5271 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5272 NumZeros = std::min(NumZeros + 1, PreferredNum);
5280 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5281 /// correspond consecutively to elements from one of the vector operands,
5282 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5284 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5285 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5286 unsigned NumElems, unsigned &OpNum) {
5287 bool SeenV1 = false;
5288 bool SeenV2 = false;
5290 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5291 int Idx = SVOp->getMaskElt(i);
5292 // Ignore undef indicies
5296 if (Idx < (int)NumElems)
5301 // Only accept consecutive elements from the same vector
5302 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5306 OpNum = SeenV1 ? 0 : 1;
5310 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5311 /// logical left shift of a vector.
5312 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5313 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5315 SVOp->getSimpleValueType(0).getVectorNumElements();
5316 unsigned NumZeros = getNumOfConsecutiveZeros(
5317 SVOp, NumElems, false /* check zeros from right */, DAG,
5318 SVOp->getMaskElt(0));
5324 // Considering the elements in the mask that are not consecutive zeros,
5325 // check if they consecutively come from only one of the source vectors.
5327 // V1 = {X, A, B, C} 0
5329 // vector_shuffle V1, V2 <1, 2, 3, X>
5331 if (!isShuffleMaskConsecutive(SVOp,
5332 0, // Mask Start Index
5333 NumElems-NumZeros, // Mask End Index(exclusive)
5334 NumZeros, // Where to start looking in the src vector
5335 NumElems, // Number of elements in vector
5336 OpSrc)) // Which source operand ?
5341 ShVal = SVOp->getOperand(OpSrc);
5345 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5346 /// logical left shift of a vector.
5347 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5348 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5350 SVOp->getSimpleValueType(0).getVectorNumElements();
5351 unsigned NumZeros = getNumOfConsecutiveZeros(
5352 SVOp, NumElems, true /* check zeros from left */, DAG,
5353 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5359 // Considering the elements in the mask that are not consecutive zeros,
5360 // check if they consecutively come from only one of the source vectors.
5362 // 0 { A, B, X, X } = V2
5364 // vector_shuffle V1, V2 <X, X, 4, 5>
5366 if (!isShuffleMaskConsecutive(SVOp,
5367 NumZeros, // Mask Start Index
5368 NumElems, // Mask End Index(exclusive)
5369 0, // Where to start looking in the src vector
5370 NumElems, // Number of elements in vector
5371 OpSrc)) // Which source operand ?
5376 ShVal = SVOp->getOperand(OpSrc);
5380 /// isVectorShift - Returns true if the shuffle can be implemented as a
5381 /// logical left or right shift of a vector.
5382 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5383 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5384 // Although the logic below support any bitwidth size, there are no
5385 // shift instructions which handle more than 128-bit vectors.
5386 if (!SVOp->getSimpleValueType(0).is128BitVector())
5389 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5390 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5396 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5398 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5399 unsigned NumNonZero, unsigned NumZero,
5401 const X86Subtarget* Subtarget,
5402 const TargetLowering &TLI) {
5409 for (unsigned i = 0; i < 16; ++i) {
5410 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5411 if (ThisIsNonZero && First) {
5413 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5415 V = DAG.getUNDEF(MVT::v8i16);
5420 SDValue ThisElt, LastElt;
5421 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5422 if (LastIsNonZero) {
5423 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5424 MVT::i16, Op.getOperand(i-1));
5426 if (ThisIsNonZero) {
5427 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5428 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5429 ThisElt, DAG.getConstant(8, MVT::i8));
5431 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5435 if (ThisElt.getNode())
5436 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5437 DAG.getIntPtrConstant(i/2));
5441 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5444 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5446 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5447 unsigned NumNonZero, unsigned NumZero,
5449 const X86Subtarget* Subtarget,
5450 const TargetLowering &TLI) {
5457 for (unsigned i = 0; i < 8; ++i) {
5458 bool isNonZero = (NonZeros & (1 << i)) != 0;
5462 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5464 V = DAG.getUNDEF(MVT::v8i16);
5467 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5468 MVT::v8i16, V, Op.getOperand(i),
5469 DAG.getIntPtrConstant(i));
5476 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5477 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5478 unsigned NonZeros, unsigned NumNonZero,
5479 unsigned NumZero, SelectionDAG &DAG,
5480 const X86Subtarget *Subtarget,
5481 const TargetLowering &TLI) {
5482 // We know there's at least one non-zero element
5483 unsigned FirstNonZeroIdx = 0;
5484 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5485 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5486 X86::isZeroNode(FirstNonZero)) {
5488 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5491 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5492 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5495 SDValue V = FirstNonZero.getOperand(0);
5496 MVT VVT = V.getSimpleValueType();
5497 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5500 unsigned FirstNonZeroDst =
5501 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5502 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5503 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5504 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5506 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5507 SDValue Elem = Op.getOperand(Idx);
5508 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5511 // TODO: What else can be here? Deal with it.
5512 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5515 // TODO: Some optimizations are still possible here
5516 // ex: Getting one element from a vector, and the rest from another.
5517 if (Elem.getOperand(0) != V)
5520 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5523 else if (IncorrectIdx == -1U) {
5527 // There was already one element with an incorrect index.
5528 // We can't optimize this case to an insertps.
5532 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5534 EVT VT = Op.getSimpleValueType();
5535 unsigned ElementMoveMask = 0;
5536 if (IncorrectIdx == -1U)
5537 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5539 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5541 SDValue InsertpsMask =
5542 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5543 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5549 /// getVShift - Return a vector logical shift node.
5551 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5552 unsigned NumBits, SelectionDAG &DAG,
5553 const TargetLowering &TLI, SDLoc dl) {
5554 assert(VT.is128BitVector() && "Unknown type for VShift");
5555 EVT ShVT = MVT::v2i64;
5556 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5557 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5558 return DAG.getNode(ISD::BITCAST, dl, VT,
5559 DAG.getNode(Opc, dl, ShVT, SrcOp,
5560 DAG.getConstant(NumBits,
5561 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5565 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5567 // Check if the scalar load can be widened into a vector load. And if
5568 // the address is "base + cst" see if the cst can be "absorbed" into
5569 // the shuffle mask.
5570 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5571 SDValue Ptr = LD->getBasePtr();
5572 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5574 EVT PVT = LD->getValueType(0);
5575 if (PVT != MVT::i32 && PVT != MVT::f32)
5580 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5581 FI = FINode->getIndex();
5583 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5584 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5585 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5586 Offset = Ptr.getConstantOperandVal(1);
5587 Ptr = Ptr.getOperand(0);
5592 // FIXME: 256-bit vector instructions don't require a strict alignment,
5593 // improve this code to support it better.
5594 unsigned RequiredAlign = VT.getSizeInBits()/8;
5595 SDValue Chain = LD->getChain();
5596 // Make sure the stack object alignment is at least 16 or 32.
5597 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5598 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5599 if (MFI->isFixedObjectIndex(FI)) {
5600 // Can't change the alignment. FIXME: It's possible to compute
5601 // the exact stack offset and reference FI + adjust offset instead.
5602 // If someone *really* cares about this. That's the way to implement it.
5605 MFI->setObjectAlignment(FI, RequiredAlign);
5609 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5610 // Ptr + (Offset & ~15).
5613 if ((Offset % RequiredAlign) & 3)
5615 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5617 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5618 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5620 int EltNo = (Offset - StartOffset) >> 2;
5621 unsigned NumElems = VT.getVectorNumElements();
5623 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5624 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5625 LD->getPointerInfo().getWithOffset(StartOffset),
5626 false, false, false, 0);
5628 SmallVector<int, 8> Mask;
5629 for (unsigned i = 0; i != NumElems; ++i)
5630 Mask.push_back(EltNo);
5632 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5638 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5639 /// vector of type 'VT', see if the elements can be replaced by a single large
5640 /// load which has the same value as a build_vector whose operands are 'elts'.
5642 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5644 /// FIXME: we'd also like to handle the case where the last elements are zero
5645 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5646 /// There's even a handy isZeroNode for that purpose.
5647 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5648 SDLoc &DL, SelectionDAG &DAG,
5649 bool isAfterLegalize) {
5650 EVT EltVT = VT.getVectorElementType();
5651 unsigned NumElems = Elts.size();
5653 LoadSDNode *LDBase = nullptr;
5654 unsigned LastLoadedElt = -1U;
5656 // For each element in the initializer, see if we've found a load or an undef.
5657 // If we don't find an initial load element, or later load elements are
5658 // non-consecutive, bail out.
5659 for (unsigned i = 0; i < NumElems; ++i) {
5660 SDValue Elt = Elts[i];
5662 if (!Elt.getNode() ||
5663 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5666 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5668 LDBase = cast<LoadSDNode>(Elt.getNode());
5672 if (Elt.getOpcode() == ISD::UNDEF)
5675 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5676 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5681 // If we have found an entire vector of loads and undefs, then return a large
5682 // load of the entire vector width starting at the base pointer. If we found
5683 // consecutive loads for the low half, generate a vzext_load node.
5684 if (LastLoadedElt == NumElems - 1) {
5686 if (isAfterLegalize &&
5687 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5690 SDValue NewLd = SDValue();
5692 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5693 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5694 LDBase->getPointerInfo(),
5695 LDBase->isVolatile(), LDBase->isNonTemporal(),
5696 LDBase->isInvariant(), 0);
5697 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5698 LDBase->getPointerInfo(),
5699 LDBase->isVolatile(), LDBase->isNonTemporal(),
5700 LDBase->isInvariant(), LDBase->getAlignment());
5702 if (LDBase->hasAnyUseOfValue(1)) {
5703 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5705 SDValue(NewLd.getNode(), 1));
5706 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5707 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5708 SDValue(NewLd.getNode(), 1));
5713 if (NumElems == 4 && LastLoadedElt == 1 &&
5714 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5715 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5716 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5718 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5719 LDBase->getPointerInfo(),
5720 LDBase->getAlignment(),
5721 false/*isVolatile*/, true/*ReadMem*/,
5724 // Make sure the newly-created LOAD is in the same position as LDBase in
5725 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5726 // update uses of LDBase's output chain to use the TokenFactor.
5727 if (LDBase->hasAnyUseOfValue(1)) {
5728 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5729 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5730 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5731 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5732 SDValue(ResNode.getNode(), 1));
5735 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5740 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5741 /// to generate a splat value for the following cases:
5742 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5743 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5744 /// a scalar load, or a constant.
5745 /// The VBROADCAST node is returned when a pattern is found,
5746 /// or SDValue() otherwise.
5747 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5748 SelectionDAG &DAG) {
5749 if (!Subtarget->hasFp256())
5752 MVT VT = Op.getSimpleValueType();
5755 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5756 "Unsupported vector type for broadcast.");
5761 switch (Op.getOpcode()) {
5763 // Unknown pattern found.
5766 case ISD::BUILD_VECTOR: {
5767 // The BUILD_VECTOR node must be a splat.
5768 if (!isSplatVector(Op.getNode()))
5771 Ld = Op.getOperand(0);
5772 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5773 Ld.getOpcode() == ISD::ConstantFP);
5775 // The suspected load node has several users. Make sure that all
5776 // of its users are from the BUILD_VECTOR node.
5777 // Constants may have multiple users.
5778 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5783 case ISD::VECTOR_SHUFFLE: {
5784 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5786 // Shuffles must have a splat mask where the first element is
5788 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5791 SDValue Sc = Op.getOperand(0);
5792 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5793 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5795 if (!Subtarget->hasInt256())
5798 // Use the register form of the broadcast instruction available on AVX2.
5799 if (VT.getSizeInBits() >= 256)
5800 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5801 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5804 Ld = Sc.getOperand(0);
5805 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5806 Ld.getOpcode() == ISD::ConstantFP);
5808 // The scalar_to_vector node and the suspected
5809 // load node must have exactly one user.
5810 // Constants may have multiple users.
5812 // AVX-512 has register version of the broadcast
5813 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5814 Ld.getValueType().getSizeInBits() >= 32;
5815 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5822 bool IsGE256 = (VT.getSizeInBits() >= 256);
5824 // Handle the broadcasting a single constant scalar from the constant pool
5825 // into a vector. On Sandybridge it is still better to load a constant vector
5826 // from the constant pool and not to broadcast it from a scalar.
5827 if (ConstSplatVal && Subtarget->hasInt256()) {
5828 EVT CVT = Ld.getValueType();
5829 assert(!CVT.isVector() && "Must not broadcast a vector type");
5830 unsigned ScalarSize = CVT.getSizeInBits();
5832 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5833 const Constant *C = nullptr;
5834 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5835 C = CI->getConstantIntValue();
5836 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5837 C = CF->getConstantFPValue();
5839 assert(C && "Invalid constant type");
5841 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5842 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5843 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5844 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5845 MachinePointerInfo::getConstantPool(),
5846 false, false, false, Alignment);
5848 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5852 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5853 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5855 // Handle AVX2 in-register broadcasts.
5856 if (!IsLoad && Subtarget->hasInt256() &&
5857 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5858 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5860 // The scalar source must be a normal load.
5864 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5865 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5867 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5868 // double since there is no vbroadcastsd xmm
5869 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5870 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5871 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5874 // Unsupported broadcast.
5878 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5879 /// underlying vector and index.
5881 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5883 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5885 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5886 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5889 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5891 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5893 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5894 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5897 // In this case the vector is the extract_subvector expression and the index
5898 // is 2, as specified by the shuffle.
5899 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5900 SDValue ShuffleVec = SVOp->getOperand(0);
5901 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5902 assert(ShuffleVecVT.getVectorElementType() ==
5903 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5905 int ShuffleIdx = SVOp->getMaskElt(Idx);
5906 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5907 ExtractedFromVec = ShuffleVec;
5913 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5914 MVT VT = Op.getSimpleValueType();
5916 // Skip if insert_vec_elt is not supported.
5917 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5918 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5922 unsigned NumElems = Op.getNumOperands();
5926 SmallVector<unsigned, 4> InsertIndices;
5927 SmallVector<int, 8> Mask(NumElems, -1);
5929 for (unsigned i = 0; i != NumElems; ++i) {
5930 unsigned Opc = Op.getOperand(i).getOpcode();
5932 if (Opc == ISD::UNDEF)
5935 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5936 // Quit if more than 1 elements need inserting.
5937 if (InsertIndices.size() > 1)
5940 InsertIndices.push_back(i);
5944 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5945 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5946 // Quit if non-constant index.
5947 if (!isa<ConstantSDNode>(ExtIdx))
5949 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5951 // Quit if extracted from vector of different type.
5952 if (ExtractedFromVec.getValueType() != VT)
5955 if (!VecIn1.getNode())
5956 VecIn1 = ExtractedFromVec;
5957 else if (VecIn1 != ExtractedFromVec) {
5958 if (!VecIn2.getNode())
5959 VecIn2 = ExtractedFromVec;
5960 else if (VecIn2 != ExtractedFromVec)
5961 // Quit if more than 2 vectors to shuffle
5965 if (ExtractedFromVec == VecIn1)
5967 else if (ExtractedFromVec == VecIn2)
5968 Mask[i] = Idx + NumElems;
5971 if (!VecIn1.getNode())
5974 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5975 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5976 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5977 unsigned Idx = InsertIndices[i];
5978 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5979 DAG.getIntPtrConstant(Idx));
5985 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5987 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5989 MVT VT = Op.getSimpleValueType();
5990 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5991 "Unexpected type in LowerBUILD_VECTORvXi1!");
5994 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5995 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5996 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5997 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6000 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6001 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6002 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6006 bool AllContants = true;
6007 uint64_t Immediate = 0;
6008 int NonConstIdx = -1;
6009 bool IsSplat = true;
6010 unsigned NumNonConsts = 0;
6011 unsigned NumConsts = 0;
6012 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6013 SDValue In = Op.getOperand(idx);
6014 if (In.getOpcode() == ISD::UNDEF)
6016 if (!isa<ConstantSDNode>(In)) {
6017 AllContants = false;
6023 if (cast<ConstantSDNode>(In)->getZExtValue())
6024 Immediate |= (1ULL << idx);
6026 if (In != Op.getOperand(0))
6031 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6032 DAG.getConstant(Immediate, MVT::i16));
6033 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6034 DAG.getIntPtrConstant(0));
6037 if (NumNonConsts == 1 && NonConstIdx != 0) {
6040 SDValue VecAsImm = DAG.getConstant(Immediate,
6041 MVT::getIntegerVT(VT.getSizeInBits()));
6042 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6045 DstVec = DAG.getUNDEF(VT);
6046 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6047 Op.getOperand(NonConstIdx),
6048 DAG.getIntPtrConstant(NonConstIdx));
6050 if (!IsSplat && (NonConstIdx != 0))
6051 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6052 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6055 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6056 DAG.getConstant(-1, SelectVT),
6057 DAG.getConstant(0, SelectVT));
6059 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6060 DAG.getConstant((Immediate | 1), SelectVT),
6061 DAG.getConstant(Immediate, SelectVT));
6062 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6065 /// \brief Return true if \p N implements a horizontal binop and return the
6066 /// operands for the horizontal binop into V0 and V1.
6068 /// This is a helper function of PerformBUILD_VECTORCombine.
6069 /// This function checks that the build_vector \p N in input implements a
6070 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6071 /// operation to match.
6072 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6073 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6074 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6077 /// This function only analyzes elements of \p N whose indices are
6078 /// in range [BaseIdx, LastIdx).
6079 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6081 unsigned BaseIdx, unsigned LastIdx,
6082 SDValue &V0, SDValue &V1) {
6083 EVT VT = N->getValueType(0);
6085 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6086 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6087 "Invalid Vector in input!");
6089 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6090 bool CanFold = true;
6091 unsigned ExpectedVExtractIdx = BaseIdx;
6092 unsigned NumElts = LastIdx - BaseIdx;
6093 V0 = DAG.getUNDEF(VT);
6094 V1 = DAG.getUNDEF(VT);
6096 // Check if N implements a horizontal binop.
6097 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6098 SDValue Op = N->getOperand(i + BaseIdx);
6101 if (Op->getOpcode() == ISD::UNDEF) {
6102 // Update the expected vector extract index.
6103 if (i * 2 == NumElts)
6104 ExpectedVExtractIdx = BaseIdx;
6105 ExpectedVExtractIdx += 2;
6109 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6114 SDValue Op0 = Op.getOperand(0);
6115 SDValue Op1 = Op.getOperand(1);
6117 // Try to match the following pattern:
6118 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6119 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6120 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6121 Op0.getOperand(0) == Op1.getOperand(0) &&
6122 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6123 isa<ConstantSDNode>(Op1.getOperand(1)));
6127 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6128 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6130 if (i * 2 < NumElts) {
6131 if (V0.getOpcode() == ISD::UNDEF)
6132 V0 = Op0.getOperand(0);
6134 if (V1.getOpcode() == ISD::UNDEF)
6135 V1 = Op0.getOperand(0);
6136 if (i * 2 == NumElts)
6137 ExpectedVExtractIdx = BaseIdx;
6140 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6141 if (I0 == ExpectedVExtractIdx)
6142 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6143 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6144 // Try to match the following dag sequence:
6145 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6146 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6150 ExpectedVExtractIdx += 2;
6156 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6157 /// a concat_vector.
6159 /// This is a helper function of PerformBUILD_VECTORCombine.
6160 /// This function expects two 256-bit vectors called V0 and V1.
6161 /// At first, each vector is split into two separate 128-bit vectors.
6162 /// Then, the resulting 128-bit vectors are used to implement two
6163 /// horizontal binary operations.
6165 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6167 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6168 /// the two new horizontal binop.
6169 /// When Mode is set, the first horizontal binop dag node would take as input
6170 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6171 /// horizontal binop dag node would take as input the lower 128-bit of V1
6172 /// and the upper 128-bit of V1.
6174 /// HADD V0_LO, V0_HI
6175 /// HADD V1_LO, V1_HI
6177 /// Otherwise, the first horizontal binop dag node takes as input the lower
6178 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6179 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6181 /// HADD V0_LO, V1_LO
6182 /// HADD V0_HI, V1_HI
6184 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6185 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6186 /// the upper 128-bits of the result.
6187 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6188 SDLoc DL, SelectionDAG &DAG,
6189 unsigned X86Opcode, bool Mode,
6190 bool isUndefLO, bool isUndefHI) {
6191 EVT VT = V0.getValueType();
6192 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6193 "Invalid nodes in input!");
6195 unsigned NumElts = VT.getVectorNumElements();
6196 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6197 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6198 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6199 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6200 EVT NewVT = V0_LO.getValueType();
6202 SDValue LO = DAG.getUNDEF(NewVT);
6203 SDValue HI = DAG.getUNDEF(NewVT);
6206 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6207 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6208 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6209 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6210 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6212 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6213 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6214 V1_LO->getOpcode() != ISD::UNDEF))
6215 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6217 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6218 V1_HI->getOpcode() != ISD::UNDEF))
6219 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6222 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6225 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6226 /// sequence of 'vadd + vsub + blendi'.
6227 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6228 const X86Subtarget *Subtarget) {
6230 EVT VT = BV->getValueType(0);
6231 unsigned NumElts = VT.getVectorNumElements();
6232 SDValue InVec0 = DAG.getUNDEF(VT);
6233 SDValue InVec1 = DAG.getUNDEF(VT);
6235 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6236 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6238 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6239 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6240 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6243 // Odd-numbered elements in the input build vector are obtained from
6244 // adding two integer/float elements.
6245 // Even-numbered elements in the input build vector are obtained from
6246 // subtracting two integer/float elements.
6247 unsigned ExpectedOpcode = ISD::FSUB;
6248 unsigned NextExpectedOpcode = ISD::FADD;
6249 bool AddFound = false;
6250 bool SubFound = false;
6252 for (unsigned i = 0, e = NumElts; i != e; i++) {
6253 SDValue Op = BV->getOperand(i);
6255 // Skip 'undef' values.
6256 unsigned Opcode = Op.getOpcode();
6257 if (Opcode == ISD::UNDEF) {
6258 std::swap(ExpectedOpcode, NextExpectedOpcode);
6262 // Early exit if we found an unexpected opcode.
6263 if (Opcode != ExpectedOpcode)
6266 SDValue Op0 = Op.getOperand(0);
6267 SDValue Op1 = Op.getOperand(1);
6269 // Try to match the following pattern:
6270 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6271 // Early exit if we cannot match that sequence.
6272 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6273 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6274 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6275 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6276 Op0.getOperand(1) != Op1.getOperand(1))
6279 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6283 // We found a valid add/sub node. Update the information accordingly.
6289 // Update InVec0 and InVec1.
6290 if (InVec0.getOpcode() == ISD::UNDEF)
6291 InVec0 = Op0.getOperand(0);
6292 if (InVec1.getOpcode() == ISD::UNDEF)
6293 InVec1 = Op1.getOperand(0);
6295 // Make sure that operands in input to each add/sub node always
6296 // come from a same pair of vectors.
6297 if (InVec0 != Op0.getOperand(0)) {
6298 if (ExpectedOpcode == ISD::FSUB)
6301 // FADD is commutable. Try to commute the operands
6302 // and then test again.
6303 std::swap(Op0, Op1);
6304 if (InVec0 != Op0.getOperand(0))
6308 if (InVec1 != Op1.getOperand(0))
6311 // Update the pair of expected opcodes.
6312 std::swap(ExpectedOpcode, NextExpectedOpcode);
6315 // Don't try to fold this build_vector into a VSELECT if it has
6316 // too many UNDEF operands.
6317 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6318 InVec1.getOpcode() != ISD::UNDEF) {
6319 // Emit a sequence of vector add and sub followed by a VSELECT.
6320 // The new VSELECT will be lowered into a BLENDI.
6321 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6322 // and emit a single ADDSUB instruction.
6323 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6324 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6326 // Construct the VSELECT mask.
6327 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6328 EVT SVT = MaskVT.getVectorElementType();
6329 unsigned SVTBits = SVT.getSizeInBits();
6330 SmallVector<SDValue, 8> Ops;
6332 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6333 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6334 APInt::getAllOnesValue(SVTBits);
6335 SDValue Constant = DAG.getConstant(Value, SVT);
6336 Ops.push_back(Constant);
6339 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6340 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6346 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6347 const X86Subtarget *Subtarget) {
6349 EVT VT = N->getValueType(0);
6350 unsigned NumElts = VT.getVectorNumElements();
6351 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6352 SDValue InVec0, InVec1;
6354 // Try to match an ADDSUB.
6355 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6356 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6357 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6358 if (Value.getNode())
6362 // Try to match horizontal ADD/SUB.
6363 unsigned NumUndefsLO = 0;
6364 unsigned NumUndefsHI = 0;
6365 unsigned Half = NumElts/2;
6367 // Count the number of UNDEF operands in the build_vector in input.
6368 for (unsigned i = 0, e = Half; i != e; ++i)
6369 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6372 for (unsigned i = Half, e = NumElts; i != e; ++i)
6373 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6376 // Early exit if this is either a build_vector of all UNDEFs or all the
6377 // operands but one are UNDEF.
6378 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6381 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6382 // Try to match an SSE3 float HADD/HSUB.
6383 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6384 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6386 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6387 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6388 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6389 // Try to match an SSSE3 integer HADD/HSUB.
6390 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6391 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6393 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6394 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6397 if (!Subtarget->hasAVX())
6400 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6401 // Try to match an AVX horizontal add/sub of packed single/double
6402 // precision floating point values from 256-bit vectors.
6403 SDValue InVec2, InVec3;
6404 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6405 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6406 ((InVec0.getOpcode() == ISD::UNDEF ||
6407 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6408 ((InVec1.getOpcode() == ISD::UNDEF ||
6409 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6410 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6412 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6413 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6414 ((InVec0.getOpcode() == ISD::UNDEF ||
6415 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6416 ((InVec1.getOpcode() == ISD::UNDEF ||
6417 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6418 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6419 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6420 // Try to match an AVX2 horizontal add/sub of signed integers.
6421 SDValue InVec2, InVec3;
6423 bool CanFold = true;
6425 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6426 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6427 ((InVec0.getOpcode() == ISD::UNDEF ||
6428 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6429 ((InVec1.getOpcode() == ISD::UNDEF ||
6430 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6431 X86Opcode = X86ISD::HADD;
6432 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6433 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6434 ((InVec0.getOpcode() == ISD::UNDEF ||
6435 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6436 ((InVec1.getOpcode() == ISD::UNDEF ||
6437 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6438 X86Opcode = X86ISD::HSUB;
6443 // Fold this build_vector into a single horizontal add/sub.
6444 // Do this only if the target has AVX2.
6445 if (Subtarget->hasAVX2())
6446 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6448 // Do not try to expand this build_vector into a pair of horizontal
6449 // add/sub if we can emit a pair of scalar add/sub.
6450 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6453 // Convert this build_vector into a pair of horizontal binop followed by
6455 bool isUndefLO = NumUndefsLO == Half;
6456 bool isUndefHI = NumUndefsHI == Half;
6457 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6458 isUndefLO, isUndefHI);
6462 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6463 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6465 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6466 X86Opcode = X86ISD::HADD;
6467 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6468 X86Opcode = X86ISD::HSUB;
6469 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6470 X86Opcode = X86ISD::FHADD;
6471 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6472 X86Opcode = X86ISD::FHSUB;
6476 // Don't try to expand this build_vector into a pair of horizontal add/sub
6477 // if we can simply emit a pair of scalar add/sub.
6478 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6481 // Convert this build_vector into two horizontal add/sub followed by
6483 bool isUndefLO = NumUndefsLO == Half;
6484 bool isUndefHI = NumUndefsHI == Half;
6485 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6486 isUndefLO, isUndefHI);
6493 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6496 MVT VT = Op.getSimpleValueType();
6497 MVT ExtVT = VT.getVectorElementType();
6498 unsigned NumElems = Op.getNumOperands();
6500 // Generate vectors for predicate vectors.
6501 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6502 return LowerBUILD_VECTORvXi1(Op, DAG);
6504 // Vectors containing all zeros can be matched by pxor and xorps later
6505 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6506 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6507 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6508 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6511 return getZeroVector(VT, Subtarget, DAG, dl);
6514 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6515 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6516 // vpcmpeqd on 256-bit vectors.
6517 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6518 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6521 if (!VT.is512BitVector())
6522 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6525 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6526 if (Broadcast.getNode())
6529 unsigned EVTBits = ExtVT.getSizeInBits();
6531 unsigned NumZero = 0;
6532 unsigned NumNonZero = 0;
6533 unsigned NonZeros = 0;
6534 bool IsAllConstants = true;
6535 SmallSet<SDValue, 8> Values;
6536 for (unsigned i = 0; i < NumElems; ++i) {
6537 SDValue Elt = Op.getOperand(i);
6538 if (Elt.getOpcode() == ISD::UNDEF)
6541 if (Elt.getOpcode() != ISD::Constant &&
6542 Elt.getOpcode() != ISD::ConstantFP)
6543 IsAllConstants = false;
6544 if (X86::isZeroNode(Elt))
6547 NonZeros |= (1 << i);
6552 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6553 if (NumNonZero == 0)
6554 return DAG.getUNDEF(VT);
6556 // Special case for single non-zero, non-undef, element.
6557 if (NumNonZero == 1) {
6558 unsigned Idx = countTrailingZeros(NonZeros);
6559 SDValue Item = Op.getOperand(Idx);
6561 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6562 // the value are obviously zero, truncate the value to i32 and do the
6563 // insertion that way. Only do this if the value is non-constant or if the
6564 // value is a constant being inserted into element 0. It is cheaper to do
6565 // a constant pool load than it is to do a movd + shuffle.
6566 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6567 (!IsAllConstants || Idx == 0)) {
6568 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6570 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6571 EVT VecVT = MVT::v4i32;
6572 unsigned VecElts = 4;
6574 // Truncate the value (which may itself be a constant) to i32, and
6575 // convert it to a vector with movd (S2V+shuffle to zero extend).
6576 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6577 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6578 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6580 // Now we have our 32-bit value zero extended in the low element of
6581 // a vector. If Idx != 0, swizzle it into place.
6583 SmallVector<int, 4> Mask;
6584 Mask.push_back(Idx);
6585 for (unsigned i = 1; i != VecElts; ++i)
6587 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6590 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6594 // If we have a constant or non-constant insertion into the low element of
6595 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6596 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6597 // depending on what the source datatype is.
6600 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6602 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6603 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6604 if (VT.is256BitVector() || VT.is512BitVector()) {
6605 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6606 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6607 Item, DAG.getIntPtrConstant(0));
6609 assert(VT.is128BitVector() && "Expected an SSE value type!");
6610 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6611 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6612 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6615 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6616 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6617 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6618 if (VT.is256BitVector()) {
6619 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6620 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6622 assert(VT.is128BitVector() && "Expected an SSE value type!");
6623 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6625 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6629 // Is it a vector logical left shift?
6630 if (NumElems == 2 && Idx == 1 &&
6631 X86::isZeroNode(Op.getOperand(0)) &&
6632 !X86::isZeroNode(Op.getOperand(1))) {
6633 unsigned NumBits = VT.getSizeInBits();
6634 return getVShift(true, VT,
6635 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6636 VT, Op.getOperand(1)),
6637 NumBits/2, DAG, *this, dl);
6640 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6643 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6644 // is a non-constant being inserted into an element other than the low one,
6645 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6646 // movd/movss) to move this into the low element, then shuffle it into
6648 if (EVTBits == 32) {
6649 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6651 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6652 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6653 SmallVector<int, 8> MaskVec;
6654 for (unsigned i = 0; i != NumElems; ++i)
6655 MaskVec.push_back(i == Idx ? 0 : 1);
6656 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6660 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6661 if (Values.size() == 1) {
6662 if (EVTBits == 32) {
6663 // Instead of a shuffle like this:
6664 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6665 // Check if it's possible to issue this instead.
6666 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6667 unsigned Idx = countTrailingZeros(NonZeros);
6668 SDValue Item = Op.getOperand(Idx);
6669 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6670 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6675 // A vector full of immediates; various special cases are already
6676 // handled, so this is best done with a single constant-pool load.
6680 // For AVX-length vectors, build the individual 128-bit pieces and use
6681 // shuffles to put them in place.
6682 if (VT.is256BitVector() || VT.is512BitVector()) {
6683 SmallVector<SDValue, 64> V;
6684 for (unsigned i = 0; i != NumElems; ++i)
6685 V.push_back(Op.getOperand(i));
6687 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6689 // Build both the lower and upper subvector.
6690 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6691 makeArrayRef(&V[0], NumElems/2));
6692 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6693 makeArrayRef(&V[NumElems / 2], NumElems/2));
6695 // Recreate the wider vector with the lower and upper part.
6696 if (VT.is256BitVector())
6697 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6698 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6701 // Let legalizer expand 2-wide build_vectors.
6702 if (EVTBits == 64) {
6703 if (NumNonZero == 1) {
6704 // One half is zero or undef.
6705 unsigned Idx = countTrailingZeros(NonZeros);
6706 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6707 Op.getOperand(Idx));
6708 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6713 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6714 if (EVTBits == 8 && NumElems == 16) {
6715 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6717 if (V.getNode()) return V;
6720 if (EVTBits == 16 && NumElems == 8) {
6721 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6723 if (V.getNode()) return V;
6726 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6727 if (EVTBits == 32 && NumElems == 4) {
6728 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6729 NumZero, DAG, Subtarget, *this);
6734 // If element VT is == 32 bits, turn it into a number of shuffles.
6735 SmallVector<SDValue, 8> V(NumElems);
6736 if (NumElems == 4 && NumZero > 0) {
6737 for (unsigned i = 0; i < 4; ++i) {
6738 bool isZero = !(NonZeros & (1 << i));
6740 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6742 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6745 for (unsigned i = 0; i < 2; ++i) {
6746 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6749 V[i] = V[i*2]; // Must be a zero vector.
6752 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6755 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6758 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6763 bool Reverse1 = (NonZeros & 0x3) == 2;
6764 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6768 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6769 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6771 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6774 if (Values.size() > 1 && VT.is128BitVector()) {
6775 // Check for a build vector of consecutive loads.
6776 for (unsigned i = 0; i < NumElems; ++i)
6777 V[i] = Op.getOperand(i);
6779 // Check for elements which are consecutive loads.
6780 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6784 // Check for a build vector from mostly shuffle plus few inserting.
6785 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6789 // For SSE 4.1, use insertps to put the high elements into the low element.
6790 if (getSubtarget()->hasSSE41()) {
6792 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6793 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6795 Result = DAG.getUNDEF(VT);
6797 for (unsigned i = 1; i < NumElems; ++i) {
6798 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6799 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6800 Op.getOperand(i), DAG.getIntPtrConstant(i));
6805 // Otherwise, expand into a number of unpckl*, start by extending each of
6806 // our (non-undef) elements to the full vector width with the element in the
6807 // bottom slot of the vector (which generates no code for SSE).
6808 for (unsigned i = 0; i < NumElems; ++i) {
6809 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6810 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6812 V[i] = DAG.getUNDEF(VT);
6815 // Next, we iteratively mix elements, e.g. for v4f32:
6816 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6817 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6818 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6819 unsigned EltStride = NumElems >> 1;
6820 while (EltStride != 0) {
6821 for (unsigned i = 0; i < EltStride; ++i) {
6822 // If V[i+EltStride] is undef and this is the first round of mixing,
6823 // then it is safe to just drop this shuffle: V[i] is already in the
6824 // right place, the one element (since it's the first round) being
6825 // inserted as undef can be dropped. This isn't safe for successive
6826 // rounds because they will permute elements within both vectors.
6827 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6828 EltStride == NumElems/2)
6831 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6840 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6841 // to create 256-bit vectors from two other 128-bit ones.
6842 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6844 MVT ResVT = Op.getSimpleValueType();
6846 assert((ResVT.is256BitVector() ||
6847 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6849 SDValue V1 = Op.getOperand(0);
6850 SDValue V2 = Op.getOperand(1);
6851 unsigned NumElems = ResVT.getVectorNumElements();
6852 if(ResVT.is256BitVector())
6853 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6855 if (Op.getNumOperands() == 4) {
6856 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6857 ResVT.getVectorNumElements()/2);
6858 SDValue V3 = Op.getOperand(2);
6859 SDValue V4 = Op.getOperand(3);
6860 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6861 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6863 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6866 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6867 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6868 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6869 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6870 Op.getNumOperands() == 4)));
6872 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6873 // from two other 128-bit ones.
6875 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6876 return LowerAVXCONCAT_VECTORS(Op, DAG);
6879 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6880 bool hasInt256, unsigned *MaskOut = nullptr) {
6881 MVT EltVT = VT.getVectorElementType();
6883 // There is no blend with immediate in AVX-512.
6884 if (VT.is512BitVector())
6887 if (!hasSSE41 || EltVT == MVT::i8)
6889 if (!hasInt256 && VT == MVT::v16i16)
6892 unsigned MaskValue = 0;
6893 unsigned NumElems = VT.getVectorNumElements();
6894 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6895 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6896 unsigned NumElemsInLane = NumElems / NumLanes;
6898 // Blend for v16i16 should be symetric for the both lanes.
6899 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6901 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6902 int EltIdx = MaskVals[i];
6904 if ((EltIdx < 0 || EltIdx == (int)i) &&
6905 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6908 if (((unsigned)EltIdx == (i + NumElems)) &&
6909 (SndLaneEltIdx < 0 ||
6910 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6911 MaskValue |= (1 << i);
6917 *MaskOut = MaskValue;
6921 // Try to lower a shuffle node into a simple blend instruction.
6922 // This function assumes isBlendMask returns true for this
6923 // SuffleVectorSDNode
6924 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6926 const X86Subtarget *Subtarget,
6927 SelectionDAG &DAG) {
6928 MVT VT = SVOp->getSimpleValueType(0);
6929 MVT EltVT = VT.getVectorElementType();
6930 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6931 Subtarget->hasInt256() && "Trying to lower a "
6932 "VECTOR_SHUFFLE to a Blend but "
6933 "with the wrong mask"));
6934 SDValue V1 = SVOp->getOperand(0);
6935 SDValue V2 = SVOp->getOperand(1);
6937 unsigned NumElems = VT.getVectorNumElements();
6939 // Convert i32 vectors to floating point if it is not AVX2.
6940 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6942 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6943 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6945 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6946 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6949 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6950 DAG.getConstant(MaskValue, MVT::i32));
6951 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6954 /// In vector type \p VT, return true if the element at index \p InputIdx
6955 /// falls on a different 128-bit lane than \p OutputIdx.
6956 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6957 unsigned OutputIdx) {
6958 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6959 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6962 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6963 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6964 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6965 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6967 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6968 SelectionDAG &DAG) {
6969 MVT VT = V1.getSimpleValueType();
6970 assert(VT.is128BitVector() || VT.is256BitVector());
6972 MVT EltVT = VT.getVectorElementType();
6973 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6974 unsigned NumElts = VT.getVectorNumElements();
6976 SmallVector<SDValue, 32> PshufbMask;
6977 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6978 int InputIdx = MaskVals[OutputIdx];
6979 unsigned InputByteIdx;
6981 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6982 InputByteIdx = 0x80;
6984 // Cross lane is not allowed.
6985 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6987 InputByteIdx = InputIdx * EltSizeInBytes;
6988 // Index is an byte offset within the 128-bit lane.
6989 InputByteIdx &= 0xf;
6992 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6993 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6994 if (InputByteIdx != 0x80)
6999 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
7001 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
7002 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
7003 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
7006 // v8i16 shuffles - Prefer shuffles in the following order:
7007 // 1. [all] pshuflw, pshufhw, optional move
7008 // 2. [ssse3] 1 x pshufb
7009 // 3. [ssse3] 2 x pshufb + 1 x por
7010 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
7012 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
7013 SelectionDAG &DAG) {
7014 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7015 SDValue V1 = SVOp->getOperand(0);
7016 SDValue V2 = SVOp->getOperand(1);
7018 SmallVector<int, 8> MaskVals;
7020 // Determine if more than 1 of the words in each of the low and high quadwords
7021 // of the result come from the same quadword of one of the two inputs. Undef
7022 // mask values count as coming from any quadword, for better codegen.
7024 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
7025 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
7026 unsigned LoQuad[] = { 0, 0, 0, 0 };
7027 unsigned HiQuad[] = { 0, 0, 0, 0 };
7028 // Indices of quads used.
7029 std::bitset<4> InputQuads;
7030 for (unsigned i = 0; i < 8; ++i) {
7031 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
7032 int EltIdx = SVOp->getMaskElt(i);
7033 MaskVals.push_back(EltIdx);
7042 InputQuads.set(EltIdx / 4);
7045 int BestLoQuad = -1;
7046 unsigned MaxQuad = 1;
7047 for (unsigned i = 0; i < 4; ++i) {
7048 if (LoQuad[i] > MaxQuad) {
7050 MaxQuad = LoQuad[i];
7054 int BestHiQuad = -1;
7056 for (unsigned i = 0; i < 4; ++i) {
7057 if (HiQuad[i] > MaxQuad) {
7059 MaxQuad = HiQuad[i];
7063 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
7064 // of the two input vectors, shuffle them into one input vector so only a
7065 // single pshufb instruction is necessary. If there are more than 2 input
7066 // quads, disable the next transformation since it does not help SSSE3.
7067 bool V1Used = InputQuads[0] || InputQuads[1];
7068 bool V2Used = InputQuads[2] || InputQuads[3];
7069 if (Subtarget->hasSSSE3()) {
7070 if (InputQuads.count() == 2 && V1Used && V2Used) {
7071 BestLoQuad = InputQuads[0] ? 0 : 1;
7072 BestHiQuad = InputQuads[2] ? 2 : 3;
7074 if (InputQuads.count() > 2) {
7080 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
7081 // the shuffle mask. If a quad is scored as -1, that means that it contains
7082 // words from all 4 input quadwords.
7084 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
7086 BestLoQuad < 0 ? 0 : BestLoQuad,
7087 BestHiQuad < 0 ? 1 : BestHiQuad
7089 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
7090 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
7091 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
7092 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
7094 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
7095 // source words for the shuffle, to aid later transformations.
7096 bool AllWordsInNewV = true;
7097 bool InOrder[2] = { true, true };
7098 for (unsigned i = 0; i != 8; ++i) {
7099 int idx = MaskVals[i];
7101 InOrder[i/4] = false;
7102 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
7104 AllWordsInNewV = false;
7108 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
7109 if (AllWordsInNewV) {
7110 for (int i = 0; i != 8; ++i) {
7111 int idx = MaskVals[i];
7114 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
7115 if ((idx != i) && idx < 4)
7117 if ((idx != i) && idx > 3)
7126 // If we've eliminated the use of V2, and the new mask is a pshuflw or
7127 // pshufhw, that's as cheap as it gets. Return the new shuffle.
7128 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
7129 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
7130 unsigned TargetMask = 0;
7131 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
7132 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
7133 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7134 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
7135 getShufflePSHUFLWImmediate(SVOp);
7136 V1 = NewV.getOperand(0);
7137 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
7141 // Promote splats to a larger type which usually leads to more efficient code.
7142 // FIXME: Is this true if pshufb is available?
7143 if (SVOp->isSplat())
7144 return PromoteSplat(SVOp, DAG);
7146 // If we have SSSE3, and all words of the result are from 1 input vector,
7147 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
7148 // is present, fall back to case 4.
7149 if (Subtarget->hasSSSE3()) {
7150 SmallVector<SDValue,16> pshufbMask;
7152 // If we have elements from both input vectors, set the high bit of the
7153 // shuffle mask element to zero out elements that come from V2 in the V1
7154 // mask, and elements that come from V1 in the V2 mask, so that the two
7155 // results can be OR'd together.
7156 bool TwoInputs = V1Used && V2Used;
7157 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
7159 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7161 // Calculate the shuffle mask for the second input, shuffle it, and
7162 // OR it with the first shuffled input.
7163 CommuteVectorShuffleMask(MaskVals, 8);
7164 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
7165 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7166 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7169 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
7170 // and update MaskVals with new element order.
7171 std::bitset<8> InOrder;
7172 if (BestLoQuad >= 0) {
7173 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
7174 for (int i = 0; i != 4; ++i) {
7175 int idx = MaskVals[i];
7178 } else if ((idx / 4) == BestLoQuad) {
7183 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7186 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7187 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7188 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
7190 getShufflePSHUFLWImmediate(SVOp), DAG);
7194 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
7195 // and update MaskVals with the new element order.
7196 if (BestHiQuad >= 0) {
7197 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
7198 for (unsigned i = 4; i != 8; ++i) {
7199 int idx = MaskVals[i];
7202 } else if ((idx / 4) == BestHiQuad) {
7203 MaskV[i] = (idx & 3) + 4;
7207 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7210 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7211 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7212 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
7214 getShufflePSHUFHWImmediate(SVOp), DAG);
7218 // In case BestHi & BestLo were both -1, which means each quadword has a word
7219 // from each of the four input quadwords, calculate the InOrder bitvector now
7220 // before falling through to the insert/extract cleanup.
7221 if (BestLoQuad == -1 && BestHiQuad == -1) {
7223 for (int i = 0; i != 8; ++i)
7224 if (MaskVals[i] < 0 || MaskVals[i] == i)
7228 // The other elements are put in the right place using pextrw and pinsrw.
7229 for (unsigned i = 0; i != 8; ++i) {
7232 int EltIdx = MaskVals[i];
7235 SDValue ExtOp = (EltIdx < 8) ?
7236 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
7237 DAG.getIntPtrConstant(EltIdx)) :
7238 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
7239 DAG.getIntPtrConstant(EltIdx - 8));
7240 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
7241 DAG.getIntPtrConstant(i));
7246 /// \brief v16i16 shuffles
7248 /// FIXME: We only support generation of a single pshufb currently. We can
7249 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
7250 /// well (e.g 2 x pshufb + 1 x por).
7252 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
7253 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7254 SDValue V1 = SVOp->getOperand(0);
7255 SDValue V2 = SVOp->getOperand(1);
7258 if (V2.getOpcode() != ISD::UNDEF)
7261 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7262 return getPSHUFB(MaskVals, V1, dl, DAG);
7265 // v16i8 shuffles - Prefer shuffles in the following order:
7266 // 1. [ssse3] 1 x pshufb
7267 // 2. [ssse3] 2 x pshufb + 1 x por
7268 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
7269 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
7270 const X86Subtarget* Subtarget,
7271 SelectionDAG &DAG) {
7272 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7273 SDValue V1 = SVOp->getOperand(0);
7274 SDValue V2 = SVOp->getOperand(1);
7276 ArrayRef<int> MaskVals = SVOp->getMask();
7278 // Promote splats to a larger type which usually leads to more efficient code.
7279 // FIXME: Is this true if pshufb is available?
7280 if (SVOp->isSplat())
7281 return PromoteSplat(SVOp, DAG);
7283 // If we have SSSE3, case 1 is generated when all result bytes come from
7284 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
7285 // present, fall back to case 3.
7287 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
7288 if (Subtarget->hasSSSE3()) {
7289 SmallVector<SDValue,16> pshufbMask;
7291 // If all result elements are from one input vector, then only translate
7292 // undef mask values to 0x80 (zero out result) in the pshufb mask.
7294 // Otherwise, we have elements from both input vectors, and must zero out
7295 // elements that come from V2 in the first mask, and V1 in the second mask
7296 // so that we can OR them together.
7297 for (unsigned i = 0; i != 16; ++i) {
7298 int EltIdx = MaskVals[i];
7299 if (EltIdx < 0 || EltIdx >= 16)
7301 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7303 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
7304 DAG.getNode(ISD::BUILD_VECTOR, dl,
7305 MVT::v16i8, pshufbMask));
7307 // As PSHUFB will zero elements with negative indices, it's safe to ignore
7308 // the 2nd operand if it's undefined or zero.
7309 if (V2.getOpcode() == ISD::UNDEF ||
7310 ISD::isBuildVectorAllZeros(V2.getNode()))
7313 // Calculate the shuffle mask for the second input, shuffle it, and
7314 // OR it with the first shuffled input.
7316 for (unsigned i = 0; i != 16; ++i) {
7317 int EltIdx = MaskVals[i];
7318 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
7319 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7321 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
7322 DAG.getNode(ISD::BUILD_VECTOR, dl,
7323 MVT::v16i8, pshufbMask));
7324 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7327 // No SSSE3 - Calculate in place words and then fix all out of place words
7328 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
7329 // the 16 different words that comprise the two doublequadword input vectors.
7330 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7331 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7333 for (int i = 0; i != 8; ++i) {
7334 int Elt0 = MaskVals[i*2];
7335 int Elt1 = MaskVals[i*2+1];
7337 // This word of the result is all undef, skip it.
7338 if (Elt0 < 0 && Elt1 < 0)
7341 // This word of the result is already in the correct place, skip it.
7342 if ((Elt0 == i*2) && (Elt1 == i*2+1))
7345 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7346 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7349 // If Elt0 and Elt1 are defined, are consecutive, and can be load
7350 // using a single extract together, load it and store it.
7351 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7352 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7353 DAG.getIntPtrConstant(Elt1 / 2));
7354 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7355 DAG.getIntPtrConstant(i));
7359 // If Elt1 is defined, extract it from the appropriate source. If the
7360 // source byte is not also odd, shift the extracted word left 8 bits
7361 // otherwise clear the bottom 8 bits if we need to do an or.
7363 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7364 DAG.getIntPtrConstant(Elt1 / 2));
7365 if ((Elt1 & 1) == 0)
7366 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7368 TLI.getShiftAmountTy(InsElt.getValueType())));
7370 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7371 DAG.getConstant(0xFF00, MVT::i16));
7373 // If Elt0 is defined, extract it from the appropriate source. If the
7374 // source byte is not also even, shift the extracted word right 8 bits. If
7375 // Elt1 was also defined, OR the extracted values together before
7376 // inserting them in the result.
7378 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7379 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7380 if ((Elt0 & 1) != 0)
7381 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7383 TLI.getShiftAmountTy(InsElt0.getValueType())));
7385 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7386 DAG.getConstant(0x00FF, MVT::i16));
7387 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7390 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7391 DAG.getIntPtrConstant(i));
7393 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7396 // v32i8 shuffles - Translate to VPSHUFB if possible.
7398 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7399 const X86Subtarget *Subtarget,
7400 SelectionDAG &DAG) {
7401 MVT VT = SVOp->getSimpleValueType(0);
7402 SDValue V1 = SVOp->getOperand(0);
7403 SDValue V2 = SVOp->getOperand(1);
7405 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7407 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7408 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7409 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7411 // VPSHUFB may be generated if
7412 // (1) one of input vector is undefined or zeroinitializer.
7413 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7414 // And (2) the mask indexes don't cross the 128-bit lane.
7415 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7416 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7419 if (V1IsAllZero && !V2IsAllZero) {
7420 CommuteVectorShuffleMask(MaskVals, 32);
7423 return getPSHUFB(MaskVals, V1, dl, DAG);
7426 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7427 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7428 /// done when every pair / quad of shuffle mask elements point to elements in
7429 /// the right sequence. e.g.
7430 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7432 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7433 SelectionDAG &DAG) {
7434 MVT VT = SVOp->getSimpleValueType(0);
7436 unsigned NumElems = VT.getVectorNumElements();
7439 switch (VT.SimpleTy) {
7440 default: llvm_unreachable("Unexpected!");
7443 return SDValue(SVOp, 0);
7444 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7445 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7446 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7447 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7448 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7449 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7452 SmallVector<int, 8> MaskVec;
7453 for (unsigned i = 0; i != NumElems; i += Scale) {
7455 for (unsigned j = 0; j != Scale; ++j) {
7456 int EltIdx = SVOp->getMaskElt(i+j);
7460 StartIdx = (EltIdx / Scale);
7461 if (EltIdx != (int)(StartIdx*Scale + j))
7464 MaskVec.push_back(StartIdx);
7467 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7468 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7469 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7472 /// getVZextMovL - Return a zero-extending vector move low node.
7474 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7475 SDValue SrcOp, SelectionDAG &DAG,
7476 const X86Subtarget *Subtarget, SDLoc dl) {
7477 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7478 LoadSDNode *LD = nullptr;
7479 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7480 LD = dyn_cast<LoadSDNode>(SrcOp);
7482 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7484 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7485 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7486 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7487 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7488 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7490 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7491 return DAG.getNode(ISD::BITCAST, dl, VT,
7492 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7493 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7501 return DAG.getNode(ISD::BITCAST, dl, VT,
7502 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7503 DAG.getNode(ISD::BITCAST, dl,
7507 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7508 /// which could not be matched by any known target speficic shuffle
7510 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7512 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7513 if (NewOp.getNode())
7516 MVT VT = SVOp->getSimpleValueType(0);
7518 unsigned NumElems = VT.getVectorNumElements();
7519 unsigned NumLaneElems = NumElems / 2;
7522 MVT EltVT = VT.getVectorElementType();
7523 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7526 SmallVector<int, 16> Mask;
7527 for (unsigned l = 0; l < 2; ++l) {
7528 // Build a shuffle mask for the output, discovering on the fly which
7529 // input vectors to use as shuffle operands (recorded in InputUsed).
7530 // If building a suitable shuffle vector proves too hard, then bail
7531 // out with UseBuildVector set.
7532 bool UseBuildVector = false;
7533 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7534 unsigned LaneStart = l * NumLaneElems;
7535 for (unsigned i = 0; i != NumLaneElems; ++i) {
7536 // The mask element. This indexes into the input.
7537 int Idx = SVOp->getMaskElt(i+LaneStart);
7539 // the mask element does not index into any input vector.
7544 // The input vector this mask element indexes into.
7545 int Input = Idx / NumLaneElems;
7547 // Turn the index into an offset from the start of the input vector.
7548 Idx -= Input * NumLaneElems;
7550 // Find or create a shuffle vector operand to hold this input.
7552 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7553 if (InputUsed[OpNo] == Input)
7554 // This input vector is already an operand.
7556 if (InputUsed[OpNo] < 0) {
7557 // Create a new operand for this input vector.
7558 InputUsed[OpNo] = Input;
7563 if (OpNo >= array_lengthof(InputUsed)) {
7564 // More than two input vectors used! Give up on trying to create a
7565 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7566 UseBuildVector = true;
7570 // Add the mask index for the new shuffle vector.
7571 Mask.push_back(Idx + OpNo * NumLaneElems);
7574 if (UseBuildVector) {
7575 SmallVector<SDValue, 16> SVOps;
7576 for (unsigned i = 0; i != NumLaneElems; ++i) {
7577 // The mask element. This indexes into the input.
7578 int Idx = SVOp->getMaskElt(i+LaneStart);
7580 SVOps.push_back(DAG.getUNDEF(EltVT));
7584 // The input vector this mask element indexes into.
7585 int Input = Idx / NumElems;
7587 // Turn the index into an offset from the start of the input vector.
7588 Idx -= Input * NumElems;
7590 // Extract the vector element by hand.
7591 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7592 SVOp->getOperand(Input),
7593 DAG.getIntPtrConstant(Idx)));
7596 // Construct the output using a BUILD_VECTOR.
7597 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7598 } else if (InputUsed[0] < 0) {
7599 // No input vectors were used! The result is undefined.
7600 Output[l] = DAG.getUNDEF(NVT);
7602 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7603 (InputUsed[0] % 2) * NumLaneElems,
7605 // If only one input was used, use an undefined vector for the other.
7606 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7607 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7608 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7609 // At least one input vector was used. Create a new shuffle vector.
7610 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7616 // Concatenate the result back
7617 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7620 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7621 /// 4 elements, and match them with several different shuffle types.
7623 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7624 SDValue V1 = SVOp->getOperand(0);
7625 SDValue V2 = SVOp->getOperand(1);
7627 MVT VT = SVOp->getSimpleValueType(0);
7629 assert(VT.is128BitVector() && "Unsupported vector size");
7631 std::pair<int, int> Locs[4];
7632 int Mask1[] = { -1, -1, -1, -1 };
7633 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7637 for (unsigned i = 0; i != 4; ++i) {
7638 int Idx = PermMask[i];
7640 Locs[i] = std::make_pair(-1, -1);
7642 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7644 Locs[i] = std::make_pair(0, NumLo);
7648 Locs[i] = std::make_pair(1, NumHi);
7650 Mask1[2+NumHi] = Idx;
7656 if (NumLo <= 2 && NumHi <= 2) {
7657 // If no more than two elements come from either vector. This can be
7658 // implemented with two shuffles. First shuffle gather the elements.
7659 // The second shuffle, which takes the first shuffle as both of its
7660 // vector operands, put the elements into the right order.
7661 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7663 int Mask2[] = { -1, -1, -1, -1 };
7665 for (unsigned i = 0; i != 4; ++i)
7666 if (Locs[i].first != -1) {
7667 unsigned Idx = (i < 2) ? 0 : 4;
7668 Idx += Locs[i].first * 2 + Locs[i].second;
7672 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7675 if (NumLo == 3 || NumHi == 3) {
7676 // Otherwise, we must have three elements from one vector, call it X, and
7677 // one element from the other, call it Y. First, use a shufps to build an
7678 // intermediate vector with the one element from Y and the element from X
7679 // that will be in the same half in the final destination (the indexes don't
7680 // matter). Then, use a shufps to build the final vector, taking the half
7681 // containing the element from Y from the intermediate, and the other half
7684 // Normalize it so the 3 elements come from V1.
7685 CommuteVectorShuffleMask(PermMask, 4);
7689 // Find the element from V2.
7691 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7692 int Val = PermMask[HiIndex];
7699 Mask1[0] = PermMask[HiIndex];
7701 Mask1[2] = PermMask[HiIndex^1];
7703 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7706 Mask1[0] = PermMask[0];
7707 Mask1[1] = PermMask[1];
7708 Mask1[2] = HiIndex & 1 ? 6 : 4;
7709 Mask1[3] = HiIndex & 1 ? 4 : 6;
7710 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7713 Mask1[0] = HiIndex & 1 ? 2 : 0;
7714 Mask1[1] = HiIndex & 1 ? 0 : 2;
7715 Mask1[2] = PermMask[2];
7716 Mask1[3] = PermMask[3];
7721 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7724 // Break it into (shuffle shuffle_hi, shuffle_lo).
7725 int LoMask[] = { -1, -1, -1, -1 };
7726 int HiMask[] = { -1, -1, -1, -1 };
7728 int *MaskPtr = LoMask;
7729 unsigned MaskIdx = 0;
7732 for (unsigned i = 0; i != 4; ++i) {
7739 int Idx = PermMask[i];
7741 Locs[i] = std::make_pair(-1, -1);
7742 } else if (Idx < 4) {
7743 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7744 MaskPtr[LoIdx] = Idx;
7747 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7748 MaskPtr[HiIdx] = Idx;
7753 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7754 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7755 int MaskOps[] = { -1, -1, -1, -1 };
7756 for (unsigned i = 0; i != 4; ++i)
7757 if (Locs[i].first != -1)
7758 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7759 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7762 static bool MayFoldVectorLoad(SDValue V) {
7763 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7764 V = V.getOperand(0);
7766 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7767 V = V.getOperand(0);
7768 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7769 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7770 // BUILD_VECTOR (load), undef
7771 V = V.getOperand(0);
7773 return MayFoldLoad(V);
7777 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7778 MVT VT = Op.getSimpleValueType();
7780 // Canonizalize to v2f64.
7781 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7782 return DAG.getNode(ISD::BITCAST, dl, VT,
7783 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7788 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7790 SDValue V1 = Op.getOperand(0);
7791 SDValue V2 = Op.getOperand(1);
7792 MVT VT = Op.getSimpleValueType();
7794 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7796 if (HasSSE2 && VT == MVT::v2f64)
7797 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7799 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7800 return DAG.getNode(ISD::BITCAST, dl, VT,
7801 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7802 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7803 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7807 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7808 SDValue V1 = Op.getOperand(0);
7809 SDValue V2 = Op.getOperand(1);
7810 MVT VT = Op.getSimpleValueType();
7812 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7813 "unsupported shuffle type");
7815 if (V2.getOpcode() == ISD::UNDEF)
7819 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7823 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7824 SDValue V1 = Op.getOperand(0);
7825 SDValue V2 = Op.getOperand(1);
7826 MVT VT = Op.getSimpleValueType();
7827 unsigned NumElems = VT.getVectorNumElements();
7829 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7830 // operand of these instructions is only memory, so check if there's a
7831 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7833 bool CanFoldLoad = false;
7835 // Trivial case, when V2 comes from a load.
7836 if (MayFoldVectorLoad(V2))
7839 // When V1 is a load, it can be folded later into a store in isel, example:
7840 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7842 // (MOVLPSmr addr:$src1, VR128:$src2)
7843 // So, recognize this potential and also use MOVLPS or MOVLPD
7844 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7847 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7849 if (HasSSE2 && NumElems == 2)
7850 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7853 // If we don't care about the second element, proceed to use movss.
7854 if (SVOp->getMaskElt(1) != -1)
7855 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7858 // movl and movlp will both match v2i64, but v2i64 is never matched by
7859 // movl earlier because we make it strict to avoid messing with the movlp load
7860 // folding logic (see the code above getMOVLP call). Match it here then,
7861 // this is horrible, but will stay like this until we move all shuffle
7862 // matching to x86 specific nodes. Note that for the 1st condition all
7863 // types are matched with movsd.
7865 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7866 // as to remove this logic from here, as much as possible
7867 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7868 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7869 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7872 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7874 // Invert the operand order and use SHUFPS to match it.
7875 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7876 getShuffleSHUFImmediate(SVOp), DAG);
7879 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7880 SelectionDAG &DAG) {
7882 MVT VT = Load->getSimpleValueType(0);
7883 MVT EVT = VT.getVectorElementType();
7884 SDValue Addr = Load->getOperand(1);
7885 SDValue NewAddr = DAG.getNode(
7886 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7887 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7890 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7891 DAG.getMachineFunction().getMachineMemOperand(
7892 Load->getMemOperand(), 0, EVT.getStoreSize()));
7896 // It is only safe to call this function if isINSERTPSMask is true for
7897 // this shufflevector mask.
7898 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7899 SelectionDAG &DAG) {
7900 // Generate an insertps instruction when inserting an f32 from memory onto a
7901 // v4f32 or when copying a member from one v4f32 to another.
7902 // We also use it for transferring i32 from one register to another,
7903 // since it simply copies the same bits.
7904 // If we're transferring an i32 from memory to a specific element in a
7905 // register, we output a generic DAG that will match the PINSRD
7907 MVT VT = SVOp->getSimpleValueType(0);
7908 MVT EVT = VT.getVectorElementType();
7909 SDValue V1 = SVOp->getOperand(0);
7910 SDValue V2 = SVOp->getOperand(1);
7911 auto Mask = SVOp->getMask();
7912 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7913 "unsupported vector type for insertps/pinsrd");
7915 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7916 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7917 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7925 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7928 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7929 "More than one element from V1 and from V2, or no elements from one "
7930 "of the vectors. This case should not have returned true from "
7935 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7938 unsigned SrcIndex = Mask[DestIndex] % 4;
7939 if (MayFoldLoad(From)) {
7940 // Trivial case, when From comes from a load and is only used by the
7941 // shuffle. Make it use insertps from the vector that we need from that
7944 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
7945 if (!NewLoad.getNode())
7948 if (EVT == MVT::f32) {
7949 // Create this as a scalar to vector to match the instruction pattern.
7950 SDValue LoadScalarToVector =
7951 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7952 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7953 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7955 } else { // EVT == MVT::i32
7956 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7957 // instruction, to match the PINSRD instruction, which loads an i32 to a
7958 // certain vector element.
7959 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7960 DAG.getConstant(DestIndex, MVT::i32));
7964 // Vector-element-to-vector
7965 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7966 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7969 // Reduce a vector shuffle to zext.
7970 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7971 SelectionDAG &DAG) {
7972 // PMOVZX is only available from SSE41.
7973 if (!Subtarget->hasSSE41())
7976 MVT VT = Op.getSimpleValueType();
7978 // Only AVX2 support 256-bit vector integer extending.
7979 if (!Subtarget->hasInt256() && VT.is256BitVector())
7982 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7984 SDValue V1 = Op.getOperand(0);
7985 SDValue V2 = Op.getOperand(1);
7986 unsigned NumElems = VT.getVectorNumElements();
7988 // Extending is an unary operation and the element type of the source vector
7989 // won't be equal to or larger than i64.
7990 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7991 VT.getVectorElementType() == MVT::i64)
7994 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7995 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7996 while ((1U << Shift) < NumElems) {
7997 if (SVOp->getMaskElt(1U << Shift) == 1)
8000 // The maximal ratio is 8, i.e. from i8 to i64.
8005 // Check the shuffle mask.
8006 unsigned Mask = (1U << Shift) - 1;
8007 for (unsigned i = 0; i != NumElems; ++i) {
8008 int EltIdx = SVOp->getMaskElt(i);
8009 if ((i & Mask) != 0 && EltIdx != -1)
8011 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
8015 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
8016 MVT NeVT = MVT::getIntegerVT(NBits);
8017 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
8019 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
8022 // Simplify the operand as it's prepared to be fed into shuffle.
8023 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
8024 if (V1.getOpcode() == ISD::BITCAST &&
8025 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
8026 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8027 V1.getOperand(0).getOperand(0)
8028 .getSimpleValueType().getSizeInBits() == SignificantBits) {
8029 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
8030 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
8031 ConstantSDNode *CIdx =
8032 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
8033 // If it's foldable, i.e. normal load with single use, we will let code
8034 // selection to fold it. Otherwise, we will short the conversion sequence.
8035 if (CIdx && CIdx->getZExtValue() == 0 &&
8036 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
8037 MVT FullVT = V.getSimpleValueType();
8038 MVT V1VT = V1.getSimpleValueType();
8039 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
8040 // The "ext_vec_elt" node is wider than the result node.
8041 // In this case we should extract subvector from V.
8042 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
8043 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
8044 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
8045 FullVT.getVectorNumElements()/Ratio);
8046 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
8047 DAG.getIntPtrConstant(0));
8049 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
8053 return DAG.getNode(ISD::BITCAST, DL, VT,
8054 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
8057 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8058 SelectionDAG &DAG) {
8059 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8060 MVT VT = Op.getSimpleValueType();
8062 SDValue V1 = Op.getOperand(0);
8063 SDValue V2 = Op.getOperand(1);
8065 if (isZeroShuffle(SVOp))
8066 return getZeroVector(VT, Subtarget, DAG, dl);
8068 // Handle splat operations
8069 if (SVOp->isSplat()) {
8070 // Use vbroadcast whenever the splat comes from a foldable load
8071 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
8072 if (Broadcast.getNode())
8076 // Check integer expanding shuffles.
8077 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
8078 if (NewOp.getNode())
8081 // If the shuffle can be profitably rewritten as a narrower shuffle, then
8083 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
8085 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
8086 if (NewOp.getNode())
8087 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
8088 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
8089 // FIXME: Figure out a cleaner way to do this.
8090 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
8091 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
8092 if (NewOp.getNode()) {
8093 MVT NewVT = NewOp.getSimpleValueType();
8094 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
8095 NewVT, true, false))
8096 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
8099 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
8100 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
8101 if (NewOp.getNode()) {
8102 MVT NewVT = NewOp.getSimpleValueType();
8103 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
8104 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
8113 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
8114 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8115 SDValue V1 = Op.getOperand(0);
8116 SDValue V2 = Op.getOperand(1);
8117 MVT VT = Op.getSimpleValueType();
8119 unsigned NumElems = VT.getVectorNumElements();
8120 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8121 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8122 bool V1IsSplat = false;
8123 bool V2IsSplat = false;
8124 bool HasSSE2 = Subtarget->hasSSE2();
8125 bool HasFp256 = Subtarget->hasFp256();
8126 bool HasInt256 = Subtarget->hasInt256();
8127 MachineFunction &MF = DAG.getMachineFunction();
8128 bool OptForSize = MF.getFunction()->getAttributes().
8129 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
8131 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8133 if (V1IsUndef && V2IsUndef)
8134 return DAG.getUNDEF(VT);
8136 // When we create a shuffle node we put the UNDEF node to second operand,
8137 // but in some cases the first operand may be transformed to UNDEF.
8138 // In this case we should just commute the node.
8140 return CommuteVectorShuffle(SVOp, DAG);
8142 // Vector shuffle lowering takes 3 steps:
8144 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
8145 // narrowing and commutation of operands should be handled.
8146 // 2) Matching of shuffles with known shuffle masks to x86 target specific
8148 // 3) Rewriting of unmatched masks into new generic shuffle operations,
8149 // so the shuffle can be broken into other shuffles and the legalizer can
8150 // try the lowering again.
8152 // The general idea is that no vector_shuffle operation should be left to
8153 // be matched during isel, all of them must be converted to a target specific
8156 // Normalize the input vectors. Here splats, zeroed vectors, profitable
8157 // narrowing and commutation of operands should be handled. The actual code
8158 // doesn't include all of those, work in progress...
8159 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
8160 if (NewOp.getNode())
8163 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
8165 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
8166 // unpckh_undef). Only use pshufd if speed is more important than size.
8167 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8168 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8169 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8170 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8172 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
8173 V2IsUndef && MayFoldVectorLoad(V1))
8174 return getMOVDDup(Op, dl, V1, DAG);
8176 if (isMOVHLPS_v_undef_Mask(M, VT))
8177 return getMOVHighToLow(Op, dl, DAG);
8179 // Use to match splats
8180 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
8181 (VT == MVT::v2f64 || VT == MVT::v2i64))
8182 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8184 if (isPSHUFDMask(M, VT)) {
8185 // The actual implementation will match the mask in the if above and then
8186 // during isel it can match several different instructions, not only pshufd
8187 // as its name says, sad but true, emulate the behavior for now...
8188 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
8189 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
8191 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
8193 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
8194 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
8196 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
8197 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
8200 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
8204 if (isPALIGNRMask(M, VT, Subtarget))
8205 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
8206 getShufflePALIGNRImmediate(SVOp),
8209 // Check if this can be converted into a logical shift.
8210 bool isLeft = false;
8213 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
8214 if (isShift && ShVal.hasOneUse()) {
8215 // If the shifted value has multiple uses, it may be cheaper to use
8216 // v_set0 + movlhps or movhlps, etc.
8217 MVT EltVT = VT.getVectorElementType();
8218 ShAmt *= EltVT.getSizeInBits();
8219 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8222 if (isMOVLMask(M, VT)) {
8223 if (ISD::isBuildVectorAllZeros(V1.getNode()))
8224 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
8225 if (!isMOVLPMask(M, VT)) {
8226 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
8227 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8229 if (VT == MVT::v4i32 || VT == MVT::v4f32)
8230 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8234 // FIXME: fold these into legal mask.
8235 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
8236 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
8238 if (isMOVHLPSMask(M, VT))
8239 return getMOVHighToLow(Op, dl, DAG);
8241 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
8242 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
8244 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
8245 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
8247 if (isMOVLPMask(M, VT))
8248 return getMOVLP(Op, dl, DAG, HasSSE2);
8250 if (ShouldXformToMOVHLPS(M, VT) ||
8251 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
8252 return CommuteVectorShuffle(SVOp, DAG);
8255 // No better options. Use a vshldq / vsrldq.
8256 MVT EltVT = VT.getVectorElementType();
8257 ShAmt *= EltVT.getSizeInBits();
8258 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8261 bool Commuted = false;
8262 // FIXME: This should also accept a bitcast of a splat? Be careful, not
8263 // 1,1,1,1 -> v8i16 though.
8264 V1IsSplat = isSplatVector(V1.getNode());
8265 V2IsSplat = isSplatVector(V2.getNode());
8267 // Canonicalize the splat or undef, if present, to be on the RHS.
8268 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
8269 CommuteVectorShuffleMask(M, NumElems);
8271 std::swap(V1IsSplat, V2IsSplat);
8275 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
8276 // Shuffling low element of v1 into undef, just return v1.
8279 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
8280 // the instruction selector will not match, so get a canonical MOVL with
8281 // swapped operands to undo the commute.
8282 return getMOVL(DAG, dl, VT, V2, V1);
8285 if (isUNPCKLMask(M, VT, HasInt256))
8286 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8288 if (isUNPCKHMask(M, VT, HasInt256))
8289 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8292 // Normalize mask so all entries that point to V2 points to its first
8293 // element then try to match unpck{h|l} again. If match, return a
8294 // new vector_shuffle with the corrected mask.p
8295 SmallVector<int, 8> NewMask(M.begin(), M.end());
8296 NormalizeMask(NewMask, NumElems);
8297 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
8298 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8299 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
8300 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8304 // Commute is back and try unpck* again.
8305 // FIXME: this seems wrong.
8306 CommuteVectorShuffleMask(M, NumElems);
8308 std::swap(V1IsSplat, V2IsSplat);
8310 if (isUNPCKLMask(M, VT, HasInt256))
8311 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8313 if (isUNPCKHMask(M, VT, HasInt256))
8314 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8317 // Normalize the node to match x86 shuffle ops if needed
8318 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
8319 return CommuteVectorShuffle(SVOp, DAG);
8321 // The checks below are all present in isShuffleMaskLegal, but they are
8322 // inlined here right now to enable us to directly emit target specific
8323 // nodes, and remove one by one until they don't return Op anymore.
8325 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
8326 SVOp->getSplatIndex() == 0 && V2IsUndef) {
8327 if (VT == MVT::v2f64 || VT == MVT::v2i64)
8328 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8331 if (isPSHUFHWMask(M, VT, HasInt256))
8332 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8333 getShufflePSHUFHWImmediate(SVOp),
8336 if (isPSHUFLWMask(M, VT, HasInt256))
8337 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8338 getShufflePSHUFLWImmediate(SVOp),
8341 if (isSHUFPMask(M, VT))
8342 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8343 getShuffleSHUFImmediate(SVOp), DAG);
8345 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8346 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8347 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8348 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8350 //===--------------------------------------------------------------------===//
8351 // Generate target specific nodes for 128 or 256-bit shuffles only
8352 // supported in the AVX instruction set.
8355 // Handle VMOVDDUPY permutations
8356 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8357 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8359 // Handle VPERMILPS/D* permutations
8360 if (isVPERMILPMask(M, VT)) {
8361 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8362 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8363 getShuffleSHUFImmediate(SVOp), DAG);
8364 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8365 getShuffleSHUFImmediate(SVOp), DAG);
8369 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8370 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8371 Idx*(NumElems/2), DAG, dl);
8373 // Handle VPERM2F128/VPERM2I128 permutations
8374 if (isVPERM2X128Mask(M, VT, HasFp256))
8375 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8376 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8379 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8381 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8383 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8384 return getINSERTPS(SVOp, dl, DAG);
8387 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8388 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8390 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8391 VT.is512BitVector()) {
8392 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8393 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8394 SmallVector<SDValue, 16> permclMask;
8395 for (unsigned i = 0; i != NumElems; ++i) {
8396 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8399 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8401 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8402 return DAG.getNode(X86ISD::VPERMV, dl, VT,
8403 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8404 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8405 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8408 //===--------------------------------------------------------------------===//
8409 // Since no target specific shuffle was selected for this generic one,
8410 // lower it into other known shuffles. FIXME: this isn't true yet, but
8411 // this is the plan.
8414 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8415 if (VT == MVT::v8i16) {
8416 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8417 if (NewOp.getNode())
8421 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8422 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8423 if (NewOp.getNode())
8427 if (VT == MVT::v16i8) {
8428 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8429 if (NewOp.getNode())
8433 if (VT == MVT::v32i8) {
8434 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8435 if (NewOp.getNode())
8439 // Handle all 128-bit wide vectors with 4 elements, and match them with
8440 // several different shuffle types.
8441 if (NumElems == 4 && VT.is128BitVector())
8442 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8444 // Handle general 256-bit shuffles
8445 if (VT.is256BitVector())
8446 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8451 // This function assumes its argument is a BUILD_VECTOR of constants or
8452 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8454 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8455 unsigned &MaskValue) {
8457 unsigned NumElems = BuildVector->getNumOperands();
8458 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8459 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8460 unsigned NumElemsInLane = NumElems / NumLanes;
8462 // Blend for v16i16 should be symetric for the both lanes.
8463 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8464 SDValue EltCond = BuildVector->getOperand(i);
8465 SDValue SndLaneEltCond =
8466 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8468 int Lane1Cond = -1, Lane2Cond = -1;
8469 if (isa<ConstantSDNode>(EltCond))
8470 Lane1Cond = !isZero(EltCond);
8471 if (isa<ConstantSDNode>(SndLaneEltCond))
8472 Lane2Cond = !isZero(SndLaneEltCond);
8474 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8475 // Lane1Cond != 0, means we want the first argument.
8476 // Lane1Cond == 0, means we want the second argument.
8477 // The encoding of this argument is 0 for the first argument, 1
8478 // for the second. Therefore, invert the condition.
8479 MaskValue |= !Lane1Cond << i;
8480 else if (Lane1Cond < 0)
8481 MaskValue |= !Lane2Cond << i;
8488 // Try to lower a vselect node into a simple blend instruction.
8489 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8490 SelectionDAG &DAG) {
8491 SDValue Cond = Op.getOperand(0);
8492 SDValue LHS = Op.getOperand(1);
8493 SDValue RHS = Op.getOperand(2);
8495 MVT VT = Op.getSimpleValueType();
8496 MVT EltVT = VT.getVectorElementType();
8497 unsigned NumElems = VT.getVectorNumElements();
8499 // There is no blend with immediate in AVX-512.
8500 if (VT.is512BitVector())
8503 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8505 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8508 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8511 // Check the mask for BLEND and build the value.
8512 unsigned MaskValue = 0;
8513 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8516 // Convert i32 vectors to floating point if it is not AVX2.
8517 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8519 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8520 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8522 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8523 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8526 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8527 DAG.getConstant(MaskValue, MVT::i32));
8528 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8531 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8532 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8533 if (BlendOp.getNode())
8536 // Some types for vselect were previously set to Expand, not Legal or
8537 // Custom. Return an empty SDValue so we fall-through to Expand, after
8538 // the Custom lowering phase.
8539 MVT VT = Op.getSimpleValueType();
8540 switch (VT.SimpleTy) {
8548 // We couldn't create a "Blend with immediate" node.
8549 // This node should still be legal, but we'll have to emit a blendv*
8554 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8555 MVT VT = Op.getSimpleValueType();
8558 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8561 if (VT.getSizeInBits() == 8) {
8562 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8563 Op.getOperand(0), Op.getOperand(1));
8564 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8565 DAG.getValueType(VT));
8566 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8569 if (VT.getSizeInBits() == 16) {
8570 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8571 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8573 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8574 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8575 DAG.getNode(ISD::BITCAST, dl,
8579 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8580 Op.getOperand(0), Op.getOperand(1));
8581 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8582 DAG.getValueType(VT));
8583 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8586 if (VT == MVT::f32) {
8587 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8588 // the result back to FR32 register. It's only worth matching if the
8589 // result has a single use which is a store or a bitcast to i32. And in
8590 // the case of a store, it's not worth it if the index is a constant 0,
8591 // because a MOVSSmr can be used instead, which is smaller and faster.
8592 if (!Op.hasOneUse())
8594 SDNode *User = *Op.getNode()->use_begin();
8595 if ((User->getOpcode() != ISD::STORE ||
8596 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8597 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8598 (User->getOpcode() != ISD::BITCAST ||
8599 User->getValueType(0) != MVT::i32))
8601 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8602 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8605 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8608 if (VT == MVT::i32 || VT == MVT::i64) {
8609 // ExtractPS/pextrq works with constant index.
8610 if (isa<ConstantSDNode>(Op.getOperand(1)))
8616 /// Extract one bit from mask vector, like v16i1 or v8i1.
8617 /// AVX-512 feature.
8619 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8620 SDValue Vec = Op.getOperand(0);
8622 MVT VecVT = Vec.getSimpleValueType();
8623 SDValue Idx = Op.getOperand(1);
8624 MVT EltVT = Op.getSimpleValueType();
8626 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8628 // variable index can't be handled in mask registers,
8629 // extend vector to VR512
8630 if (!isa<ConstantSDNode>(Idx)) {
8631 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8632 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8633 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8634 ExtVT.getVectorElementType(), Ext, Idx);
8635 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8638 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8639 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8640 unsigned MaxSift = rc->getSize()*8 - 1;
8641 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8642 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8643 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8644 DAG.getConstant(MaxSift, MVT::i8));
8645 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8646 DAG.getIntPtrConstant(0));
8650 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8651 SelectionDAG &DAG) const {
8653 SDValue Vec = Op.getOperand(0);
8654 MVT VecVT = Vec.getSimpleValueType();
8655 SDValue Idx = Op.getOperand(1);
8657 if (Op.getSimpleValueType() == MVT::i1)
8658 return ExtractBitFromMaskVector(Op, DAG);
8660 if (!isa<ConstantSDNode>(Idx)) {
8661 if (VecVT.is512BitVector() ||
8662 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8663 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8666 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8667 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8668 MaskEltVT.getSizeInBits());
8670 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8671 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8672 getZeroVector(MaskVT, Subtarget, DAG, dl),
8673 Idx, DAG.getConstant(0, getPointerTy()));
8674 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8675 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8676 Perm, DAG.getConstant(0, getPointerTy()));
8681 // If this is a 256-bit vector result, first extract the 128-bit vector and
8682 // then extract the element from the 128-bit vector.
8683 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8685 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8686 // Get the 128-bit vector.
8687 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8688 MVT EltVT = VecVT.getVectorElementType();
8690 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8692 //if (IdxVal >= NumElems/2)
8693 // IdxVal -= NumElems/2;
8694 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8695 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8696 DAG.getConstant(IdxVal, MVT::i32));
8699 assert(VecVT.is128BitVector() && "Unexpected vector length");
8701 if (Subtarget->hasSSE41()) {
8702 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8707 MVT VT = Op.getSimpleValueType();
8708 // TODO: handle v16i8.
8709 if (VT.getSizeInBits() == 16) {
8710 SDValue Vec = Op.getOperand(0);
8711 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8713 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8714 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8715 DAG.getNode(ISD::BITCAST, dl,
8718 // Transform it so it match pextrw which produces a 32-bit result.
8719 MVT EltVT = MVT::i32;
8720 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8721 Op.getOperand(0), Op.getOperand(1));
8722 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8723 DAG.getValueType(VT));
8724 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8727 if (VT.getSizeInBits() == 32) {
8728 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8732 // SHUFPS the element to the lowest double word, then movss.
8733 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8734 MVT VVT = Op.getOperand(0).getSimpleValueType();
8735 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8736 DAG.getUNDEF(VVT), Mask);
8737 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8738 DAG.getIntPtrConstant(0));
8741 if (VT.getSizeInBits() == 64) {
8742 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8743 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8744 // to match extract_elt for f64.
8745 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8749 // UNPCKHPD the element to the lowest double word, then movsd.
8750 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8751 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8752 int Mask[2] = { 1, -1 };
8753 MVT VVT = Op.getOperand(0).getSimpleValueType();
8754 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8755 DAG.getUNDEF(VVT), Mask);
8756 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8757 DAG.getIntPtrConstant(0));
8763 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8764 MVT VT = Op.getSimpleValueType();
8765 MVT EltVT = VT.getVectorElementType();
8768 SDValue N0 = Op.getOperand(0);
8769 SDValue N1 = Op.getOperand(1);
8770 SDValue N2 = Op.getOperand(2);
8772 if (!VT.is128BitVector())
8775 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8776 isa<ConstantSDNode>(N2)) {
8778 if (VT == MVT::v8i16)
8779 Opc = X86ISD::PINSRW;
8780 else if (VT == MVT::v16i8)
8781 Opc = X86ISD::PINSRB;
8783 Opc = X86ISD::PINSRB;
8785 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8787 if (N1.getValueType() != MVT::i32)
8788 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8789 if (N2.getValueType() != MVT::i32)
8790 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8791 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8794 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8795 // Bits [7:6] of the constant are the source select. This will always be
8796 // zero here. The DAG Combiner may combine an extract_elt index into these
8797 // bits. For example (insert (extract, 3), 2) could be matched by putting
8798 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8799 // Bits [5:4] of the constant are the destination select. This is the
8800 // value of the incoming immediate.
8801 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8802 // combine either bitwise AND or insert of float 0.0 to set these bits.
8803 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8804 // Create this as a scalar to vector..
8805 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8806 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8809 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8810 // PINSR* works with constant index.
8816 /// Insert one bit to mask vector, like v16i1 or v8i1.
8817 /// AVX-512 feature.
8819 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8821 SDValue Vec = Op.getOperand(0);
8822 SDValue Elt = Op.getOperand(1);
8823 SDValue Idx = Op.getOperand(2);
8824 MVT VecVT = Vec.getSimpleValueType();
8826 if (!isa<ConstantSDNode>(Idx)) {
8827 // Non constant index. Extend source and destination,
8828 // insert element and then truncate the result.
8829 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8830 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8831 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8832 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8833 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8834 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8837 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8838 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8839 if (Vec.getOpcode() == ISD::UNDEF)
8840 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8841 DAG.getConstant(IdxVal, MVT::i8));
8842 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8843 unsigned MaxSift = rc->getSize()*8 - 1;
8844 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8845 DAG.getConstant(MaxSift, MVT::i8));
8846 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8847 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8848 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8851 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8852 MVT VT = Op.getSimpleValueType();
8853 MVT EltVT = VT.getVectorElementType();
8855 if (EltVT == MVT::i1)
8856 return InsertBitToMaskVector(Op, DAG);
8859 SDValue N0 = Op.getOperand(0);
8860 SDValue N1 = Op.getOperand(1);
8861 SDValue N2 = Op.getOperand(2);
8863 // If this is a 256-bit vector result, first extract the 128-bit vector,
8864 // insert the element into the extracted half and then place it back.
8865 if (VT.is256BitVector() || VT.is512BitVector()) {
8866 if (!isa<ConstantSDNode>(N2))
8869 // Get the desired 128-bit vector half.
8870 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8871 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8873 // Insert the element into the desired half.
8874 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8875 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8877 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8878 DAG.getConstant(IdxIn128, MVT::i32));
8880 // Insert the changed part back to the 256-bit vector
8881 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8884 if (Subtarget->hasSSE41())
8885 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8887 if (EltVT == MVT::i8)
8890 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8891 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8892 // as its second argument.
8893 if (N1.getValueType() != MVT::i32)
8894 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8895 if (N2.getValueType() != MVT::i32)
8896 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8897 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8902 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8904 MVT OpVT = Op.getSimpleValueType();
8906 // If this is a 256-bit vector result, first insert into a 128-bit
8907 // vector and then insert into the 256-bit vector.
8908 if (!OpVT.is128BitVector()) {
8909 // Insert into a 128-bit vector.
8910 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8911 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8912 OpVT.getVectorNumElements() / SizeFactor);
8914 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8916 // Insert the 128-bit vector.
8917 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8920 if (OpVT == MVT::v1i64 &&
8921 Op.getOperand(0).getValueType() == MVT::i64)
8922 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8924 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8925 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8926 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8927 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8930 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8931 // a simple subregister reference or explicit instructions to grab
8932 // upper bits of a vector.
8933 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8934 SelectionDAG &DAG) {
8936 SDValue In = Op.getOperand(0);
8937 SDValue Idx = Op.getOperand(1);
8938 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8939 MVT ResVT = Op.getSimpleValueType();
8940 MVT InVT = In.getSimpleValueType();
8942 if (Subtarget->hasFp256()) {
8943 if (ResVT.is128BitVector() &&
8944 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8945 isa<ConstantSDNode>(Idx)) {
8946 return Extract128BitVector(In, IdxVal, DAG, dl);
8948 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8949 isa<ConstantSDNode>(Idx)) {
8950 return Extract256BitVector(In, IdxVal, DAG, dl);
8956 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8957 // simple superregister reference or explicit instructions to insert
8958 // the upper bits of a vector.
8959 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8960 SelectionDAG &DAG) {
8961 if (Subtarget->hasFp256()) {
8962 SDLoc dl(Op.getNode());
8963 SDValue Vec = Op.getNode()->getOperand(0);
8964 SDValue SubVec = Op.getNode()->getOperand(1);
8965 SDValue Idx = Op.getNode()->getOperand(2);
8967 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8968 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8969 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8970 isa<ConstantSDNode>(Idx)) {
8971 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8972 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8975 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8976 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8977 isa<ConstantSDNode>(Idx)) {
8978 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8979 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8985 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8986 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8987 // one of the above mentioned nodes. It has to be wrapped because otherwise
8988 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8989 // be used to form addressing mode. These wrapped nodes will be selected
8992 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8993 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8995 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8997 unsigned char OpFlag = 0;
8998 unsigned WrapperKind = X86ISD::Wrapper;
8999 CodeModel::Model M = DAG.getTarget().getCodeModel();
9001 if (Subtarget->isPICStyleRIPRel() &&
9002 (M == CodeModel::Small || M == CodeModel::Kernel))
9003 WrapperKind = X86ISD::WrapperRIP;
9004 else if (Subtarget->isPICStyleGOT())
9005 OpFlag = X86II::MO_GOTOFF;
9006 else if (Subtarget->isPICStyleStubPIC())
9007 OpFlag = X86II::MO_PIC_BASE_OFFSET;
9009 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
9011 CP->getOffset(), OpFlag);
9013 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9014 // With PIC, the address is actually $g + Offset.
9016 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9017 DAG.getNode(X86ISD::GlobalBaseReg,
9018 SDLoc(), getPointerTy()),
9025 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
9026 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
9028 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9030 unsigned char OpFlag = 0;
9031 unsigned WrapperKind = X86ISD::Wrapper;
9032 CodeModel::Model M = DAG.getTarget().getCodeModel();
9034 if (Subtarget->isPICStyleRIPRel() &&
9035 (M == CodeModel::Small || M == CodeModel::Kernel))
9036 WrapperKind = X86ISD::WrapperRIP;
9037 else if (Subtarget->isPICStyleGOT())
9038 OpFlag = X86II::MO_GOTOFF;
9039 else if (Subtarget->isPICStyleStubPIC())
9040 OpFlag = X86II::MO_PIC_BASE_OFFSET;
9042 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
9045 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9047 // With PIC, the address is actually $g + Offset.
9049 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9050 DAG.getNode(X86ISD::GlobalBaseReg,
9051 SDLoc(), getPointerTy()),
9058 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
9059 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9061 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9063 unsigned char OpFlag = 0;
9064 unsigned WrapperKind = X86ISD::Wrapper;
9065 CodeModel::Model M = DAG.getTarget().getCodeModel();
9067 if (Subtarget->isPICStyleRIPRel() &&
9068 (M == CodeModel::Small || M == CodeModel::Kernel)) {
9069 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
9070 OpFlag = X86II::MO_GOTPCREL;
9071 WrapperKind = X86ISD::WrapperRIP;
9072 } else if (Subtarget->isPICStyleGOT()) {
9073 OpFlag = X86II::MO_GOT;
9074 } else if (Subtarget->isPICStyleStubPIC()) {
9075 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
9076 } else if (Subtarget->isPICStyleStubNoDynamic()) {
9077 OpFlag = X86II::MO_DARWIN_NONLAZY;
9080 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
9083 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9085 // With PIC, the address is actually $g + Offset.
9086 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
9087 !Subtarget->is64Bit()) {
9088 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9089 DAG.getNode(X86ISD::GlobalBaseReg,
9090 SDLoc(), getPointerTy()),
9094 // For symbols that require a load from a stub to get the address, emit the
9096 if (isGlobalStubReference(OpFlag))
9097 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
9098 MachinePointerInfo::getGOT(), false, false, false, 0);
9104 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
9105 // Create the TargetBlockAddressAddress node.
9106 unsigned char OpFlags =
9107 Subtarget->ClassifyBlockAddressReference();
9108 CodeModel::Model M = DAG.getTarget().getCodeModel();
9109 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
9110 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
9112 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
9115 if (Subtarget->isPICStyleRIPRel() &&
9116 (M == CodeModel::Small || M == CodeModel::Kernel))
9117 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
9119 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
9121 // With PIC, the address is actually $g + Offset.
9122 if (isGlobalRelativeToPICBase(OpFlags)) {
9123 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
9124 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9132 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
9133 int64_t Offset, SelectionDAG &DAG) const {
9134 // Create the TargetGlobalAddress node, folding in the constant
9135 // offset if it is legal.
9136 unsigned char OpFlags =
9137 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
9138 CodeModel::Model M = DAG.getTarget().getCodeModel();
9140 if (OpFlags == X86II::MO_NO_FLAG &&
9141 X86::isOffsetSuitableForCodeModel(Offset, M)) {
9142 // A direct static reference to a global.
9143 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
9146 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
9149 if (Subtarget->isPICStyleRIPRel() &&
9150 (M == CodeModel::Small || M == CodeModel::Kernel))
9151 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
9153 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
9155 // With PIC, the address is actually $g + Offset.
9156 if (isGlobalRelativeToPICBase(OpFlags)) {
9157 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
9158 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9162 // For globals that require a load from a stub to get the address, emit the
9164 if (isGlobalStubReference(OpFlags))
9165 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
9166 MachinePointerInfo::getGOT(), false, false, false, 0);
9168 // If there was a non-zero offset that we didn't fold, create an explicit
9171 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
9172 DAG.getConstant(Offset, getPointerTy()));
9178 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
9179 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
9180 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
9181 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
9185 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
9186 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
9187 unsigned char OperandFlags, bool LocalDynamic = false) {
9188 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9189 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9191 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9192 GA->getValueType(0),
9196 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
9200 SDValue Ops[] = { Chain, TGA, *InFlag };
9201 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9203 SDValue Ops[] = { Chain, TGA };
9204 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9207 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
9208 MFI->setAdjustsStack(true);
9210 SDValue Flag = Chain.getValue(1);
9211 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
9214 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
9216 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9219 SDLoc dl(GA); // ? function entry point might be better
9220 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9221 DAG.getNode(X86ISD::GlobalBaseReg,
9222 SDLoc(), PtrVT), InFlag);
9223 InFlag = Chain.getValue(1);
9225 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
9228 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
9230 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9232 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
9233 X86::RAX, X86II::MO_TLSGD);
9236 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
9242 // Get the start address of the TLS block for this module.
9243 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
9244 .getInfo<X86MachineFunctionInfo>();
9245 MFI->incNumLocalDynamicTLSAccesses();
9249 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
9250 X86II::MO_TLSLD, /*LocalDynamic=*/true);
9253 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9254 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
9255 InFlag = Chain.getValue(1);
9256 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
9257 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
9260 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
9264 unsigned char OperandFlags = X86II::MO_DTPOFF;
9265 unsigned WrapperKind = X86ISD::Wrapper;
9266 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9267 GA->getValueType(0),
9268 GA->getOffset(), OperandFlags);
9269 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9271 // Add x@dtpoff with the base.
9272 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
9275 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
9276 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9277 const EVT PtrVT, TLSModel::Model model,
9278 bool is64Bit, bool isPIC) {
9281 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
9282 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
9283 is64Bit ? 257 : 256));
9285 SDValue ThreadPointer =
9286 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
9287 MachinePointerInfo(Ptr), false, false, false, 0);
9289 unsigned char OperandFlags = 0;
9290 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
9292 unsigned WrapperKind = X86ISD::Wrapper;
9293 if (model == TLSModel::LocalExec) {
9294 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
9295 } else if (model == TLSModel::InitialExec) {
9297 OperandFlags = X86II::MO_GOTTPOFF;
9298 WrapperKind = X86ISD::WrapperRIP;
9300 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
9303 llvm_unreachable("Unexpected model");
9306 // emit "addl x@ntpoff,%eax" (local exec)
9307 // or "addl x@indntpoff,%eax" (initial exec)
9308 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
9310 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
9311 GA->getOffset(), OperandFlags);
9312 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9314 if (model == TLSModel::InitialExec) {
9315 if (isPIC && !is64Bit) {
9316 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
9317 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
9321 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
9322 MachinePointerInfo::getGOT(), false, false, false, 0);
9325 // The address of the thread local variable is the add of the thread
9326 // pointer with the offset of the variable.
9327 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9331 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9333 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9334 const GlobalValue *GV = GA->getGlobal();
9336 if (Subtarget->isTargetELF()) {
9337 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9340 case TLSModel::GeneralDynamic:
9341 if (Subtarget->is64Bit())
9342 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9343 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9344 case TLSModel::LocalDynamic:
9345 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9346 Subtarget->is64Bit());
9347 case TLSModel::InitialExec:
9348 case TLSModel::LocalExec:
9349 return LowerToTLSExecModel(
9350 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9351 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9353 llvm_unreachable("Unknown TLS model.");
9356 if (Subtarget->isTargetDarwin()) {
9357 // Darwin only has one model of TLS. Lower to that.
9358 unsigned char OpFlag = 0;
9359 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9360 X86ISD::WrapperRIP : X86ISD::Wrapper;
9362 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9364 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9365 !Subtarget->is64Bit();
9367 OpFlag = X86II::MO_TLVP_PIC_BASE;
9369 OpFlag = X86II::MO_TLVP;
9371 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9372 GA->getValueType(0),
9373 GA->getOffset(), OpFlag);
9374 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9376 // With PIC32, the address is actually $g + Offset.
9378 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9379 DAG.getNode(X86ISD::GlobalBaseReg,
9380 SDLoc(), getPointerTy()),
9383 // Lowering the machine isd will make sure everything is in the right
9385 SDValue Chain = DAG.getEntryNode();
9386 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9387 SDValue Args[] = { Chain, Offset };
9388 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9390 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9391 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9392 MFI->setAdjustsStack(true);
9394 // And our return value (tls address) is in the standard call return value
9396 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9397 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9401 if (Subtarget->isTargetKnownWindowsMSVC() ||
9402 Subtarget->isTargetWindowsGNU()) {
9403 // Just use the implicit TLS architecture
9404 // Need to generate someting similar to:
9405 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9407 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
9408 // mov rcx, qword [rdx+rcx*8]
9409 // mov eax, .tls$:tlsvar
9410 // [rax+rcx] contains the address
9411 // Windows 64bit: gs:0x58
9412 // Windows 32bit: fs:__tls_array
9415 SDValue Chain = DAG.getEntryNode();
9417 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9418 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9419 // use its literal value of 0x2C.
9420 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9421 ? Type::getInt8PtrTy(*DAG.getContext(),
9423 : Type::getInt32PtrTy(*DAG.getContext(),
9427 Subtarget->is64Bit()
9428 ? DAG.getIntPtrConstant(0x58)
9429 : (Subtarget->isTargetWindowsGNU()
9430 ? DAG.getIntPtrConstant(0x2C)
9431 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9433 SDValue ThreadPointer =
9434 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9435 MachinePointerInfo(Ptr), false, false, false, 0);
9437 // Load the _tls_index variable
9438 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9439 if (Subtarget->is64Bit())
9440 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9441 IDX, MachinePointerInfo(), MVT::i32,
9444 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9445 false, false, false, 0);
9447 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9449 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9451 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9452 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9453 false, false, false, 0);
9455 // Get the offset of start of .tls section
9456 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9457 GA->getValueType(0),
9458 GA->getOffset(), X86II::MO_SECREL);
9459 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9461 // The address of the thread local variable is the add of the thread
9462 // pointer with the offset of the variable.
9463 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9466 llvm_unreachable("TLS not implemented for this target.");
9469 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9470 /// and take a 2 x i32 value to shift plus a shift amount.
9471 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9472 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9473 MVT VT = Op.getSimpleValueType();
9474 unsigned VTBits = VT.getSizeInBits();
9476 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9477 SDValue ShOpLo = Op.getOperand(0);
9478 SDValue ShOpHi = Op.getOperand(1);
9479 SDValue ShAmt = Op.getOperand(2);
9480 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9481 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9483 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9484 DAG.getConstant(VTBits - 1, MVT::i8));
9485 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9486 DAG.getConstant(VTBits - 1, MVT::i8))
9487 : DAG.getConstant(0, VT);
9490 if (Op.getOpcode() == ISD::SHL_PARTS) {
9491 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9492 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9494 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9495 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9498 // If the shift amount is larger or equal than the width of a part we can't
9499 // rely on the results of shld/shrd. Insert a test and select the appropriate
9500 // values for large shift amounts.
9501 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9502 DAG.getConstant(VTBits, MVT::i8));
9503 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9504 AndNode, DAG.getConstant(0, MVT::i8));
9507 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9508 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9509 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9511 if (Op.getOpcode() == ISD::SHL_PARTS) {
9512 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9513 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9515 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9516 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9519 SDValue Ops[2] = { Lo, Hi };
9520 return DAG.getMergeValues(Ops, dl);
9523 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9524 SelectionDAG &DAG) const {
9525 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9527 if (SrcVT.isVector())
9530 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9531 "Unknown SINT_TO_FP to lower!");
9533 // These are really Legal; return the operand so the caller accepts it as
9535 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9537 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9538 Subtarget->is64Bit()) {
9543 unsigned Size = SrcVT.getSizeInBits()/8;
9544 MachineFunction &MF = DAG.getMachineFunction();
9545 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9546 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9547 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9549 MachinePointerInfo::getFixedStack(SSFI),
9551 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9554 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9556 SelectionDAG &DAG) const {
9560 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9562 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9564 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9566 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9568 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9569 MachineMemOperand *MMO;
9571 int SSFI = FI->getIndex();
9573 DAG.getMachineFunction()
9574 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9575 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9577 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9578 StackSlot = StackSlot.getOperand(1);
9580 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9581 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9583 Tys, Ops, SrcVT, MMO);
9586 Chain = Result.getValue(1);
9587 SDValue InFlag = Result.getValue(2);
9589 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9590 // shouldn't be necessary except that RFP cannot be live across
9591 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9592 MachineFunction &MF = DAG.getMachineFunction();
9593 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9594 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9595 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9596 Tys = DAG.getVTList(MVT::Other);
9598 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9600 MachineMemOperand *MMO =
9601 DAG.getMachineFunction()
9602 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9603 MachineMemOperand::MOStore, SSFISize, SSFISize);
9605 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9606 Ops, Op.getValueType(), MMO);
9607 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9608 MachinePointerInfo::getFixedStack(SSFI),
9609 false, false, false, 0);
9615 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9616 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9617 SelectionDAG &DAG) const {
9618 // This algorithm is not obvious. Here it is what we're trying to output:
9621 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9622 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9626 pshufd $0x4e, %xmm0, %xmm1
9632 LLVMContext *Context = DAG.getContext();
9634 // Build some magic constants.
9635 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9636 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9637 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9639 SmallVector<Constant*,2> CV1;
9641 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9642 APInt(64, 0x4330000000000000ULL))));
9644 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9645 APInt(64, 0x4530000000000000ULL))));
9646 Constant *C1 = ConstantVector::get(CV1);
9647 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9649 // Load the 64-bit value into an XMM register.
9650 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9652 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9653 MachinePointerInfo::getConstantPool(),
9654 false, false, false, 16);
9655 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9656 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9659 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9660 MachinePointerInfo::getConstantPool(),
9661 false, false, false, 16);
9662 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9663 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9666 if (Subtarget->hasSSE3()) {
9667 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9668 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9670 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9671 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9673 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9674 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9678 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9679 DAG.getIntPtrConstant(0));
9682 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9683 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9684 SelectionDAG &DAG) const {
9686 // FP constant to bias correct the final result.
9687 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9690 // Load the 32-bit value into an XMM register.
9691 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9694 // Zero out the upper parts of the register.
9695 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9697 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9698 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9699 DAG.getIntPtrConstant(0));
9701 // Or the load with the bias.
9702 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9703 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9704 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9706 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9707 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9708 MVT::v2f64, Bias)));
9709 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9710 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9711 DAG.getIntPtrConstant(0));
9713 // Subtract the bias.
9714 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9716 // Handle final rounding.
9717 EVT DestVT = Op.getValueType();
9719 if (DestVT.bitsLT(MVT::f64))
9720 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9721 DAG.getIntPtrConstant(0));
9722 if (DestVT.bitsGT(MVT::f64))
9723 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9725 // Handle final rounding.
9729 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9730 SelectionDAG &DAG) const {
9731 SDValue N0 = Op.getOperand(0);
9732 MVT SVT = N0.getSimpleValueType();
9735 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9736 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9737 "Custom UINT_TO_FP is not supported!");
9739 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9740 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9741 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9744 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9745 SelectionDAG &DAG) const {
9746 SDValue N0 = Op.getOperand(0);
9749 if (Op.getValueType().isVector())
9750 return lowerUINT_TO_FP_vec(Op, DAG);
9752 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9753 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9754 // the optimization here.
9755 if (DAG.SignBitIsZero(N0))
9756 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9758 MVT SrcVT = N0.getSimpleValueType();
9759 MVT DstVT = Op.getSimpleValueType();
9760 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9761 return LowerUINT_TO_FP_i64(Op, DAG);
9762 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9763 return LowerUINT_TO_FP_i32(Op, DAG);
9764 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9767 // Make a 64-bit buffer, and use it to build an FILD.
9768 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9769 if (SrcVT == MVT::i32) {
9770 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9771 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9772 getPointerTy(), StackSlot, WordOff);
9773 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9774 StackSlot, MachinePointerInfo(),
9776 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9777 OffsetSlot, MachinePointerInfo(),
9779 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9783 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9784 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9785 StackSlot, MachinePointerInfo(),
9787 // For i64 source, we need to add the appropriate power of 2 if the input
9788 // was negative. This is the same as the optimization in
9789 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9790 // we must be careful to do the computation in x87 extended precision, not
9791 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9792 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9793 MachineMemOperand *MMO =
9794 DAG.getMachineFunction()
9795 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9796 MachineMemOperand::MOLoad, 8, 8);
9798 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9799 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9800 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9803 APInt FF(32, 0x5F800000ULL);
9805 // Check whether the sign bit is set.
9806 SDValue SignSet = DAG.getSetCC(dl,
9807 getSetCCResultType(*DAG.getContext(), MVT::i64),
9808 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9811 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9812 SDValue FudgePtr = DAG.getConstantPool(
9813 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9816 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9817 SDValue Zero = DAG.getIntPtrConstant(0);
9818 SDValue Four = DAG.getIntPtrConstant(4);
9819 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9821 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9823 // Load the value out, extending it from f32 to f80.
9824 // FIXME: Avoid the extend by constructing the right constant pool?
9825 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9826 FudgePtr, MachinePointerInfo::getConstantPool(),
9827 MVT::f32, false, false, 4);
9828 // Extend everything to 80 bits to force it to be done on x87.
9829 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9830 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9833 std::pair<SDValue,SDValue>
9834 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9835 bool IsSigned, bool IsReplace) const {
9838 EVT DstTy = Op.getValueType();
9840 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9841 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9845 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9846 DstTy.getSimpleVT() >= MVT::i16 &&
9847 "Unknown FP_TO_INT to lower!");
9849 // These are really Legal.
9850 if (DstTy == MVT::i32 &&
9851 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9852 return std::make_pair(SDValue(), SDValue());
9853 if (Subtarget->is64Bit() &&
9854 DstTy == MVT::i64 &&
9855 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9856 return std::make_pair(SDValue(), SDValue());
9858 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9859 // stack slot, or into the FTOL runtime function.
9860 MachineFunction &MF = DAG.getMachineFunction();
9861 unsigned MemSize = DstTy.getSizeInBits()/8;
9862 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9863 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9866 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9867 Opc = X86ISD::WIN_FTOL;
9869 switch (DstTy.getSimpleVT().SimpleTy) {
9870 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9871 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9872 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9873 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9876 SDValue Chain = DAG.getEntryNode();
9877 SDValue Value = Op.getOperand(0);
9878 EVT TheVT = Op.getOperand(0).getValueType();
9879 // FIXME This causes a redundant load/store if the SSE-class value is already
9880 // in memory, such as if it is on the callstack.
9881 if (isScalarFPTypeInSSEReg(TheVT)) {
9882 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9883 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9884 MachinePointerInfo::getFixedStack(SSFI),
9886 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9888 Chain, StackSlot, DAG.getValueType(TheVT)
9891 MachineMemOperand *MMO =
9892 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9893 MachineMemOperand::MOLoad, MemSize, MemSize);
9894 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9895 Chain = Value.getValue(1);
9896 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9897 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9900 MachineMemOperand *MMO =
9901 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9902 MachineMemOperand::MOStore, MemSize, MemSize);
9904 if (Opc != X86ISD::WIN_FTOL) {
9905 // Build the FP_TO_INT*_IN_MEM
9906 SDValue Ops[] = { Chain, Value, StackSlot };
9907 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9909 return std::make_pair(FIST, StackSlot);
9911 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9912 DAG.getVTList(MVT::Other, MVT::Glue),
9914 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9915 MVT::i32, ftol.getValue(1));
9916 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9917 MVT::i32, eax.getValue(2));
9918 SDValue Ops[] = { eax, edx };
9919 SDValue pair = IsReplace
9920 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9921 : DAG.getMergeValues(Ops, DL);
9922 return std::make_pair(pair, SDValue());
9926 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9927 const X86Subtarget *Subtarget) {
9928 MVT VT = Op->getSimpleValueType(0);
9929 SDValue In = Op->getOperand(0);
9930 MVT InVT = In.getSimpleValueType();
9933 // Optimize vectors in AVX mode:
9936 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9937 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9938 // Concat upper and lower parts.
9941 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9942 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9943 // Concat upper and lower parts.
9946 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9947 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9948 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9951 if (Subtarget->hasInt256())
9952 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9954 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9955 SDValue Undef = DAG.getUNDEF(InVT);
9956 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9957 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9958 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9960 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9961 VT.getVectorNumElements()/2);
9963 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9964 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9966 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9969 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9970 SelectionDAG &DAG) {
9971 MVT VT = Op->getSimpleValueType(0);
9972 SDValue In = Op->getOperand(0);
9973 MVT InVT = In.getSimpleValueType();
9975 unsigned int NumElts = VT.getVectorNumElements();
9976 if (NumElts != 8 && NumElts != 16)
9979 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9980 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9982 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9983 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9984 // Now we have only mask extension
9985 assert(InVT.getVectorElementType() == MVT::i1);
9986 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9987 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9988 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9989 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9990 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9991 MachinePointerInfo::getConstantPool(),
9992 false, false, false, Alignment);
9994 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9995 if (VT.is512BitVector())
9997 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
10000 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10001 SelectionDAG &DAG) {
10002 if (Subtarget->hasFp256()) {
10003 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
10011 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10012 SelectionDAG &DAG) {
10014 MVT VT = Op.getSimpleValueType();
10015 SDValue In = Op.getOperand(0);
10016 MVT SVT = In.getSimpleValueType();
10018 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
10019 return LowerZERO_EXTEND_AVX512(Op, DAG);
10021 if (Subtarget->hasFp256()) {
10022 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
10027 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
10028 VT.getVectorNumElements() != SVT.getVectorNumElements());
10032 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
10034 MVT VT = Op.getSimpleValueType();
10035 SDValue In = Op.getOperand(0);
10036 MVT InVT = In.getSimpleValueType();
10038 if (VT == MVT::i1) {
10039 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
10040 "Invalid scalar TRUNCATE operation");
10041 if (InVT == MVT::i32)
10043 if (InVT.getSizeInBits() == 64)
10044 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
10045 else if (InVT.getSizeInBits() < 32)
10046 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
10047 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
10049 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
10050 "Invalid TRUNCATE operation");
10052 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
10053 if (VT.getVectorElementType().getSizeInBits() >=8)
10054 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
10056 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10057 unsigned NumElts = InVT.getVectorNumElements();
10058 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
10059 if (InVT.getSizeInBits() < 512) {
10060 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
10061 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
10065 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
10066 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
10067 SDValue CP = DAG.getConstantPool(C, getPointerTy());
10068 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10069 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
10070 MachinePointerInfo::getConstantPool(),
10071 false, false, false, Alignment);
10072 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
10073 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
10074 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
10077 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
10078 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
10079 if (Subtarget->hasInt256()) {
10080 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
10081 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
10082 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
10084 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
10085 DAG.getIntPtrConstant(0));
10088 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
10089 DAG.getIntPtrConstant(0));
10090 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
10091 DAG.getIntPtrConstant(2));
10092 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
10093 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
10094 static const int ShufMask[] = {0, 2, 4, 6};
10095 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
10098 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
10099 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
10100 if (Subtarget->hasInt256()) {
10101 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
10103 SmallVector<SDValue,32> pshufbMask;
10104 for (unsigned i = 0; i < 2; ++i) {
10105 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
10106 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
10107 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
10108 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
10109 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
10110 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
10111 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
10112 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
10113 for (unsigned j = 0; j < 8; ++j)
10114 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
10116 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
10117 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
10118 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
10120 static const int ShufMask[] = {0, 2, -1, -1};
10121 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
10123 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
10124 DAG.getIntPtrConstant(0));
10125 return DAG.getNode(ISD::BITCAST, DL, VT, In);
10128 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10129 DAG.getIntPtrConstant(0));
10131 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10132 DAG.getIntPtrConstant(4));
10134 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
10135 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
10137 // The PSHUFB mask:
10138 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
10139 -1, -1, -1, -1, -1, -1, -1, -1};
10141 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
10142 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
10143 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
10145 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
10146 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
10148 // The MOVLHPS Mask:
10149 static const int ShufMask2[] = {0, 1, 4, 5};
10150 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
10151 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
10154 // Handle truncation of V256 to V128 using shuffles.
10155 if (!VT.is128BitVector() || !InVT.is256BitVector())
10158 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
10160 unsigned NumElems = VT.getVectorNumElements();
10161 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
10163 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
10164 // Prepare truncation shuffle mask
10165 for (unsigned i = 0; i != NumElems; ++i)
10166 MaskVec[i] = i * 2;
10167 SDValue V = DAG.getVectorShuffle(NVT, DL,
10168 DAG.getNode(ISD::BITCAST, DL, NVT, In),
10169 DAG.getUNDEF(NVT), &MaskVec[0]);
10170 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
10171 DAG.getIntPtrConstant(0));
10174 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
10175 SelectionDAG &DAG) const {
10176 assert(!Op.getSimpleValueType().isVector());
10178 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10179 /*IsSigned=*/ true, /*IsReplace=*/ false);
10180 SDValue FIST = Vals.first, StackSlot = Vals.second;
10181 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
10182 if (!FIST.getNode()) return Op;
10184 if (StackSlot.getNode())
10185 // Load the result.
10186 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10187 FIST, StackSlot, MachinePointerInfo(),
10188 false, false, false, 0);
10190 // The node is the result.
10194 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
10195 SelectionDAG &DAG) const {
10196 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10197 /*IsSigned=*/ false, /*IsReplace=*/ false);
10198 SDValue FIST = Vals.first, StackSlot = Vals.second;
10199 assert(FIST.getNode() && "Unexpected failure");
10201 if (StackSlot.getNode())
10202 // Load the result.
10203 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10204 FIST, StackSlot, MachinePointerInfo(),
10205 false, false, false, 0);
10207 // The node is the result.
10211 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
10213 MVT VT = Op.getSimpleValueType();
10214 SDValue In = Op.getOperand(0);
10215 MVT SVT = In.getSimpleValueType();
10217 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
10219 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
10220 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
10221 In, DAG.getUNDEF(SVT)));
10224 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
10225 LLVMContext *Context = DAG.getContext();
10227 MVT VT = Op.getSimpleValueType();
10229 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10230 if (VT.isVector()) {
10231 EltVT = VT.getVectorElementType();
10232 NumElts = VT.getVectorNumElements();
10235 if (EltVT == MVT::f64)
10236 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10237 APInt(64, ~(1ULL << 63))));
10239 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10240 APInt(32, ~(1U << 31))));
10241 C = ConstantVector::getSplat(NumElts, C);
10242 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10243 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10244 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10245 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10246 MachinePointerInfo::getConstantPool(),
10247 false, false, false, Alignment);
10248 if (VT.isVector()) {
10249 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10250 return DAG.getNode(ISD::BITCAST, dl, VT,
10251 DAG.getNode(ISD::AND, dl, ANDVT,
10252 DAG.getNode(ISD::BITCAST, dl, ANDVT,
10254 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
10256 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
10259 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
10260 LLVMContext *Context = DAG.getContext();
10262 MVT VT = Op.getSimpleValueType();
10264 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10265 if (VT.isVector()) {
10266 EltVT = VT.getVectorElementType();
10267 NumElts = VT.getVectorNumElements();
10270 if (EltVT == MVT::f64)
10271 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10272 APInt(64, 1ULL << 63)));
10274 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10275 APInt(32, 1U << 31)));
10276 C = ConstantVector::getSplat(NumElts, C);
10277 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10278 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10279 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10280 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10281 MachinePointerInfo::getConstantPool(),
10282 false, false, false, Alignment);
10283 if (VT.isVector()) {
10284 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
10285 return DAG.getNode(ISD::BITCAST, dl, VT,
10286 DAG.getNode(ISD::XOR, dl, XORVT,
10287 DAG.getNode(ISD::BITCAST, dl, XORVT,
10289 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
10292 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
10295 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
10296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10297 LLVMContext *Context = DAG.getContext();
10298 SDValue Op0 = Op.getOperand(0);
10299 SDValue Op1 = Op.getOperand(1);
10301 MVT VT = Op.getSimpleValueType();
10302 MVT SrcVT = Op1.getSimpleValueType();
10304 // If second operand is smaller, extend it first.
10305 if (SrcVT.bitsLT(VT)) {
10306 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
10309 // And if it is bigger, shrink it first.
10310 if (SrcVT.bitsGT(VT)) {
10311 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
10315 // At this point the operands and the result should have the same
10316 // type, and that won't be f80 since that is not custom lowered.
10318 // First get the sign bit of second operand.
10319 SmallVector<Constant*,4> CV;
10320 if (SrcVT == MVT::f64) {
10321 const fltSemantics &Sem = APFloat::IEEEdouble;
10322 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
10323 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10325 const fltSemantics &Sem = APFloat::IEEEsingle;
10326 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
10327 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10328 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10329 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10331 Constant *C = ConstantVector::get(CV);
10332 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10333 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10334 MachinePointerInfo::getConstantPool(),
10335 false, false, false, 16);
10336 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10338 // Shift sign bit right or left if the two operands have different types.
10339 if (SrcVT.bitsGT(VT)) {
10340 // Op0 is MVT::f32, Op1 is MVT::f64.
10341 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10342 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10343 DAG.getConstant(32, MVT::i32));
10344 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10345 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10346 DAG.getIntPtrConstant(0));
10349 // Clear first operand sign bit.
10351 if (VT == MVT::f64) {
10352 const fltSemantics &Sem = APFloat::IEEEdouble;
10353 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10354 APInt(64, ~(1ULL << 63)))));
10355 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10357 const fltSemantics &Sem = APFloat::IEEEsingle;
10358 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10359 APInt(32, ~(1U << 31)))));
10360 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10361 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10362 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10364 C = ConstantVector::get(CV);
10365 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10366 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10367 MachinePointerInfo::getConstantPool(),
10368 false, false, false, 16);
10369 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10371 // Or the value with the sign bit.
10372 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10375 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10376 SDValue N0 = Op.getOperand(0);
10378 MVT VT = Op.getSimpleValueType();
10380 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10381 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10382 DAG.getConstant(1, VT));
10383 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10386 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10388 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10389 SelectionDAG &DAG) {
10390 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10392 if (!Subtarget->hasSSE41())
10395 if (!Op->hasOneUse())
10398 SDNode *N = Op.getNode();
10401 SmallVector<SDValue, 8> Opnds;
10402 DenseMap<SDValue, unsigned> VecInMap;
10403 SmallVector<SDValue, 8> VecIns;
10404 EVT VT = MVT::Other;
10406 // Recognize a special case where a vector is casted into wide integer to
10408 Opnds.push_back(N->getOperand(0));
10409 Opnds.push_back(N->getOperand(1));
10411 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10412 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10413 // BFS traverse all OR'd operands.
10414 if (I->getOpcode() == ISD::OR) {
10415 Opnds.push_back(I->getOperand(0));
10416 Opnds.push_back(I->getOperand(1));
10417 // Re-evaluate the number of nodes to be traversed.
10418 e += 2; // 2 more nodes (LHS and RHS) are pushed.
10422 // Quit if a non-EXTRACT_VECTOR_ELT
10423 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10426 // Quit if without a constant index.
10427 SDValue Idx = I->getOperand(1);
10428 if (!isa<ConstantSDNode>(Idx))
10431 SDValue ExtractedFromVec = I->getOperand(0);
10432 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10433 if (M == VecInMap.end()) {
10434 VT = ExtractedFromVec.getValueType();
10435 // Quit if not 128/256-bit vector.
10436 if (!VT.is128BitVector() && !VT.is256BitVector())
10438 // Quit if not the same type.
10439 if (VecInMap.begin() != VecInMap.end() &&
10440 VT != VecInMap.begin()->first.getValueType())
10442 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10443 VecIns.push_back(ExtractedFromVec);
10445 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10448 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10449 "Not extracted from 128-/256-bit vector.");
10451 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10453 for (DenseMap<SDValue, unsigned>::const_iterator
10454 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10455 // Quit if not all elements are used.
10456 if (I->second != FullMask)
10460 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10462 // Cast all vectors into TestVT for PTEST.
10463 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10464 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10466 // If more than one full vectors are evaluated, OR them first before PTEST.
10467 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10468 // Each iteration will OR 2 nodes and append the result until there is only
10469 // 1 node left, i.e. the final OR'd value of all vectors.
10470 SDValue LHS = VecIns[Slot];
10471 SDValue RHS = VecIns[Slot + 1];
10472 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10475 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10476 VecIns.back(), VecIns.back());
10479 /// \brief return true if \c Op has a use that doesn't just read flags.
10480 static bool hasNonFlagsUse(SDValue Op) {
10481 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10483 SDNode *User = *UI;
10484 unsigned UOpNo = UI.getOperandNo();
10485 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10486 // Look pass truncate.
10487 UOpNo = User->use_begin().getOperandNo();
10488 User = *User->use_begin();
10491 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10492 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10498 /// Emit nodes that will be selected as "test Op0,Op0", or something
10500 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10501 SelectionDAG &DAG) const {
10502 if (Op.getValueType() == MVT::i1)
10503 // KORTEST instruction should be selected
10504 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10505 DAG.getConstant(0, Op.getValueType()));
10507 // CF and OF aren't always set the way we want. Determine which
10508 // of these we need.
10509 bool NeedCF = false;
10510 bool NeedOF = false;
10513 case X86::COND_A: case X86::COND_AE:
10514 case X86::COND_B: case X86::COND_BE:
10517 case X86::COND_G: case X86::COND_GE:
10518 case X86::COND_L: case X86::COND_LE:
10519 case X86::COND_O: case X86::COND_NO: {
10520 // Check if we really need to set the
10521 // Overflow flag. If NoSignedWrap is present
10522 // that is not actually needed.
10523 switch (Op->getOpcode()) {
10528 const BinaryWithFlagsSDNode *BinNode =
10529 cast<BinaryWithFlagsSDNode>(Op.getNode());
10530 if (BinNode->hasNoSignedWrap())
10540 // See if we can use the EFLAGS value from the operand instead of
10541 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10542 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10543 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10544 // Emit a CMP with 0, which is the TEST pattern.
10545 //if (Op.getValueType() == MVT::i1)
10546 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10547 // DAG.getConstant(0, MVT::i1));
10548 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10549 DAG.getConstant(0, Op.getValueType()));
10551 unsigned Opcode = 0;
10552 unsigned NumOperands = 0;
10554 // Truncate operations may prevent the merge of the SETCC instruction
10555 // and the arithmetic instruction before it. Attempt to truncate the operands
10556 // of the arithmetic instruction and use a reduced bit-width instruction.
10557 bool NeedTruncation = false;
10558 SDValue ArithOp = Op;
10559 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10560 SDValue Arith = Op->getOperand(0);
10561 // Both the trunc and the arithmetic op need to have one user each.
10562 if (Arith->hasOneUse())
10563 switch (Arith.getOpcode()) {
10570 NeedTruncation = true;
10576 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10577 // which may be the result of a CAST. We use the variable 'Op', which is the
10578 // non-casted variable when we check for possible users.
10579 switch (ArithOp.getOpcode()) {
10581 // Due to an isel shortcoming, be conservative if this add is likely to be
10582 // selected as part of a load-modify-store instruction. When the root node
10583 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10584 // uses of other nodes in the match, such as the ADD in this case. This
10585 // leads to the ADD being left around and reselected, with the result being
10586 // two adds in the output. Alas, even if none our users are stores, that
10587 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10588 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10589 // climbing the DAG back to the root, and it doesn't seem to be worth the
10591 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10592 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10593 if (UI->getOpcode() != ISD::CopyToReg &&
10594 UI->getOpcode() != ISD::SETCC &&
10595 UI->getOpcode() != ISD::STORE)
10598 if (ConstantSDNode *C =
10599 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10600 // An add of one will be selected as an INC.
10601 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10602 Opcode = X86ISD::INC;
10607 // An add of negative one (subtract of one) will be selected as a DEC.
10608 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10609 Opcode = X86ISD::DEC;
10615 // Otherwise use a regular EFLAGS-setting add.
10616 Opcode = X86ISD::ADD;
10621 // If we have a constant logical shift that's only used in a comparison
10622 // against zero turn it into an equivalent AND. This allows turning it into
10623 // a TEST instruction later.
10624 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10625 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10626 EVT VT = Op.getValueType();
10627 unsigned BitWidth = VT.getSizeInBits();
10628 unsigned ShAmt = Op->getConstantOperandVal(1);
10629 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10631 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10632 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10633 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10634 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10636 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10637 DAG.getConstant(Mask, VT));
10638 DAG.ReplaceAllUsesWith(Op, New);
10644 // If the primary and result isn't used, don't bother using X86ISD::AND,
10645 // because a TEST instruction will be better.
10646 if (!hasNonFlagsUse(Op))
10652 // Due to the ISEL shortcoming noted above, be conservative if this op is
10653 // likely to be selected as part of a load-modify-store instruction.
10654 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10655 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10656 if (UI->getOpcode() == ISD::STORE)
10659 // Otherwise use a regular EFLAGS-setting instruction.
10660 switch (ArithOp.getOpcode()) {
10661 default: llvm_unreachable("unexpected operator!");
10662 case ISD::SUB: Opcode = X86ISD::SUB; break;
10663 case ISD::XOR: Opcode = X86ISD::XOR; break;
10664 case ISD::AND: Opcode = X86ISD::AND; break;
10666 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10667 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10668 if (EFLAGS.getNode())
10671 Opcode = X86ISD::OR;
10685 return SDValue(Op.getNode(), 1);
10691 // If we found that truncation is beneficial, perform the truncation and
10693 if (NeedTruncation) {
10694 EVT VT = Op.getValueType();
10695 SDValue WideVal = Op->getOperand(0);
10696 EVT WideVT = WideVal.getValueType();
10697 unsigned ConvertedOp = 0;
10698 // Use a target machine opcode to prevent further DAGCombine
10699 // optimizations that may separate the arithmetic operations
10700 // from the setcc node.
10701 switch (WideVal.getOpcode()) {
10703 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10704 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10705 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10706 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10707 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10711 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10712 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10713 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10714 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10715 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10721 // Emit a CMP with 0, which is the TEST pattern.
10722 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10723 DAG.getConstant(0, Op.getValueType()));
10725 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10726 SmallVector<SDValue, 4> Ops;
10727 for (unsigned i = 0; i != NumOperands; ++i)
10728 Ops.push_back(Op.getOperand(i));
10730 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10731 DAG.ReplaceAllUsesWith(Op, New);
10732 return SDValue(New.getNode(), 1);
10735 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10737 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10738 SDLoc dl, SelectionDAG &DAG) const {
10739 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10740 if (C->getAPIntValue() == 0)
10741 return EmitTest(Op0, X86CC, dl, DAG);
10743 if (Op0.getValueType() == MVT::i1)
10744 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10747 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10748 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10749 // Do the comparison at i32 if it's smaller, besides the Atom case.
10750 // This avoids subregister aliasing issues. Keep the smaller reference
10751 // if we're optimizing for size, however, as that'll allow better folding
10752 // of memory operations.
10753 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10754 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10755 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10756 !Subtarget->isAtom()) {
10757 unsigned ExtendOp =
10758 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10759 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10760 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10762 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10763 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10764 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10766 return SDValue(Sub.getNode(), 1);
10768 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10771 /// Convert a comparison if required by the subtarget.
10772 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10773 SelectionDAG &DAG) const {
10774 // If the subtarget does not support the FUCOMI instruction, floating-point
10775 // comparisons have to be converted.
10776 if (Subtarget->hasCMov() ||
10777 Cmp.getOpcode() != X86ISD::CMP ||
10778 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10779 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10782 // The instruction selector will select an FUCOM instruction instead of
10783 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10784 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10785 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10787 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10788 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10789 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10790 DAG.getConstant(8, MVT::i8));
10791 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10792 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10795 static bool isAllOnes(SDValue V) {
10796 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10797 return C && C->isAllOnesValue();
10800 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10801 /// if it's possible.
10802 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10803 SDLoc dl, SelectionDAG &DAG) const {
10804 SDValue Op0 = And.getOperand(0);
10805 SDValue Op1 = And.getOperand(1);
10806 if (Op0.getOpcode() == ISD::TRUNCATE)
10807 Op0 = Op0.getOperand(0);
10808 if (Op1.getOpcode() == ISD::TRUNCATE)
10809 Op1 = Op1.getOperand(0);
10812 if (Op1.getOpcode() == ISD::SHL)
10813 std::swap(Op0, Op1);
10814 if (Op0.getOpcode() == ISD::SHL) {
10815 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10816 if (And00C->getZExtValue() == 1) {
10817 // If we looked past a truncate, check that it's only truncating away
10819 unsigned BitWidth = Op0.getValueSizeInBits();
10820 unsigned AndBitWidth = And.getValueSizeInBits();
10821 if (BitWidth > AndBitWidth) {
10823 DAG.computeKnownBits(Op0, Zeros, Ones);
10824 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10828 RHS = Op0.getOperand(1);
10830 } else if (Op1.getOpcode() == ISD::Constant) {
10831 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10832 uint64_t AndRHSVal = AndRHS->getZExtValue();
10833 SDValue AndLHS = Op0;
10835 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10836 LHS = AndLHS.getOperand(0);
10837 RHS = AndLHS.getOperand(1);
10840 // Use BT if the immediate can't be encoded in a TEST instruction.
10841 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10843 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10847 if (LHS.getNode()) {
10848 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10849 // instruction. Since the shift amount is in-range-or-undefined, we know
10850 // that doing a bittest on the i32 value is ok. We extend to i32 because
10851 // the encoding for the i16 version is larger than the i32 version.
10852 // Also promote i16 to i32 for performance / code size reason.
10853 if (LHS.getValueType() == MVT::i8 ||
10854 LHS.getValueType() == MVT::i16)
10855 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10857 // If the operand types disagree, extend the shift amount to match. Since
10858 // BT ignores high bits (like shifts) we can use anyextend.
10859 if (LHS.getValueType() != RHS.getValueType())
10860 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10862 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10863 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10864 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10865 DAG.getConstant(Cond, MVT::i8), BT);
10871 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10873 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10878 // SSE Condition code mapping:
10887 switch (SetCCOpcode) {
10888 default: llvm_unreachable("Unexpected SETCC condition");
10890 case ISD::SETEQ: SSECC = 0; break;
10892 case ISD::SETGT: Swap = true; // Fallthrough
10894 case ISD::SETOLT: SSECC = 1; break;
10896 case ISD::SETGE: Swap = true; // Fallthrough
10898 case ISD::SETOLE: SSECC = 2; break;
10899 case ISD::SETUO: SSECC = 3; break;
10901 case ISD::SETNE: SSECC = 4; break;
10902 case ISD::SETULE: Swap = true; // Fallthrough
10903 case ISD::SETUGE: SSECC = 5; break;
10904 case ISD::SETULT: Swap = true; // Fallthrough
10905 case ISD::SETUGT: SSECC = 6; break;
10906 case ISD::SETO: SSECC = 7; break;
10908 case ISD::SETONE: SSECC = 8; break;
10911 std::swap(Op0, Op1);
10916 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10917 // ones, and then concatenate the result back.
10918 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10919 MVT VT = Op.getSimpleValueType();
10921 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10922 "Unsupported value type for operation");
10924 unsigned NumElems = VT.getVectorNumElements();
10926 SDValue CC = Op.getOperand(2);
10928 // Extract the LHS vectors
10929 SDValue LHS = Op.getOperand(0);
10930 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10931 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10933 // Extract the RHS vectors
10934 SDValue RHS = Op.getOperand(1);
10935 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10936 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10938 // Issue the operation on the smaller types and concatenate the result back
10939 MVT EltVT = VT.getVectorElementType();
10940 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10941 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10942 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10943 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10946 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10947 const X86Subtarget *Subtarget) {
10948 SDValue Op0 = Op.getOperand(0);
10949 SDValue Op1 = Op.getOperand(1);
10950 SDValue CC = Op.getOperand(2);
10951 MVT VT = Op.getSimpleValueType();
10954 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10955 Op.getValueType().getScalarType() == MVT::i1 &&
10956 "Cannot set masked compare for this operation");
10958 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10960 bool Unsigned = false;
10963 switch (SetCCOpcode) {
10964 default: llvm_unreachable("Unexpected SETCC condition");
10965 case ISD::SETNE: SSECC = 4; break;
10966 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10967 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10968 case ISD::SETLT: Swap = true; //fall-through
10969 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10970 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10971 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10972 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10973 case ISD::SETULE: Unsigned = true; //fall-through
10974 case ISD::SETLE: SSECC = 2; break;
10978 std::swap(Op0, Op1);
10980 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10981 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10982 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10983 DAG.getConstant(SSECC, MVT::i8));
10986 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10987 /// operand \p Op1. If non-trivial (for example because it's not constant)
10988 /// return an empty value.
10989 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10991 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10995 MVT VT = Op1.getSimpleValueType();
10996 MVT EVT = VT.getVectorElementType();
10997 unsigned n = VT.getVectorNumElements();
10998 SmallVector<SDValue, 8> ULTOp1;
11000 for (unsigned i = 0; i < n; ++i) {
11001 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
11002 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
11005 // Avoid underflow.
11006 APInt Val = Elt->getAPIntValue();
11010 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
11013 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
11016 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
11017 SelectionDAG &DAG) {
11018 SDValue Op0 = Op.getOperand(0);
11019 SDValue Op1 = Op.getOperand(1);
11020 SDValue CC = Op.getOperand(2);
11021 MVT VT = Op.getSimpleValueType();
11022 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
11023 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
11028 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
11029 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
11032 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
11033 unsigned Opc = X86ISD::CMPP;
11034 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
11035 assert(VT.getVectorNumElements() <= 16);
11036 Opc = X86ISD::CMPM;
11038 // In the two special cases we can't handle, emit two comparisons.
11041 unsigned CombineOpc;
11042 if (SetCCOpcode == ISD::SETUEQ) {
11043 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
11045 assert(SetCCOpcode == ISD::SETONE);
11046 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
11049 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
11050 DAG.getConstant(CC0, MVT::i8));
11051 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
11052 DAG.getConstant(CC1, MVT::i8));
11053 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
11055 // Handle all other FP comparisons here.
11056 return DAG.getNode(Opc, dl, VT, Op0, Op1,
11057 DAG.getConstant(SSECC, MVT::i8));
11060 // Break 256-bit integer vector compare into smaller ones.
11061 if (VT.is256BitVector() && !Subtarget->hasInt256())
11062 return Lower256IntVSETCC(Op, DAG);
11064 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
11065 EVT OpVT = Op1.getValueType();
11066 if (Subtarget->hasAVX512()) {
11067 if (Op1.getValueType().is512BitVector() ||
11068 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
11069 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
11071 // In AVX-512 architecture setcc returns mask with i1 elements,
11072 // But there is no compare instruction for i8 and i16 elements.
11073 // We are not talking about 512-bit operands in this case, these
11074 // types are illegal.
11076 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
11077 OpVT.getVectorElementType().getSizeInBits() >= 8))
11078 return DAG.getNode(ISD::TRUNCATE, dl, VT,
11079 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
11082 // We are handling one of the integer comparisons here. Since SSE only has
11083 // GT and EQ comparisons for integer, swapping operands and multiple
11084 // operations may be required for some comparisons.
11086 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
11087 bool Subus = false;
11089 switch (SetCCOpcode) {
11090 default: llvm_unreachable("Unexpected SETCC condition");
11091 case ISD::SETNE: Invert = true;
11092 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
11093 case ISD::SETLT: Swap = true;
11094 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
11095 case ISD::SETGE: Swap = true;
11096 case ISD::SETLE: Opc = X86ISD::PCMPGT;
11097 Invert = true; break;
11098 case ISD::SETULT: Swap = true;
11099 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
11100 FlipSigns = true; break;
11101 case ISD::SETUGE: Swap = true;
11102 case ISD::SETULE: Opc = X86ISD::PCMPGT;
11103 FlipSigns = true; Invert = true; break;
11106 // Special case: Use min/max operations for SETULE/SETUGE
11107 MVT VET = VT.getVectorElementType();
11109 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
11110 || (Subtarget->hasSSE2() && (VET == MVT::i8));
11113 switch (SetCCOpcode) {
11115 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
11116 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
11119 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
11122 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
11123 if (!MinMax && hasSubus) {
11124 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
11126 // t = psubus Op0, Op1
11127 // pcmpeq t, <0..0>
11128 switch (SetCCOpcode) {
11130 case ISD::SETULT: {
11131 // If the comparison is against a constant we can turn this into a
11132 // setule. With psubus, setule does not require a swap. This is
11133 // beneficial because the constant in the register is no longer
11134 // destructed as the destination so it can be hoisted out of a loop.
11135 // Only do this pre-AVX since vpcmp* is no longer destructive.
11136 if (Subtarget->hasAVX())
11138 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
11139 if (ULEOp1.getNode()) {
11141 Subus = true; Invert = false; Swap = false;
11145 // Psubus is better than flip-sign because it requires no inversion.
11146 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
11147 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
11151 Opc = X86ISD::SUBUS;
11157 std::swap(Op0, Op1);
11159 // Check that the operation in question is available (most are plain SSE2,
11160 // but PCMPGTQ and PCMPEQQ have different requirements).
11161 if (VT == MVT::v2i64) {
11162 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
11163 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
11165 // First cast everything to the right type.
11166 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11167 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11169 // Since SSE has no unsigned integer comparisons, we need to flip the sign
11170 // bits of the inputs before performing those operations. The lower
11171 // compare is always unsigned.
11174 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
11176 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
11177 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
11178 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
11179 Sign, Zero, Sign, Zero);
11181 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
11182 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
11184 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
11185 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
11186 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
11188 // Create masks for only the low parts/high parts of the 64 bit integers.
11189 static const int MaskHi[] = { 1, 1, 3, 3 };
11190 static const int MaskLo[] = { 0, 0, 2, 2 };
11191 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
11192 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
11193 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
11195 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
11196 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
11199 Result = DAG.getNOT(dl, Result, MVT::v4i32);
11201 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11204 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
11205 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
11206 // pcmpeqd + pshufd + pand.
11207 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
11209 // First cast everything to the right type.
11210 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11211 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11214 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
11216 // Make sure the lower and upper halves are both all-ones.
11217 static const int Mask[] = { 1, 0, 3, 2 };
11218 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
11219 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
11222 Result = DAG.getNOT(dl, Result, MVT::v4i32);
11224 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11228 // Since SSE has no unsigned integer comparisons, we need to flip the sign
11229 // bits of the inputs before performing those operations.
11231 EVT EltVT = VT.getVectorElementType();
11232 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
11233 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
11234 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
11237 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
11239 // If the logical-not of the result is required, perform that now.
11241 Result = DAG.getNOT(dl, Result, VT);
11244 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
11247 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
11248 getZeroVector(VT, Subtarget, DAG, dl));
11253 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
11255 MVT VT = Op.getSimpleValueType();
11257 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
11259 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
11260 && "SetCC type must be 8-bit or 1-bit integer");
11261 SDValue Op0 = Op.getOperand(0);
11262 SDValue Op1 = Op.getOperand(1);
11264 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11266 // Optimize to BT if possible.
11267 // Lower (X & (1 << N)) == 0 to BT(X, N).
11268 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
11269 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
11270 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
11271 Op1.getOpcode() == ISD::Constant &&
11272 cast<ConstantSDNode>(Op1)->isNullValue() &&
11273 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11274 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
11275 if (NewSetCC.getNode())
11279 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
11281 if (Op1.getOpcode() == ISD::Constant &&
11282 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
11283 cast<ConstantSDNode>(Op1)->isNullValue()) &&
11284 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11286 // If the input is a setcc, then reuse the input setcc or use a new one with
11287 // the inverted condition.
11288 if (Op0.getOpcode() == X86ISD::SETCC) {
11289 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
11290 bool Invert = (CC == ISD::SETNE) ^
11291 cast<ConstantSDNode>(Op1)->isNullValue();
11295 CCode = X86::GetOppositeBranchCondition(CCode);
11296 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11297 DAG.getConstant(CCode, MVT::i8),
11298 Op0.getOperand(1));
11300 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11304 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11305 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11306 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11308 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11309 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11312 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
11313 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
11314 if (X86CC == X86::COND_INVALID)
11317 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
11318 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11319 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11320 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11322 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11326 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11327 static bool isX86LogicalCmp(SDValue Op) {
11328 unsigned Opc = Op.getNode()->getOpcode();
11329 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11330 Opc == X86ISD::SAHF)
11332 if (Op.getResNo() == 1 &&
11333 (Opc == X86ISD::ADD ||
11334 Opc == X86ISD::SUB ||
11335 Opc == X86ISD::ADC ||
11336 Opc == X86ISD::SBB ||
11337 Opc == X86ISD::SMUL ||
11338 Opc == X86ISD::UMUL ||
11339 Opc == X86ISD::INC ||
11340 Opc == X86ISD::DEC ||
11341 Opc == X86ISD::OR ||
11342 Opc == X86ISD::XOR ||
11343 Opc == X86ISD::AND))
11346 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11352 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11353 if (V.getOpcode() != ISD::TRUNCATE)
11356 SDValue VOp0 = V.getOperand(0);
11357 unsigned InBits = VOp0.getValueSizeInBits();
11358 unsigned Bits = V.getValueSizeInBits();
11359 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11362 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11363 bool addTest = true;
11364 SDValue Cond = Op.getOperand(0);
11365 SDValue Op1 = Op.getOperand(1);
11366 SDValue Op2 = Op.getOperand(2);
11368 EVT VT = Op1.getValueType();
11371 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11372 // are available. Otherwise fp cmovs get lowered into a less efficient branch
11373 // sequence later on.
11374 if (Cond.getOpcode() == ISD::SETCC &&
11375 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11376 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11377 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11378 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11379 int SSECC = translateX86FSETCC(
11380 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11383 if (Subtarget->hasAVX512()) {
11384 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11385 DAG.getConstant(SSECC, MVT::i8));
11386 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11388 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11389 DAG.getConstant(SSECC, MVT::i8));
11390 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11391 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11392 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11396 if (Cond.getOpcode() == ISD::SETCC) {
11397 SDValue NewCond = LowerSETCC(Cond, DAG);
11398 if (NewCond.getNode())
11402 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11403 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11404 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11405 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11406 if (Cond.getOpcode() == X86ISD::SETCC &&
11407 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11408 isZero(Cond.getOperand(1).getOperand(1))) {
11409 SDValue Cmp = Cond.getOperand(1);
11411 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11413 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11414 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11415 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11417 SDValue CmpOp0 = Cmp.getOperand(0);
11418 // Apply further optimizations for special cases
11419 // (select (x != 0), -1, 0) -> neg & sbb
11420 // (select (x == 0), 0, -1) -> neg & sbb
11421 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11422 if (YC->isNullValue() &&
11423 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11424 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11425 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11426 DAG.getConstant(0, CmpOp0.getValueType()),
11428 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11429 DAG.getConstant(X86::COND_B, MVT::i8),
11430 SDValue(Neg.getNode(), 1));
11434 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11435 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11436 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11438 SDValue Res = // Res = 0 or -1.
11439 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11440 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11442 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11443 Res = DAG.getNOT(DL, Res, Res.getValueType());
11445 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11446 if (!N2C || !N2C->isNullValue())
11447 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11452 // Look past (and (setcc_carry (cmp ...)), 1).
11453 if (Cond.getOpcode() == ISD::AND &&
11454 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11455 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11456 if (C && C->getAPIntValue() == 1)
11457 Cond = Cond.getOperand(0);
11460 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11461 // setting operand in place of the X86ISD::SETCC.
11462 unsigned CondOpcode = Cond.getOpcode();
11463 if (CondOpcode == X86ISD::SETCC ||
11464 CondOpcode == X86ISD::SETCC_CARRY) {
11465 CC = Cond.getOperand(0);
11467 SDValue Cmp = Cond.getOperand(1);
11468 unsigned Opc = Cmp.getOpcode();
11469 MVT VT = Op.getSimpleValueType();
11471 bool IllegalFPCMov = false;
11472 if (VT.isFloatingPoint() && !VT.isVector() &&
11473 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11474 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11476 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11477 Opc == X86ISD::BT) { // FIXME
11481 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11482 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11483 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11484 Cond.getOperand(0).getValueType() != MVT::i8)) {
11485 SDValue LHS = Cond.getOperand(0);
11486 SDValue RHS = Cond.getOperand(1);
11487 unsigned X86Opcode;
11490 switch (CondOpcode) {
11491 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11492 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11493 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11494 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11495 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11496 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11497 default: llvm_unreachable("unexpected overflowing operator");
11499 if (CondOpcode == ISD::UMULO)
11500 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11503 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11505 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11507 if (CondOpcode == ISD::UMULO)
11508 Cond = X86Op.getValue(2);
11510 Cond = X86Op.getValue(1);
11512 CC = DAG.getConstant(X86Cond, MVT::i8);
11517 // Look pass the truncate if the high bits are known zero.
11518 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11519 Cond = Cond.getOperand(0);
11521 // We know the result of AND is compared against zero. Try to match
11523 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11524 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11525 if (NewSetCC.getNode()) {
11526 CC = NewSetCC.getOperand(0);
11527 Cond = NewSetCC.getOperand(1);
11534 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11535 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11538 // a < b ? -1 : 0 -> RES = ~setcc_carry
11539 // a < b ? 0 : -1 -> RES = setcc_carry
11540 // a >= b ? -1 : 0 -> RES = setcc_carry
11541 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11542 if (Cond.getOpcode() == X86ISD::SUB) {
11543 Cond = ConvertCmpIfNecessary(Cond, DAG);
11544 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11546 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11547 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11548 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11549 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11550 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11551 return DAG.getNOT(DL, Res, Res.getValueType());
11556 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11557 // widen the cmov and push the truncate through. This avoids introducing a new
11558 // branch during isel and doesn't add any extensions.
11559 if (Op.getValueType() == MVT::i8 &&
11560 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11561 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11562 if (T1.getValueType() == T2.getValueType() &&
11563 // Blacklist CopyFromReg to avoid partial register stalls.
11564 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11565 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11566 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11567 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11571 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11572 // condition is true.
11573 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11574 SDValue Ops[] = { Op2, Op1, CC, Cond };
11575 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11578 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11579 MVT VT = Op->getSimpleValueType(0);
11580 SDValue In = Op->getOperand(0);
11581 MVT InVT = In.getSimpleValueType();
11584 unsigned int NumElts = VT.getVectorNumElements();
11585 if (NumElts != 8 && NumElts != 16)
11588 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11589 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11591 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11592 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11594 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11595 Constant *C = ConstantInt::get(*DAG.getContext(),
11596 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11598 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11599 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11600 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11601 MachinePointerInfo::getConstantPool(),
11602 false, false, false, Alignment);
11603 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11604 if (VT.is512BitVector())
11606 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11609 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11610 SelectionDAG &DAG) {
11611 MVT VT = Op->getSimpleValueType(0);
11612 SDValue In = Op->getOperand(0);
11613 MVT InVT = In.getSimpleValueType();
11616 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11617 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11619 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11620 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11621 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11624 if (Subtarget->hasInt256())
11625 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11627 // Optimize vectors in AVX mode
11628 // Sign extend v8i16 to v8i32 and
11631 // Divide input vector into two parts
11632 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11633 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11634 // concat the vectors to original VT
11636 unsigned NumElems = InVT.getVectorNumElements();
11637 SDValue Undef = DAG.getUNDEF(InVT);
11639 SmallVector<int,8> ShufMask1(NumElems, -1);
11640 for (unsigned i = 0; i != NumElems/2; ++i)
11643 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11645 SmallVector<int,8> ShufMask2(NumElems, -1);
11646 for (unsigned i = 0; i != NumElems/2; ++i)
11647 ShufMask2[i] = i + NumElems/2;
11649 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11651 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11652 VT.getVectorNumElements()/2);
11654 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11655 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11657 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11660 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11661 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11662 // from the AND / OR.
11663 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11664 Opc = Op.getOpcode();
11665 if (Opc != ISD::OR && Opc != ISD::AND)
11667 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11668 Op.getOperand(0).hasOneUse() &&
11669 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11670 Op.getOperand(1).hasOneUse());
11673 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11674 // 1 and that the SETCC node has a single use.
11675 static bool isXor1OfSetCC(SDValue Op) {
11676 if (Op.getOpcode() != ISD::XOR)
11678 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11679 if (N1C && N1C->getAPIntValue() == 1) {
11680 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11681 Op.getOperand(0).hasOneUse();
11686 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11687 bool addTest = true;
11688 SDValue Chain = Op.getOperand(0);
11689 SDValue Cond = Op.getOperand(1);
11690 SDValue Dest = Op.getOperand(2);
11693 bool Inverted = false;
11695 if (Cond.getOpcode() == ISD::SETCC) {
11696 // Check for setcc([su]{add,sub,mul}o == 0).
11697 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11698 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11699 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11700 Cond.getOperand(0).getResNo() == 1 &&
11701 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11702 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11703 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11704 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11705 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11706 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11708 Cond = Cond.getOperand(0);
11710 SDValue NewCond = LowerSETCC(Cond, DAG);
11711 if (NewCond.getNode())
11716 // FIXME: LowerXALUO doesn't handle these!!
11717 else if (Cond.getOpcode() == X86ISD::ADD ||
11718 Cond.getOpcode() == X86ISD::SUB ||
11719 Cond.getOpcode() == X86ISD::SMUL ||
11720 Cond.getOpcode() == X86ISD::UMUL)
11721 Cond = LowerXALUO(Cond, DAG);
11724 // Look pass (and (setcc_carry (cmp ...)), 1).
11725 if (Cond.getOpcode() == ISD::AND &&
11726 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11727 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11728 if (C && C->getAPIntValue() == 1)
11729 Cond = Cond.getOperand(0);
11732 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11733 // setting operand in place of the X86ISD::SETCC.
11734 unsigned CondOpcode = Cond.getOpcode();
11735 if (CondOpcode == X86ISD::SETCC ||
11736 CondOpcode == X86ISD::SETCC_CARRY) {
11737 CC = Cond.getOperand(0);
11739 SDValue Cmp = Cond.getOperand(1);
11740 unsigned Opc = Cmp.getOpcode();
11741 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11742 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11746 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11750 // These can only come from an arithmetic instruction with overflow,
11751 // e.g. SADDO, UADDO.
11752 Cond = Cond.getNode()->getOperand(1);
11758 CondOpcode = Cond.getOpcode();
11759 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11760 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11761 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11762 Cond.getOperand(0).getValueType() != MVT::i8)) {
11763 SDValue LHS = Cond.getOperand(0);
11764 SDValue RHS = Cond.getOperand(1);
11765 unsigned X86Opcode;
11768 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11769 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11771 switch (CondOpcode) {
11772 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11774 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11776 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11779 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11780 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11782 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11784 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11787 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11788 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11789 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11790 default: llvm_unreachable("unexpected overflowing operator");
11793 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11794 if (CondOpcode == ISD::UMULO)
11795 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11798 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11800 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11802 if (CondOpcode == ISD::UMULO)
11803 Cond = X86Op.getValue(2);
11805 Cond = X86Op.getValue(1);
11807 CC = DAG.getConstant(X86Cond, MVT::i8);
11811 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11812 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11813 if (CondOpc == ISD::OR) {
11814 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11815 // two branches instead of an explicit OR instruction with a
11817 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11818 isX86LogicalCmp(Cmp)) {
11819 CC = Cond.getOperand(0).getOperand(0);
11820 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11821 Chain, Dest, CC, Cmp);
11822 CC = Cond.getOperand(1).getOperand(0);
11826 } else { // ISD::AND
11827 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11828 // two branches instead of an explicit AND instruction with a
11829 // separate test. However, we only do this if this block doesn't
11830 // have a fall-through edge, because this requires an explicit
11831 // jmp when the condition is false.
11832 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11833 isX86LogicalCmp(Cmp) &&
11834 Op.getNode()->hasOneUse()) {
11835 X86::CondCode CCode =
11836 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11837 CCode = X86::GetOppositeBranchCondition(CCode);
11838 CC = DAG.getConstant(CCode, MVT::i8);
11839 SDNode *User = *Op.getNode()->use_begin();
11840 // Look for an unconditional branch following this conditional branch.
11841 // We need this because we need to reverse the successors in order
11842 // to implement FCMP_OEQ.
11843 if (User->getOpcode() == ISD::BR) {
11844 SDValue FalseBB = User->getOperand(1);
11846 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11847 assert(NewBR == User);
11851 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11852 Chain, Dest, CC, Cmp);
11853 X86::CondCode CCode =
11854 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11855 CCode = X86::GetOppositeBranchCondition(CCode);
11856 CC = DAG.getConstant(CCode, MVT::i8);
11862 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11863 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11864 // It should be transformed during dag combiner except when the condition
11865 // is set by a arithmetics with overflow node.
11866 X86::CondCode CCode =
11867 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11868 CCode = X86::GetOppositeBranchCondition(CCode);
11869 CC = DAG.getConstant(CCode, MVT::i8);
11870 Cond = Cond.getOperand(0).getOperand(1);
11872 } else if (Cond.getOpcode() == ISD::SETCC &&
11873 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11874 // For FCMP_OEQ, we can emit
11875 // two branches instead of an explicit AND instruction with a
11876 // separate test. However, we only do this if this block doesn't
11877 // have a fall-through edge, because this requires an explicit
11878 // jmp when the condition is false.
11879 if (Op.getNode()->hasOneUse()) {
11880 SDNode *User = *Op.getNode()->use_begin();
11881 // Look for an unconditional branch following this conditional branch.
11882 // We need this because we need to reverse the successors in order
11883 // to implement FCMP_OEQ.
11884 if (User->getOpcode() == ISD::BR) {
11885 SDValue FalseBB = User->getOperand(1);
11887 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11888 assert(NewBR == User);
11892 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11893 Cond.getOperand(0), Cond.getOperand(1));
11894 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11895 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11896 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11897 Chain, Dest, CC, Cmp);
11898 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11903 } else if (Cond.getOpcode() == ISD::SETCC &&
11904 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11905 // For FCMP_UNE, we can emit
11906 // two branches instead of an explicit AND instruction with a
11907 // separate test. However, we only do this if this block doesn't
11908 // have a fall-through edge, because this requires an explicit
11909 // jmp when the condition is false.
11910 if (Op.getNode()->hasOneUse()) {
11911 SDNode *User = *Op.getNode()->use_begin();
11912 // Look for an unconditional branch following this conditional branch.
11913 // We need this because we need to reverse the successors in order
11914 // to implement FCMP_UNE.
11915 if (User->getOpcode() == ISD::BR) {
11916 SDValue FalseBB = User->getOperand(1);
11918 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11919 assert(NewBR == User);
11922 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11923 Cond.getOperand(0), Cond.getOperand(1));
11924 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11925 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11926 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11927 Chain, Dest, CC, Cmp);
11928 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11938 // Look pass the truncate if the high bits are known zero.
11939 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11940 Cond = Cond.getOperand(0);
11942 // We know the result of AND is compared against zero. Try to match
11944 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11945 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11946 if (NewSetCC.getNode()) {
11947 CC = NewSetCC.getOperand(0);
11948 Cond = NewSetCC.getOperand(1);
11955 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11956 CC = DAG.getConstant(X86Cond, MVT::i8);
11957 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11959 Cond = ConvertCmpIfNecessary(Cond, DAG);
11960 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11961 Chain, Dest, CC, Cond);
11964 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11965 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11966 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11967 // that the guard pages used by the OS virtual memory manager are allocated in
11968 // correct sequence.
11970 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11971 SelectionDAG &DAG) const {
11972 MachineFunction &MF = DAG.getMachineFunction();
11973 bool SplitStack = MF.shouldSplitStack();
11974 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11979 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11980 SDNode* Node = Op.getNode();
11982 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11983 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11984 " not tell us which reg is the stack pointer!");
11985 EVT VT = Node->getValueType(0);
11986 SDValue Tmp1 = SDValue(Node, 0);
11987 SDValue Tmp2 = SDValue(Node, 1);
11988 SDValue Tmp3 = Node->getOperand(2);
11989 SDValue Chain = Tmp1.getOperand(0);
11991 // Chain the dynamic stack allocation so that it doesn't modify the stack
11992 // pointer when other instructions are using the stack.
11993 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11996 SDValue Size = Tmp2.getOperand(1);
11997 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11998 Chain = SP.getValue(1);
11999 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
12000 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
12001 unsigned StackAlign = TFI.getStackAlignment();
12002 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
12003 if (Align > StackAlign)
12004 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
12005 DAG.getConstant(-(uint64_t)Align, VT));
12006 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
12008 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
12009 DAG.getIntPtrConstant(0, true), SDValue(),
12012 SDValue Ops[2] = { Tmp1, Tmp2 };
12013 return DAG.getMergeValues(Ops, dl);
12017 SDValue Chain = Op.getOperand(0);
12018 SDValue Size = Op.getOperand(1);
12019 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12020 EVT VT = Op.getNode()->getValueType(0);
12022 bool Is64Bit = Subtarget->is64Bit();
12023 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
12026 MachineRegisterInfo &MRI = MF.getRegInfo();
12029 // The 64 bit implementation of segmented stacks needs to clobber both r10
12030 // r11. This makes it impossible to use it along with nested parameters.
12031 const Function *F = MF.getFunction();
12033 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
12035 if (I->hasNestAttr())
12036 report_fatal_error("Cannot use segmented stacks with functions that "
12037 "have nested arguments.");
12040 const TargetRegisterClass *AddrRegClass =
12041 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
12042 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
12043 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
12044 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
12045 DAG.getRegister(Vreg, SPTy));
12046 SDValue Ops1[2] = { Value, Chain };
12047 return DAG.getMergeValues(Ops1, dl);
12050 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
12052 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
12053 Flag = Chain.getValue(1);
12054 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12056 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
12058 const X86RegisterInfo *RegInfo =
12059 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
12060 unsigned SPReg = RegInfo->getStackRegister();
12061 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
12062 Chain = SP.getValue(1);
12065 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
12066 DAG.getConstant(-(uint64_t)Align, VT));
12067 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
12070 SDValue Ops1[2] = { SP, Chain };
12071 return DAG.getMergeValues(Ops1, dl);
12075 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
12076 MachineFunction &MF = DAG.getMachineFunction();
12077 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
12079 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
12082 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
12083 // vastart just stores the address of the VarArgsFrameIndex slot into the
12084 // memory location argument.
12085 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
12087 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
12088 MachinePointerInfo(SV), false, false, 0);
12092 // gp_offset (0 - 6 * 8)
12093 // fp_offset (48 - 48 + 8 * 16)
12094 // overflow_arg_area (point to parameters coming in memory).
12096 SmallVector<SDValue, 8> MemOps;
12097 SDValue FIN = Op.getOperand(1);
12099 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
12100 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
12102 FIN, MachinePointerInfo(SV), false, false, 0);
12103 MemOps.push_back(Store);
12106 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12107 FIN, DAG.getIntPtrConstant(4));
12108 Store = DAG.getStore(Op.getOperand(0), DL,
12109 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
12111 FIN, MachinePointerInfo(SV, 4), false, false, 0);
12112 MemOps.push_back(Store);
12114 // Store ptr to overflow_arg_area
12115 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12116 FIN, DAG.getIntPtrConstant(4));
12117 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
12119 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
12120 MachinePointerInfo(SV, 8),
12122 MemOps.push_back(Store);
12124 // Store ptr to reg_save_area.
12125 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12126 FIN, DAG.getIntPtrConstant(8));
12127 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
12129 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
12130 MachinePointerInfo(SV, 16), false, false, 0);
12131 MemOps.push_back(Store);
12132 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
12135 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
12136 assert(Subtarget->is64Bit() &&
12137 "LowerVAARG only handles 64-bit va_arg!");
12138 assert((Subtarget->isTargetLinux() ||
12139 Subtarget->isTargetDarwin()) &&
12140 "Unhandled target in LowerVAARG");
12141 assert(Op.getNode()->getNumOperands() == 4);
12142 SDValue Chain = Op.getOperand(0);
12143 SDValue SrcPtr = Op.getOperand(1);
12144 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
12145 unsigned Align = Op.getConstantOperandVal(3);
12148 EVT ArgVT = Op.getNode()->getValueType(0);
12149 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12150 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
12153 // Decide which area this value should be read from.
12154 // TODO: Implement the AMD64 ABI in its entirety. This simple
12155 // selection mechanism works only for the basic types.
12156 if (ArgVT == MVT::f80) {
12157 llvm_unreachable("va_arg for f80 not yet implemented");
12158 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
12159 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
12160 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
12161 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
12163 llvm_unreachable("Unhandled argument type in LowerVAARG");
12166 if (ArgMode == 2) {
12167 // Sanity Check: Make sure using fp_offset makes sense.
12168 assert(!DAG.getTarget().Options.UseSoftFloat &&
12169 !(DAG.getMachineFunction()
12170 .getFunction()->getAttributes()
12171 .hasAttribute(AttributeSet::FunctionIndex,
12172 Attribute::NoImplicitFloat)) &&
12173 Subtarget->hasSSE1());
12176 // Insert VAARG_64 node into the DAG
12177 // VAARG_64 returns two values: Variable Argument Address, Chain
12178 SmallVector<SDValue, 11> InstOps;
12179 InstOps.push_back(Chain);
12180 InstOps.push_back(SrcPtr);
12181 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
12182 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
12183 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
12184 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
12185 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
12186 VTs, InstOps, MVT::i64,
12187 MachinePointerInfo(SV),
12189 /*Volatile=*/false,
12191 /*WriteMem=*/true);
12192 Chain = VAARG.getValue(1);
12194 // Load the next argument and return it
12195 return DAG.getLoad(ArgVT, dl,
12198 MachinePointerInfo(),
12199 false, false, false, 0);
12202 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
12203 SelectionDAG &DAG) {
12204 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
12205 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
12206 SDValue Chain = Op.getOperand(0);
12207 SDValue DstPtr = Op.getOperand(1);
12208 SDValue SrcPtr = Op.getOperand(2);
12209 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
12210 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12213 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
12214 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
12216 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
12219 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
12220 // amount is a constant. Takes immediate version of shift as input.
12221 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
12222 SDValue SrcOp, uint64_t ShiftAmt,
12223 SelectionDAG &DAG) {
12224 MVT ElementType = VT.getVectorElementType();
12226 // Fold this packed shift into its first operand if ShiftAmt is 0.
12230 // Check for ShiftAmt >= element width
12231 if (ShiftAmt >= ElementType.getSizeInBits()) {
12232 if (Opc == X86ISD::VSRAI)
12233 ShiftAmt = ElementType.getSizeInBits() - 1;
12235 return DAG.getConstant(0, VT);
12238 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
12239 && "Unknown target vector shift-by-constant node");
12241 // Fold this packed vector shift into a build vector if SrcOp is a
12242 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
12243 if (VT == SrcOp.getSimpleValueType() &&
12244 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
12245 SmallVector<SDValue, 8> Elts;
12246 unsigned NumElts = SrcOp->getNumOperands();
12247 ConstantSDNode *ND;
12250 default: llvm_unreachable(nullptr);
12251 case X86ISD::VSHLI:
12252 for (unsigned i=0; i!=NumElts; ++i) {
12253 SDValue CurrentOp = SrcOp->getOperand(i);
12254 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12255 Elts.push_back(CurrentOp);
12258 ND = cast<ConstantSDNode>(CurrentOp);
12259 const APInt &C = ND->getAPIntValue();
12260 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
12263 case X86ISD::VSRLI:
12264 for (unsigned i=0; i!=NumElts; ++i) {
12265 SDValue CurrentOp = SrcOp->getOperand(i);
12266 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12267 Elts.push_back(CurrentOp);
12270 ND = cast<ConstantSDNode>(CurrentOp);
12271 const APInt &C = ND->getAPIntValue();
12272 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
12275 case X86ISD::VSRAI:
12276 for (unsigned i=0; i!=NumElts; ++i) {
12277 SDValue CurrentOp = SrcOp->getOperand(i);
12278 if (CurrentOp->getOpcode() == ISD::UNDEF) {
12279 Elts.push_back(CurrentOp);
12282 ND = cast<ConstantSDNode>(CurrentOp);
12283 const APInt &C = ND->getAPIntValue();
12284 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
12289 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
12292 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
12295 // getTargetVShiftNode - Handle vector element shifts where the shift amount
12296 // may or may not be a constant. Takes immediate version of shift as input.
12297 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
12298 SDValue SrcOp, SDValue ShAmt,
12299 SelectionDAG &DAG) {
12300 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
12302 // Catch shift-by-constant.
12303 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12304 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12305 CShAmt->getZExtValue(), DAG);
12307 // Change opcode to non-immediate version
12309 default: llvm_unreachable("Unknown target vector shift node");
12310 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12311 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12312 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12315 // Need to build a vector containing shift amount
12316 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12319 ShOps[1] = DAG.getConstant(0, MVT::i32);
12320 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12321 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12323 // The return type has to be a 128-bit type with the same element
12324 // type as the input type.
12325 MVT EltVT = VT.getVectorElementType();
12326 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12328 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12329 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12332 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12334 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12336 default: return SDValue(); // Don't custom lower most intrinsics.
12337 // Comparison intrinsics.
12338 case Intrinsic::x86_sse_comieq_ss:
12339 case Intrinsic::x86_sse_comilt_ss:
12340 case Intrinsic::x86_sse_comile_ss:
12341 case Intrinsic::x86_sse_comigt_ss:
12342 case Intrinsic::x86_sse_comige_ss:
12343 case Intrinsic::x86_sse_comineq_ss:
12344 case Intrinsic::x86_sse_ucomieq_ss:
12345 case Intrinsic::x86_sse_ucomilt_ss:
12346 case Intrinsic::x86_sse_ucomile_ss:
12347 case Intrinsic::x86_sse_ucomigt_ss:
12348 case Intrinsic::x86_sse_ucomige_ss:
12349 case Intrinsic::x86_sse_ucomineq_ss:
12350 case Intrinsic::x86_sse2_comieq_sd:
12351 case Intrinsic::x86_sse2_comilt_sd:
12352 case Intrinsic::x86_sse2_comile_sd:
12353 case Intrinsic::x86_sse2_comigt_sd:
12354 case Intrinsic::x86_sse2_comige_sd:
12355 case Intrinsic::x86_sse2_comineq_sd:
12356 case Intrinsic::x86_sse2_ucomieq_sd:
12357 case Intrinsic::x86_sse2_ucomilt_sd:
12358 case Intrinsic::x86_sse2_ucomile_sd:
12359 case Intrinsic::x86_sse2_ucomigt_sd:
12360 case Intrinsic::x86_sse2_ucomige_sd:
12361 case Intrinsic::x86_sse2_ucomineq_sd: {
12365 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12366 case Intrinsic::x86_sse_comieq_ss:
12367 case Intrinsic::x86_sse2_comieq_sd:
12368 Opc = X86ISD::COMI;
12371 case Intrinsic::x86_sse_comilt_ss:
12372 case Intrinsic::x86_sse2_comilt_sd:
12373 Opc = X86ISD::COMI;
12376 case Intrinsic::x86_sse_comile_ss:
12377 case Intrinsic::x86_sse2_comile_sd:
12378 Opc = X86ISD::COMI;
12381 case Intrinsic::x86_sse_comigt_ss:
12382 case Intrinsic::x86_sse2_comigt_sd:
12383 Opc = X86ISD::COMI;
12386 case Intrinsic::x86_sse_comige_ss:
12387 case Intrinsic::x86_sse2_comige_sd:
12388 Opc = X86ISD::COMI;
12391 case Intrinsic::x86_sse_comineq_ss:
12392 case Intrinsic::x86_sse2_comineq_sd:
12393 Opc = X86ISD::COMI;
12396 case Intrinsic::x86_sse_ucomieq_ss:
12397 case Intrinsic::x86_sse2_ucomieq_sd:
12398 Opc = X86ISD::UCOMI;
12401 case Intrinsic::x86_sse_ucomilt_ss:
12402 case Intrinsic::x86_sse2_ucomilt_sd:
12403 Opc = X86ISD::UCOMI;
12406 case Intrinsic::x86_sse_ucomile_ss:
12407 case Intrinsic::x86_sse2_ucomile_sd:
12408 Opc = X86ISD::UCOMI;
12411 case Intrinsic::x86_sse_ucomigt_ss:
12412 case Intrinsic::x86_sse2_ucomigt_sd:
12413 Opc = X86ISD::UCOMI;
12416 case Intrinsic::x86_sse_ucomige_ss:
12417 case Intrinsic::x86_sse2_ucomige_sd:
12418 Opc = X86ISD::UCOMI;
12421 case Intrinsic::x86_sse_ucomineq_ss:
12422 case Intrinsic::x86_sse2_ucomineq_sd:
12423 Opc = X86ISD::UCOMI;
12428 SDValue LHS = Op.getOperand(1);
12429 SDValue RHS = Op.getOperand(2);
12430 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12431 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12432 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12433 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12434 DAG.getConstant(X86CC, MVT::i8), Cond);
12435 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12438 // Arithmetic intrinsics.
12439 case Intrinsic::x86_sse2_pmulu_dq:
12440 case Intrinsic::x86_avx2_pmulu_dq:
12441 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12442 Op.getOperand(1), Op.getOperand(2));
12444 case Intrinsic::x86_sse41_pmuldq:
12445 case Intrinsic::x86_avx2_pmul_dq:
12446 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12447 Op.getOperand(1), Op.getOperand(2));
12449 case Intrinsic::x86_sse2_pmulhu_w:
12450 case Intrinsic::x86_avx2_pmulhu_w:
12451 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12452 Op.getOperand(1), Op.getOperand(2));
12454 case Intrinsic::x86_sse2_pmulh_w:
12455 case Intrinsic::x86_avx2_pmulh_w:
12456 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12457 Op.getOperand(1), Op.getOperand(2));
12459 // SSE2/AVX2 sub with unsigned saturation intrinsics
12460 case Intrinsic::x86_sse2_psubus_b:
12461 case Intrinsic::x86_sse2_psubus_w:
12462 case Intrinsic::x86_avx2_psubus_b:
12463 case Intrinsic::x86_avx2_psubus_w:
12464 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12465 Op.getOperand(1), Op.getOperand(2));
12467 // SSE3/AVX horizontal add/sub intrinsics
12468 case Intrinsic::x86_sse3_hadd_ps:
12469 case Intrinsic::x86_sse3_hadd_pd:
12470 case Intrinsic::x86_avx_hadd_ps_256:
12471 case Intrinsic::x86_avx_hadd_pd_256:
12472 case Intrinsic::x86_sse3_hsub_ps:
12473 case Intrinsic::x86_sse3_hsub_pd:
12474 case Intrinsic::x86_avx_hsub_ps_256:
12475 case Intrinsic::x86_avx_hsub_pd_256:
12476 case Intrinsic::x86_ssse3_phadd_w_128:
12477 case Intrinsic::x86_ssse3_phadd_d_128:
12478 case Intrinsic::x86_avx2_phadd_w:
12479 case Intrinsic::x86_avx2_phadd_d:
12480 case Intrinsic::x86_ssse3_phsub_w_128:
12481 case Intrinsic::x86_ssse3_phsub_d_128:
12482 case Intrinsic::x86_avx2_phsub_w:
12483 case Intrinsic::x86_avx2_phsub_d: {
12486 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12487 case Intrinsic::x86_sse3_hadd_ps:
12488 case Intrinsic::x86_sse3_hadd_pd:
12489 case Intrinsic::x86_avx_hadd_ps_256:
12490 case Intrinsic::x86_avx_hadd_pd_256:
12491 Opcode = X86ISD::FHADD;
12493 case Intrinsic::x86_sse3_hsub_ps:
12494 case Intrinsic::x86_sse3_hsub_pd:
12495 case Intrinsic::x86_avx_hsub_ps_256:
12496 case Intrinsic::x86_avx_hsub_pd_256:
12497 Opcode = X86ISD::FHSUB;
12499 case Intrinsic::x86_ssse3_phadd_w_128:
12500 case Intrinsic::x86_ssse3_phadd_d_128:
12501 case Intrinsic::x86_avx2_phadd_w:
12502 case Intrinsic::x86_avx2_phadd_d:
12503 Opcode = X86ISD::HADD;
12505 case Intrinsic::x86_ssse3_phsub_w_128:
12506 case Intrinsic::x86_ssse3_phsub_d_128:
12507 case Intrinsic::x86_avx2_phsub_w:
12508 case Intrinsic::x86_avx2_phsub_d:
12509 Opcode = X86ISD::HSUB;
12512 return DAG.getNode(Opcode, dl, Op.getValueType(),
12513 Op.getOperand(1), Op.getOperand(2));
12516 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12517 case Intrinsic::x86_sse2_pmaxu_b:
12518 case Intrinsic::x86_sse41_pmaxuw:
12519 case Intrinsic::x86_sse41_pmaxud:
12520 case Intrinsic::x86_avx2_pmaxu_b:
12521 case Intrinsic::x86_avx2_pmaxu_w:
12522 case Intrinsic::x86_avx2_pmaxu_d:
12523 case Intrinsic::x86_sse2_pminu_b:
12524 case Intrinsic::x86_sse41_pminuw:
12525 case Intrinsic::x86_sse41_pminud:
12526 case Intrinsic::x86_avx2_pminu_b:
12527 case Intrinsic::x86_avx2_pminu_w:
12528 case Intrinsic::x86_avx2_pminu_d:
12529 case Intrinsic::x86_sse41_pmaxsb:
12530 case Intrinsic::x86_sse2_pmaxs_w:
12531 case Intrinsic::x86_sse41_pmaxsd:
12532 case Intrinsic::x86_avx2_pmaxs_b:
12533 case Intrinsic::x86_avx2_pmaxs_w:
12534 case Intrinsic::x86_avx2_pmaxs_d:
12535 case Intrinsic::x86_sse41_pminsb:
12536 case Intrinsic::x86_sse2_pmins_w:
12537 case Intrinsic::x86_sse41_pminsd:
12538 case Intrinsic::x86_avx2_pmins_b:
12539 case Intrinsic::x86_avx2_pmins_w:
12540 case Intrinsic::x86_avx2_pmins_d: {
12543 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12544 case Intrinsic::x86_sse2_pmaxu_b:
12545 case Intrinsic::x86_sse41_pmaxuw:
12546 case Intrinsic::x86_sse41_pmaxud:
12547 case Intrinsic::x86_avx2_pmaxu_b:
12548 case Intrinsic::x86_avx2_pmaxu_w:
12549 case Intrinsic::x86_avx2_pmaxu_d:
12550 Opcode = X86ISD::UMAX;
12552 case Intrinsic::x86_sse2_pminu_b:
12553 case Intrinsic::x86_sse41_pminuw:
12554 case Intrinsic::x86_sse41_pminud:
12555 case Intrinsic::x86_avx2_pminu_b:
12556 case Intrinsic::x86_avx2_pminu_w:
12557 case Intrinsic::x86_avx2_pminu_d:
12558 Opcode = X86ISD::UMIN;
12560 case Intrinsic::x86_sse41_pmaxsb:
12561 case Intrinsic::x86_sse2_pmaxs_w:
12562 case Intrinsic::x86_sse41_pmaxsd:
12563 case Intrinsic::x86_avx2_pmaxs_b:
12564 case Intrinsic::x86_avx2_pmaxs_w:
12565 case Intrinsic::x86_avx2_pmaxs_d:
12566 Opcode = X86ISD::SMAX;
12568 case Intrinsic::x86_sse41_pminsb:
12569 case Intrinsic::x86_sse2_pmins_w:
12570 case Intrinsic::x86_sse41_pminsd:
12571 case Intrinsic::x86_avx2_pmins_b:
12572 case Intrinsic::x86_avx2_pmins_w:
12573 case Intrinsic::x86_avx2_pmins_d:
12574 Opcode = X86ISD::SMIN;
12577 return DAG.getNode(Opcode, dl, Op.getValueType(),
12578 Op.getOperand(1), Op.getOperand(2));
12581 // SSE/SSE2/AVX floating point max/min intrinsics.
12582 case Intrinsic::x86_sse_max_ps:
12583 case Intrinsic::x86_sse2_max_pd:
12584 case Intrinsic::x86_avx_max_ps_256:
12585 case Intrinsic::x86_avx_max_pd_256:
12586 case Intrinsic::x86_sse_min_ps:
12587 case Intrinsic::x86_sse2_min_pd:
12588 case Intrinsic::x86_avx_min_ps_256:
12589 case Intrinsic::x86_avx_min_pd_256: {
12592 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12593 case Intrinsic::x86_sse_max_ps:
12594 case Intrinsic::x86_sse2_max_pd:
12595 case Intrinsic::x86_avx_max_ps_256:
12596 case Intrinsic::x86_avx_max_pd_256:
12597 Opcode = X86ISD::FMAX;
12599 case Intrinsic::x86_sse_min_ps:
12600 case Intrinsic::x86_sse2_min_pd:
12601 case Intrinsic::x86_avx_min_ps_256:
12602 case Intrinsic::x86_avx_min_pd_256:
12603 Opcode = X86ISD::FMIN;
12606 return DAG.getNode(Opcode, dl, Op.getValueType(),
12607 Op.getOperand(1), Op.getOperand(2));
12610 // AVX2 variable shift intrinsics
12611 case Intrinsic::x86_avx2_psllv_d:
12612 case Intrinsic::x86_avx2_psllv_q:
12613 case Intrinsic::x86_avx2_psllv_d_256:
12614 case Intrinsic::x86_avx2_psllv_q_256:
12615 case Intrinsic::x86_avx2_psrlv_d:
12616 case Intrinsic::x86_avx2_psrlv_q:
12617 case Intrinsic::x86_avx2_psrlv_d_256:
12618 case Intrinsic::x86_avx2_psrlv_q_256:
12619 case Intrinsic::x86_avx2_psrav_d:
12620 case Intrinsic::x86_avx2_psrav_d_256: {
12623 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12624 case Intrinsic::x86_avx2_psllv_d:
12625 case Intrinsic::x86_avx2_psllv_q:
12626 case Intrinsic::x86_avx2_psllv_d_256:
12627 case Intrinsic::x86_avx2_psllv_q_256:
12630 case Intrinsic::x86_avx2_psrlv_d:
12631 case Intrinsic::x86_avx2_psrlv_q:
12632 case Intrinsic::x86_avx2_psrlv_d_256:
12633 case Intrinsic::x86_avx2_psrlv_q_256:
12636 case Intrinsic::x86_avx2_psrav_d:
12637 case Intrinsic::x86_avx2_psrav_d_256:
12641 return DAG.getNode(Opcode, dl, Op.getValueType(),
12642 Op.getOperand(1), Op.getOperand(2));
12645 case Intrinsic::x86_sse2_packssdw_128:
12646 case Intrinsic::x86_sse2_packsswb_128:
12647 case Intrinsic::x86_avx2_packssdw:
12648 case Intrinsic::x86_avx2_packsswb:
12649 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
12650 Op.getOperand(1), Op.getOperand(2));
12652 case Intrinsic::x86_sse2_packuswb_128:
12653 case Intrinsic::x86_sse41_packusdw:
12654 case Intrinsic::x86_avx2_packuswb:
12655 case Intrinsic::x86_avx2_packusdw:
12656 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
12657 Op.getOperand(1), Op.getOperand(2));
12659 case Intrinsic::x86_ssse3_pshuf_b_128:
12660 case Intrinsic::x86_avx2_pshuf_b:
12661 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12662 Op.getOperand(1), Op.getOperand(2));
12664 case Intrinsic::x86_ssse3_psign_b_128:
12665 case Intrinsic::x86_ssse3_psign_w_128:
12666 case Intrinsic::x86_ssse3_psign_d_128:
12667 case Intrinsic::x86_avx2_psign_b:
12668 case Intrinsic::x86_avx2_psign_w:
12669 case Intrinsic::x86_avx2_psign_d:
12670 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12671 Op.getOperand(1), Op.getOperand(2));
12673 case Intrinsic::x86_sse41_insertps:
12674 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12675 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12677 case Intrinsic::x86_avx_vperm2f128_ps_256:
12678 case Intrinsic::x86_avx_vperm2f128_pd_256:
12679 case Intrinsic::x86_avx_vperm2f128_si_256:
12680 case Intrinsic::x86_avx2_vperm2i128:
12681 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12682 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12684 case Intrinsic::x86_avx2_permd:
12685 case Intrinsic::x86_avx2_permps:
12686 // Operands intentionally swapped. Mask is last operand to intrinsic,
12687 // but second operand for node/instruction.
12688 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12689 Op.getOperand(2), Op.getOperand(1));
12691 case Intrinsic::x86_sse_sqrt_ps:
12692 case Intrinsic::x86_sse2_sqrt_pd:
12693 case Intrinsic::x86_avx_sqrt_ps_256:
12694 case Intrinsic::x86_avx_sqrt_pd_256:
12695 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12697 // ptest and testp intrinsics. The intrinsic these come from are designed to
12698 // return an integer value, not just an instruction so lower it to the ptest
12699 // or testp pattern and a setcc for the result.
12700 case Intrinsic::x86_sse41_ptestz:
12701 case Intrinsic::x86_sse41_ptestc:
12702 case Intrinsic::x86_sse41_ptestnzc:
12703 case Intrinsic::x86_avx_ptestz_256:
12704 case Intrinsic::x86_avx_ptestc_256:
12705 case Intrinsic::x86_avx_ptestnzc_256:
12706 case Intrinsic::x86_avx_vtestz_ps:
12707 case Intrinsic::x86_avx_vtestc_ps:
12708 case Intrinsic::x86_avx_vtestnzc_ps:
12709 case Intrinsic::x86_avx_vtestz_pd:
12710 case Intrinsic::x86_avx_vtestc_pd:
12711 case Intrinsic::x86_avx_vtestnzc_pd:
12712 case Intrinsic::x86_avx_vtestz_ps_256:
12713 case Intrinsic::x86_avx_vtestc_ps_256:
12714 case Intrinsic::x86_avx_vtestnzc_ps_256:
12715 case Intrinsic::x86_avx_vtestz_pd_256:
12716 case Intrinsic::x86_avx_vtestc_pd_256:
12717 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12718 bool IsTestPacked = false;
12721 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12722 case Intrinsic::x86_avx_vtestz_ps:
12723 case Intrinsic::x86_avx_vtestz_pd:
12724 case Intrinsic::x86_avx_vtestz_ps_256:
12725 case Intrinsic::x86_avx_vtestz_pd_256:
12726 IsTestPacked = true; // Fallthrough
12727 case Intrinsic::x86_sse41_ptestz:
12728 case Intrinsic::x86_avx_ptestz_256:
12730 X86CC = X86::COND_E;
12732 case Intrinsic::x86_avx_vtestc_ps:
12733 case Intrinsic::x86_avx_vtestc_pd:
12734 case Intrinsic::x86_avx_vtestc_ps_256:
12735 case Intrinsic::x86_avx_vtestc_pd_256:
12736 IsTestPacked = true; // Fallthrough
12737 case Intrinsic::x86_sse41_ptestc:
12738 case Intrinsic::x86_avx_ptestc_256:
12740 X86CC = X86::COND_B;
12742 case Intrinsic::x86_avx_vtestnzc_ps:
12743 case Intrinsic::x86_avx_vtestnzc_pd:
12744 case Intrinsic::x86_avx_vtestnzc_ps_256:
12745 case Intrinsic::x86_avx_vtestnzc_pd_256:
12746 IsTestPacked = true; // Fallthrough
12747 case Intrinsic::x86_sse41_ptestnzc:
12748 case Intrinsic::x86_avx_ptestnzc_256:
12750 X86CC = X86::COND_A;
12754 SDValue LHS = Op.getOperand(1);
12755 SDValue RHS = Op.getOperand(2);
12756 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12757 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12758 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12759 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12760 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12762 case Intrinsic::x86_avx512_kortestz_w:
12763 case Intrinsic::x86_avx512_kortestc_w: {
12764 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12765 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12766 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12767 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12768 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12769 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12770 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12773 // SSE/AVX shift intrinsics
12774 case Intrinsic::x86_sse2_psll_w:
12775 case Intrinsic::x86_sse2_psll_d:
12776 case Intrinsic::x86_sse2_psll_q:
12777 case Intrinsic::x86_avx2_psll_w:
12778 case Intrinsic::x86_avx2_psll_d:
12779 case Intrinsic::x86_avx2_psll_q:
12780 case Intrinsic::x86_sse2_psrl_w:
12781 case Intrinsic::x86_sse2_psrl_d:
12782 case Intrinsic::x86_sse2_psrl_q:
12783 case Intrinsic::x86_avx2_psrl_w:
12784 case Intrinsic::x86_avx2_psrl_d:
12785 case Intrinsic::x86_avx2_psrl_q:
12786 case Intrinsic::x86_sse2_psra_w:
12787 case Intrinsic::x86_sse2_psra_d:
12788 case Intrinsic::x86_avx2_psra_w:
12789 case Intrinsic::x86_avx2_psra_d: {
12792 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12793 case Intrinsic::x86_sse2_psll_w:
12794 case Intrinsic::x86_sse2_psll_d:
12795 case Intrinsic::x86_sse2_psll_q:
12796 case Intrinsic::x86_avx2_psll_w:
12797 case Intrinsic::x86_avx2_psll_d:
12798 case Intrinsic::x86_avx2_psll_q:
12799 Opcode = X86ISD::VSHL;
12801 case Intrinsic::x86_sse2_psrl_w:
12802 case Intrinsic::x86_sse2_psrl_d:
12803 case Intrinsic::x86_sse2_psrl_q:
12804 case Intrinsic::x86_avx2_psrl_w:
12805 case Intrinsic::x86_avx2_psrl_d:
12806 case Intrinsic::x86_avx2_psrl_q:
12807 Opcode = X86ISD::VSRL;
12809 case Intrinsic::x86_sse2_psra_w:
12810 case Intrinsic::x86_sse2_psra_d:
12811 case Intrinsic::x86_avx2_psra_w:
12812 case Intrinsic::x86_avx2_psra_d:
12813 Opcode = X86ISD::VSRA;
12816 return DAG.getNode(Opcode, dl, Op.getValueType(),
12817 Op.getOperand(1), Op.getOperand(2));
12820 // SSE/AVX immediate shift intrinsics
12821 case Intrinsic::x86_sse2_pslli_w:
12822 case Intrinsic::x86_sse2_pslli_d:
12823 case Intrinsic::x86_sse2_pslli_q:
12824 case Intrinsic::x86_avx2_pslli_w:
12825 case Intrinsic::x86_avx2_pslli_d:
12826 case Intrinsic::x86_avx2_pslli_q:
12827 case Intrinsic::x86_sse2_psrli_w:
12828 case Intrinsic::x86_sse2_psrli_d:
12829 case Intrinsic::x86_sse2_psrli_q:
12830 case Intrinsic::x86_avx2_psrli_w:
12831 case Intrinsic::x86_avx2_psrli_d:
12832 case Intrinsic::x86_avx2_psrli_q:
12833 case Intrinsic::x86_sse2_psrai_w:
12834 case Intrinsic::x86_sse2_psrai_d:
12835 case Intrinsic::x86_avx2_psrai_w:
12836 case Intrinsic::x86_avx2_psrai_d: {
12839 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12840 case Intrinsic::x86_sse2_pslli_w:
12841 case Intrinsic::x86_sse2_pslli_d:
12842 case Intrinsic::x86_sse2_pslli_q:
12843 case Intrinsic::x86_avx2_pslli_w:
12844 case Intrinsic::x86_avx2_pslli_d:
12845 case Intrinsic::x86_avx2_pslli_q:
12846 Opcode = X86ISD::VSHLI;
12848 case Intrinsic::x86_sse2_psrli_w:
12849 case Intrinsic::x86_sse2_psrli_d:
12850 case Intrinsic::x86_sse2_psrli_q:
12851 case Intrinsic::x86_avx2_psrli_w:
12852 case Intrinsic::x86_avx2_psrli_d:
12853 case Intrinsic::x86_avx2_psrli_q:
12854 Opcode = X86ISD::VSRLI;
12856 case Intrinsic::x86_sse2_psrai_w:
12857 case Intrinsic::x86_sse2_psrai_d:
12858 case Intrinsic::x86_avx2_psrai_w:
12859 case Intrinsic::x86_avx2_psrai_d:
12860 Opcode = X86ISD::VSRAI;
12863 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12864 Op.getOperand(1), Op.getOperand(2), DAG);
12867 case Intrinsic::x86_sse42_pcmpistria128:
12868 case Intrinsic::x86_sse42_pcmpestria128:
12869 case Intrinsic::x86_sse42_pcmpistric128:
12870 case Intrinsic::x86_sse42_pcmpestric128:
12871 case Intrinsic::x86_sse42_pcmpistrio128:
12872 case Intrinsic::x86_sse42_pcmpestrio128:
12873 case Intrinsic::x86_sse42_pcmpistris128:
12874 case Intrinsic::x86_sse42_pcmpestris128:
12875 case Intrinsic::x86_sse42_pcmpistriz128:
12876 case Intrinsic::x86_sse42_pcmpestriz128: {
12880 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12881 case Intrinsic::x86_sse42_pcmpistria128:
12882 Opcode = X86ISD::PCMPISTRI;
12883 X86CC = X86::COND_A;
12885 case Intrinsic::x86_sse42_pcmpestria128:
12886 Opcode = X86ISD::PCMPESTRI;
12887 X86CC = X86::COND_A;
12889 case Intrinsic::x86_sse42_pcmpistric128:
12890 Opcode = X86ISD::PCMPISTRI;
12891 X86CC = X86::COND_B;
12893 case Intrinsic::x86_sse42_pcmpestric128:
12894 Opcode = X86ISD::PCMPESTRI;
12895 X86CC = X86::COND_B;
12897 case Intrinsic::x86_sse42_pcmpistrio128:
12898 Opcode = X86ISD::PCMPISTRI;
12899 X86CC = X86::COND_O;
12901 case Intrinsic::x86_sse42_pcmpestrio128:
12902 Opcode = X86ISD::PCMPESTRI;
12903 X86CC = X86::COND_O;
12905 case Intrinsic::x86_sse42_pcmpistris128:
12906 Opcode = X86ISD::PCMPISTRI;
12907 X86CC = X86::COND_S;
12909 case Intrinsic::x86_sse42_pcmpestris128:
12910 Opcode = X86ISD::PCMPESTRI;
12911 X86CC = X86::COND_S;
12913 case Intrinsic::x86_sse42_pcmpistriz128:
12914 Opcode = X86ISD::PCMPISTRI;
12915 X86CC = X86::COND_E;
12917 case Intrinsic::x86_sse42_pcmpestriz128:
12918 Opcode = X86ISD::PCMPESTRI;
12919 X86CC = X86::COND_E;
12922 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12923 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12924 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12925 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12926 DAG.getConstant(X86CC, MVT::i8),
12927 SDValue(PCMP.getNode(), 1));
12928 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12931 case Intrinsic::x86_sse42_pcmpistri128:
12932 case Intrinsic::x86_sse42_pcmpestri128: {
12934 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12935 Opcode = X86ISD::PCMPISTRI;
12937 Opcode = X86ISD::PCMPESTRI;
12939 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12940 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12941 return DAG.getNode(Opcode, dl, VTs, NewOps);
12943 case Intrinsic::x86_fma_vfmadd_ps:
12944 case Intrinsic::x86_fma_vfmadd_pd:
12945 case Intrinsic::x86_fma_vfmsub_ps:
12946 case Intrinsic::x86_fma_vfmsub_pd:
12947 case Intrinsic::x86_fma_vfnmadd_ps:
12948 case Intrinsic::x86_fma_vfnmadd_pd:
12949 case Intrinsic::x86_fma_vfnmsub_ps:
12950 case Intrinsic::x86_fma_vfnmsub_pd:
12951 case Intrinsic::x86_fma_vfmaddsub_ps:
12952 case Intrinsic::x86_fma_vfmaddsub_pd:
12953 case Intrinsic::x86_fma_vfmsubadd_ps:
12954 case Intrinsic::x86_fma_vfmsubadd_pd:
12955 case Intrinsic::x86_fma_vfmadd_ps_256:
12956 case Intrinsic::x86_fma_vfmadd_pd_256:
12957 case Intrinsic::x86_fma_vfmsub_ps_256:
12958 case Intrinsic::x86_fma_vfmsub_pd_256:
12959 case Intrinsic::x86_fma_vfnmadd_ps_256:
12960 case Intrinsic::x86_fma_vfnmadd_pd_256:
12961 case Intrinsic::x86_fma_vfnmsub_ps_256:
12962 case Intrinsic::x86_fma_vfnmsub_pd_256:
12963 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12964 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12965 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12966 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12967 case Intrinsic::x86_fma_vfmadd_ps_512:
12968 case Intrinsic::x86_fma_vfmadd_pd_512:
12969 case Intrinsic::x86_fma_vfmsub_ps_512:
12970 case Intrinsic::x86_fma_vfmsub_pd_512:
12971 case Intrinsic::x86_fma_vfnmadd_ps_512:
12972 case Intrinsic::x86_fma_vfnmadd_pd_512:
12973 case Intrinsic::x86_fma_vfnmsub_ps_512:
12974 case Intrinsic::x86_fma_vfnmsub_pd_512:
12975 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12976 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12977 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12978 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12981 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12982 case Intrinsic::x86_fma_vfmadd_ps:
12983 case Intrinsic::x86_fma_vfmadd_pd:
12984 case Intrinsic::x86_fma_vfmadd_ps_256:
12985 case Intrinsic::x86_fma_vfmadd_pd_256:
12986 case Intrinsic::x86_fma_vfmadd_ps_512:
12987 case Intrinsic::x86_fma_vfmadd_pd_512:
12988 Opc = X86ISD::FMADD;
12990 case Intrinsic::x86_fma_vfmsub_ps:
12991 case Intrinsic::x86_fma_vfmsub_pd:
12992 case Intrinsic::x86_fma_vfmsub_ps_256:
12993 case Intrinsic::x86_fma_vfmsub_pd_256:
12994 case Intrinsic::x86_fma_vfmsub_ps_512:
12995 case Intrinsic::x86_fma_vfmsub_pd_512:
12996 Opc = X86ISD::FMSUB;
12998 case Intrinsic::x86_fma_vfnmadd_ps:
12999 case Intrinsic::x86_fma_vfnmadd_pd:
13000 case Intrinsic::x86_fma_vfnmadd_ps_256:
13001 case Intrinsic::x86_fma_vfnmadd_pd_256:
13002 case Intrinsic::x86_fma_vfnmadd_ps_512:
13003 case Intrinsic::x86_fma_vfnmadd_pd_512:
13004 Opc = X86ISD::FNMADD;
13006 case Intrinsic::x86_fma_vfnmsub_ps:
13007 case Intrinsic::x86_fma_vfnmsub_pd:
13008 case Intrinsic::x86_fma_vfnmsub_ps_256:
13009 case Intrinsic::x86_fma_vfnmsub_pd_256:
13010 case Intrinsic::x86_fma_vfnmsub_ps_512:
13011 case Intrinsic::x86_fma_vfnmsub_pd_512:
13012 Opc = X86ISD::FNMSUB;
13014 case Intrinsic::x86_fma_vfmaddsub_ps:
13015 case Intrinsic::x86_fma_vfmaddsub_pd:
13016 case Intrinsic::x86_fma_vfmaddsub_ps_256:
13017 case Intrinsic::x86_fma_vfmaddsub_pd_256:
13018 case Intrinsic::x86_fma_vfmaddsub_ps_512:
13019 case Intrinsic::x86_fma_vfmaddsub_pd_512:
13020 Opc = X86ISD::FMADDSUB;
13022 case Intrinsic::x86_fma_vfmsubadd_ps:
13023 case Intrinsic::x86_fma_vfmsubadd_pd:
13024 case Intrinsic::x86_fma_vfmsubadd_ps_256:
13025 case Intrinsic::x86_fma_vfmsubadd_pd_256:
13026 case Intrinsic::x86_fma_vfmsubadd_ps_512:
13027 case Intrinsic::x86_fma_vfmsubadd_pd_512:
13028 Opc = X86ISD::FMSUBADD;
13032 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
13033 Op.getOperand(2), Op.getOperand(3));
13038 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
13039 SDValue Src, SDValue Mask, SDValue Base,
13040 SDValue Index, SDValue ScaleOp, SDValue Chain,
13041 const X86Subtarget * Subtarget) {
13043 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
13044 assert(C && "Invalid scale type");
13045 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
13046 EVT MaskVT = MVT::getVectorVT(MVT::i1,
13047 Index.getSimpleValueType().getVectorNumElements());
13049 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
13051 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
13053 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
13054 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
13055 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
13056 SDValue Segment = DAG.getRegister(0, MVT::i32);
13057 if (Src.getOpcode() == ISD::UNDEF)
13058 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
13059 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
13060 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
13061 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
13062 return DAG.getMergeValues(RetOps, dl);
13065 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
13066 SDValue Src, SDValue Mask, SDValue Base,
13067 SDValue Index, SDValue ScaleOp, SDValue Chain) {
13069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
13070 assert(C && "Invalid scale type");
13071 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
13072 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
13073 SDValue Segment = DAG.getRegister(0, MVT::i32);
13074 EVT MaskVT = MVT::getVectorVT(MVT::i1,
13075 Index.getSimpleValueType().getVectorNumElements());
13077 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
13079 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
13081 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
13082 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
13083 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
13084 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
13085 return SDValue(Res, 1);
13088 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
13089 SDValue Mask, SDValue Base, SDValue Index,
13090 SDValue ScaleOp, SDValue Chain) {
13092 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
13093 assert(C && "Invalid scale type");
13094 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
13095 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
13096 SDValue Segment = DAG.getRegister(0, MVT::i32);
13098 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
13100 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
13102 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
13104 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
13105 //SDVTList VTs = DAG.getVTList(MVT::Other);
13106 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
13107 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
13108 return SDValue(Res, 0);
13111 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
13112 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
13113 // also used to custom lower READCYCLECOUNTER nodes.
13114 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
13115 SelectionDAG &DAG, const X86Subtarget *Subtarget,
13116 SmallVectorImpl<SDValue> &Results) {
13117 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13118 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
13121 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
13122 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
13123 // and the EAX register is loaded with the low-order 32 bits.
13124 if (Subtarget->is64Bit()) {
13125 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
13126 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
13129 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
13130 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
13133 SDValue Chain = HI.getValue(1);
13135 if (Opcode == X86ISD::RDTSCP_DAG) {
13136 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
13138 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
13139 // the ECX register. Add 'ecx' explicitly to the chain.
13140 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
13142 // Explicitly store the content of ECX at the location passed in input
13143 // to the 'rdtscp' intrinsic.
13144 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
13145 MachinePointerInfo(), false, false, 0);
13148 if (Subtarget->is64Bit()) {
13149 // The EDX register is loaded with the high-order 32 bits of the MSR, and
13150 // the EAX register is loaded with the low-order 32 bits.
13151 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
13152 DAG.getConstant(32, MVT::i8));
13153 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
13154 Results.push_back(Chain);
13158 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13159 SDValue Ops[] = { LO, HI };
13160 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
13161 Results.push_back(Pair);
13162 Results.push_back(Chain);
13165 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13166 SelectionDAG &DAG) {
13167 SmallVector<SDValue, 2> Results;
13169 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
13171 return DAG.getMergeValues(Results, DL);
13174 enum IntrinsicType {
13175 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
13178 struct IntrinsicData {
13179 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
13180 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
13181 IntrinsicType Type;
13186 std::map < unsigned, IntrinsicData> IntrMap;
13187 static void InitIntinsicsMap() {
13188 static bool Initialized = false;
13191 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13192 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13193 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13194 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13195 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
13196 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
13197 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
13198 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
13199 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
13200 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
13201 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
13202 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
13203 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
13204 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
13205 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
13206 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
13207 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
13208 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
13210 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
13211 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
13212 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
13213 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
13214 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
13215 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
13216 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
13217 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
13218 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
13219 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
13220 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
13221 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
13222 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
13223 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
13224 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
13225 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
13227 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
13228 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
13229 X86::VGATHERPF1QPSm)));
13230 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
13231 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
13232 X86::VGATHERPF1QPDm)));
13233 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
13234 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
13235 X86::VGATHERPF1DPDm)));
13236 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
13237 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
13238 X86::VGATHERPF1DPSm)));
13239 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
13240 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
13241 X86::VSCATTERPF1QPSm)));
13242 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
13243 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
13244 X86::VSCATTERPF1QPDm)));
13245 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
13246 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
13247 X86::VSCATTERPF1DPDm)));
13248 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
13249 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
13250 X86::VSCATTERPF1DPSm)));
13251 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
13252 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13253 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
13254 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13255 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
13256 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13257 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
13258 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13259 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
13260 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13261 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
13262 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13263 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
13264 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
13265 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
13266 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
13267 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
13268 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
13269 Initialized = true;
13272 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
13273 SelectionDAG &DAG) {
13274 InitIntinsicsMap();
13275 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13276 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
13277 if (itr == IntrMap.end())
13281 IntrinsicData Intr = itr->second;
13282 switch(Intr.Type) {
13285 // Emit the node with the right value type.
13286 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
13287 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
13289 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
13290 // Otherwise return the value from Rand, which is always 0, casted to i32.
13291 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
13292 DAG.getConstant(1, Op->getValueType(1)),
13293 DAG.getConstant(X86::COND_B, MVT::i32),
13294 SDValue(Result.getNode(), 1) };
13295 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
13296 DAG.getVTList(Op->getValueType(1), MVT::Glue),
13299 // Return { result, isValid, chain }.
13300 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
13301 SDValue(Result.getNode(), 2));
13304 //gather(v1, mask, index, base, scale);
13305 SDValue Chain = Op.getOperand(0);
13306 SDValue Src = Op.getOperand(2);
13307 SDValue Base = Op.getOperand(3);
13308 SDValue Index = Op.getOperand(4);
13309 SDValue Mask = Op.getOperand(5);
13310 SDValue Scale = Op.getOperand(6);
13311 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
13315 //scatter(base, mask, index, v1, scale);
13316 SDValue Chain = Op.getOperand(0);
13317 SDValue Base = Op.getOperand(2);
13318 SDValue Mask = Op.getOperand(3);
13319 SDValue Index = Op.getOperand(4);
13320 SDValue Src = Op.getOperand(5);
13321 SDValue Scale = Op.getOperand(6);
13322 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13325 SDValue Hint = Op.getOperand(6);
13327 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13328 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13329 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13330 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13331 SDValue Chain = Op.getOperand(0);
13332 SDValue Mask = Op.getOperand(2);
13333 SDValue Index = Op.getOperand(3);
13334 SDValue Base = Op.getOperand(4);
13335 SDValue Scale = Op.getOperand(5);
13336 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13338 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13340 SmallVector<SDValue, 2> Results;
13341 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13342 return DAG.getMergeValues(Results, dl);
13344 // XTEST intrinsics.
13346 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13347 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13348 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13349 DAG.getConstant(X86::COND_NE, MVT::i8),
13351 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13352 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13353 Ret, SDValue(InTrans.getNode(), 1));
13356 llvm_unreachable("Unknown Intrinsic Type");
13359 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13360 SelectionDAG &DAG) const {
13361 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13362 MFI->setReturnAddressIsTaken(true);
13364 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13367 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13369 EVT PtrVT = getPointerTy();
13372 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13373 const X86RegisterInfo *RegInfo =
13374 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13375 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13376 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13377 DAG.getNode(ISD::ADD, dl, PtrVT,
13378 FrameAddr, Offset),
13379 MachinePointerInfo(), false, false, false, 0);
13382 // Just load the return address.
13383 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13384 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13385 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13388 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13389 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13390 MFI->setFrameAddressIsTaken(true);
13392 EVT VT = Op.getValueType();
13393 SDLoc dl(Op); // FIXME probably not meaningful
13394 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13395 const X86RegisterInfo *RegInfo =
13396 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13397 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13398 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13399 (FrameReg == X86::EBP && VT == MVT::i32)) &&
13400 "Invalid Frame Register!");
13401 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13403 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13404 MachinePointerInfo(),
13405 false, false, false, 0);
13409 // FIXME? Maybe this could be a TableGen attribute on some registers and
13410 // this table could be generated automatically from RegInfo.
13411 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13413 unsigned Reg = StringSwitch<unsigned>(RegName)
13414 .Case("esp", X86::ESP)
13415 .Case("rsp", X86::RSP)
13419 report_fatal_error("Invalid register name global variable");
13422 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13423 SelectionDAG &DAG) const {
13424 const X86RegisterInfo *RegInfo =
13425 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13426 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13429 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13430 SDValue Chain = Op.getOperand(0);
13431 SDValue Offset = Op.getOperand(1);
13432 SDValue Handler = Op.getOperand(2);
13435 EVT PtrVT = getPointerTy();
13436 const X86RegisterInfo *RegInfo =
13437 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13438 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13439 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13440 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13441 "Invalid Frame Register!");
13442 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13443 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13445 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13446 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13447 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13448 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13450 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13452 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13453 DAG.getRegister(StoreAddrReg, PtrVT));
13456 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13457 SelectionDAG &DAG) const {
13459 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13460 DAG.getVTList(MVT::i32, MVT::Other),
13461 Op.getOperand(0), Op.getOperand(1));
13464 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13465 SelectionDAG &DAG) const {
13467 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13468 Op.getOperand(0), Op.getOperand(1));
13471 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13472 return Op.getOperand(0);
13475 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13476 SelectionDAG &DAG) const {
13477 SDValue Root = Op.getOperand(0);
13478 SDValue Trmp = Op.getOperand(1); // trampoline
13479 SDValue FPtr = Op.getOperand(2); // nested function
13480 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13483 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13484 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13486 if (Subtarget->is64Bit()) {
13487 SDValue OutChains[6];
13489 // Large code-model.
13490 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13491 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13493 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13494 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13496 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13498 // Load the pointer to the nested function into R11.
13499 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13500 SDValue Addr = Trmp;
13501 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13502 Addr, MachinePointerInfo(TrmpAddr),
13505 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13506 DAG.getConstant(2, MVT::i64));
13507 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13508 MachinePointerInfo(TrmpAddr, 2),
13511 // Load the 'nest' parameter value into R10.
13512 // R10 is specified in X86CallingConv.td
13513 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13514 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13515 DAG.getConstant(10, MVT::i64));
13516 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13517 Addr, MachinePointerInfo(TrmpAddr, 10),
13520 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13521 DAG.getConstant(12, MVT::i64));
13522 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13523 MachinePointerInfo(TrmpAddr, 12),
13526 // Jump to the nested function.
13527 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13528 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13529 DAG.getConstant(20, MVT::i64));
13530 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13531 Addr, MachinePointerInfo(TrmpAddr, 20),
13534 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13535 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13536 DAG.getConstant(22, MVT::i64));
13537 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13538 MachinePointerInfo(TrmpAddr, 22),
13541 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13543 const Function *Func =
13544 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13545 CallingConv::ID CC = Func->getCallingConv();
13550 llvm_unreachable("Unsupported calling convention");
13551 case CallingConv::C:
13552 case CallingConv::X86_StdCall: {
13553 // Pass 'nest' parameter in ECX.
13554 // Must be kept in sync with X86CallingConv.td
13555 NestReg = X86::ECX;
13557 // Check that ECX wasn't needed by an 'inreg' parameter.
13558 FunctionType *FTy = Func->getFunctionType();
13559 const AttributeSet &Attrs = Func->getAttributes();
13561 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13562 unsigned InRegCount = 0;
13565 for (FunctionType::param_iterator I = FTy->param_begin(),
13566 E = FTy->param_end(); I != E; ++I, ++Idx)
13567 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13568 // FIXME: should only count parameters that are lowered to integers.
13569 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13571 if (InRegCount > 2) {
13572 report_fatal_error("Nest register in use - reduce number of inreg"
13578 case CallingConv::X86_FastCall:
13579 case CallingConv::X86_ThisCall:
13580 case CallingConv::Fast:
13581 // Pass 'nest' parameter in EAX.
13582 // Must be kept in sync with X86CallingConv.td
13583 NestReg = X86::EAX;
13587 SDValue OutChains[4];
13588 SDValue Addr, Disp;
13590 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13591 DAG.getConstant(10, MVT::i32));
13592 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13594 // This is storing the opcode for MOV32ri.
13595 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13596 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13597 OutChains[0] = DAG.getStore(Root, dl,
13598 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13599 Trmp, MachinePointerInfo(TrmpAddr),
13602 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13603 DAG.getConstant(1, MVT::i32));
13604 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13605 MachinePointerInfo(TrmpAddr, 1),
13608 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13609 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13610 DAG.getConstant(5, MVT::i32));
13611 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13612 MachinePointerInfo(TrmpAddr, 5),
13615 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13616 DAG.getConstant(6, MVT::i32));
13617 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13618 MachinePointerInfo(TrmpAddr, 6),
13621 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13625 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13626 SelectionDAG &DAG) const {
13628 The rounding mode is in bits 11:10 of FPSR, and has the following
13630 00 Round to nearest
13635 FLT_ROUNDS, on the other hand, expects the following:
13642 To perform the conversion, we do:
13643 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13646 MachineFunction &MF = DAG.getMachineFunction();
13647 const TargetMachine &TM = MF.getTarget();
13648 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13649 unsigned StackAlignment = TFI.getStackAlignment();
13650 MVT VT = Op.getSimpleValueType();
13653 // Save FP Control Word to stack slot
13654 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13655 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13657 MachineMemOperand *MMO =
13658 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13659 MachineMemOperand::MOStore, 2, 2);
13661 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13662 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13663 DAG.getVTList(MVT::Other),
13664 Ops, MVT::i16, MMO);
13666 // Load FP Control Word from stack slot
13667 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13668 MachinePointerInfo(), false, false, false, 0);
13670 // Transform as necessary
13672 DAG.getNode(ISD::SRL, DL, MVT::i16,
13673 DAG.getNode(ISD::AND, DL, MVT::i16,
13674 CWD, DAG.getConstant(0x800, MVT::i16)),
13675 DAG.getConstant(11, MVT::i8));
13677 DAG.getNode(ISD::SRL, DL, MVT::i16,
13678 DAG.getNode(ISD::AND, DL, MVT::i16,
13679 CWD, DAG.getConstant(0x400, MVT::i16)),
13680 DAG.getConstant(9, MVT::i8));
13683 DAG.getNode(ISD::AND, DL, MVT::i16,
13684 DAG.getNode(ISD::ADD, DL, MVT::i16,
13685 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13686 DAG.getConstant(1, MVT::i16)),
13687 DAG.getConstant(3, MVT::i16));
13689 return DAG.getNode((VT.getSizeInBits() < 16 ?
13690 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13693 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13694 MVT VT = Op.getSimpleValueType();
13696 unsigned NumBits = VT.getSizeInBits();
13699 Op = Op.getOperand(0);
13700 if (VT == MVT::i8) {
13701 // Zero extend to i32 since there is not an i8 bsr.
13703 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13706 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13707 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13708 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13710 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13713 DAG.getConstant(NumBits+NumBits-1, OpVT),
13714 DAG.getConstant(X86::COND_E, MVT::i8),
13717 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13719 // Finally xor with NumBits-1.
13720 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13723 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13727 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13728 MVT VT = Op.getSimpleValueType();
13730 unsigned NumBits = VT.getSizeInBits();
13733 Op = Op.getOperand(0);
13734 if (VT == MVT::i8) {
13735 // Zero extend to i32 since there is not an i8 bsr.
13737 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13740 // Issue a bsr (scan bits in reverse).
13741 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13742 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13744 // And xor with NumBits-1.
13745 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13748 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13752 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13753 MVT VT = Op.getSimpleValueType();
13754 unsigned NumBits = VT.getSizeInBits();
13756 Op = Op.getOperand(0);
13758 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13759 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13760 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13762 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13765 DAG.getConstant(NumBits, VT),
13766 DAG.getConstant(X86::COND_E, MVT::i8),
13769 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13772 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13773 // ones, and then concatenate the result back.
13774 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13775 MVT VT = Op.getSimpleValueType();
13777 assert(VT.is256BitVector() && VT.isInteger() &&
13778 "Unsupported value type for operation");
13780 unsigned NumElems = VT.getVectorNumElements();
13783 // Extract the LHS vectors
13784 SDValue LHS = Op.getOperand(0);
13785 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13786 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13788 // Extract the RHS vectors
13789 SDValue RHS = Op.getOperand(1);
13790 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13791 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13793 MVT EltVT = VT.getVectorElementType();
13794 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13796 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13797 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13798 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13801 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13802 assert(Op.getSimpleValueType().is256BitVector() &&
13803 Op.getSimpleValueType().isInteger() &&
13804 "Only handle AVX 256-bit vector integer operation");
13805 return Lower256IntArith(Op, DAG);
13808 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13809 assert(Op.getSimpleValueType().is256BitVector() &&
13810 Op.getSimpleValueType().isInteger() &&
13811 "Only handle AVX 256-bit vector integer operation");
13812 return Lower256IntArith(Op, DAG);
13815 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13816 SelectionDAG &DAG) {
13818 MVT VT = Op.getSimpleValueType();
13820 // Decompose 256-bit ops into smaller 128-bit ops.
13821 if (VT.is256BitVector() && !Subtarget->hasInt256())
13822 return Lower256IntArith(Op, DAG);
13824 SDValue A = Op.getOperand(0);
13825 SDValue B = Op.getOperand(1);
13827 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13828 if (VT == MVT::v4i32) {
13829 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13830 "Should not custom lower when pmuldq is available!");
13832 // Extract the odd parts.
13833 static const int UnpackMask[] = { 1, -1, 3, -1 };
13834 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13835 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13837 // Multiply the even parts.
13838 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13839 // Now multiply odd parts.
13840 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13842 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13843 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13845 // Merge the two vectors back together with a shuffle. This expands into 2
13847 static const int ShufMask[] = { 0, 4, 2, 6 };
13848 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13851 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13852 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13854 // Ahi = psrlqi(a, 32);
13855 // Bhi = psrlqi(b, 32);
13857 // AloBlo = pmuludq(a, b);
13858 // AloBhi = pmuludq(a, Bhi);
13859 // AhiBlo = pmuludq(Ahi, b);
13861 // AloBhi = psllqi(AloBhi, 32);
13862 // AhiBlo = psllqi(AhiBlo, 32);
13863 // return AloBlo + AloBhi + AhiBlo;
13865 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13866 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13868 // Bit cast to 32-bit vectors for MULUDQ
13869 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13870 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13871 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13872 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13873 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13874 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13876 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13877 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13878 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13880 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13881 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13883 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13884 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13887 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13888 assert(Subtarget->isTargetWin64() && "Unexpected target");
13889 EVT VT = Op.getValueType();
13890 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13891 "Unexpected return type for lowering");
13895 switch (Op->getOpcode()) {
13896 default: llvm_unreachable("Unexpected request for libcall!");
13897 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13898 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13899 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13900 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13901 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13902 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13906 SDValue InChain = DAG.getEntryNode();
13908 TargetLowering::ArgListTy Args;
13909 TargetLowering::ArgListEntry Entry;
13910 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13911 EVT ArgVT = Op->getOperand(i).getValueType();
13912 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13913 "Unexpected argument type for lowering");
13914 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13915 Entry.Node = StackPtr;
13916 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13918 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13919 Entry.Ty = PointerType::get(ArgTy,0);
13920 Entry.isSExt = false;
13921 Entry.isZExt = false;
13922 Args.push_back(Entry);
13925 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13928 TargetLowering::CallLoweringInfo CLI(DAG);
13929 CLI.setDebugLoc(dl).setChain(InChain)
13930 .setCallee(getLibcallCallingConv(LC),
13931 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13933 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13935 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13936 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13939 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13940 SelectionDAG &DAG) {
13941 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13942 EVT VT = Op0.getValueType();
13945 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13946 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13948 // Get the high parts.
13949 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13950 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13951 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13953 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13955 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13956 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13958 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13959 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13960 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13961 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13962 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13964 // Shuffle it back into the right order.
13965 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13966 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13967 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13968 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13970 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13971 // unsigned multiply.
13972 if (IsSigned && !Subtarget->hasSSE41()) {
13974 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13975 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13976 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13977 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13978 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13980 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13981 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13984 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13987 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13988 const X86Subtarget *Subtarget) {
13989 MVT VT = Op.getSimpleValueType();
13991 SDValue R = Op.getOperand(0);
13992 SDValue Amt = Op.getOperand(1);
13994 // Optimize shl/srl/sra with constant shift amount.
13995 if (isSplatVector(Amt.getNode())) {
13996 SDValue SclrAmt = Amt->getOperand(0);
13997 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13998 uint64_t ShiftAmt = C->getZExtValue();
14000 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
14001 (Subtarget->hasInt256() &&
14002 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
14003 (Subtarget->hasAVX512() &&
14004 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
14005 if (Op.getOpcode() == ISD::SHL)
14006 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
14008 if (Op.getOpcode() == ISD::SRL)
14009 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
14011 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
14012 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
14016 if (VT == MVT::v16i8) {
14017 if (Op.getOpcode() == ISD::SHL) {
14018 // Make a large shift.
14019 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
14020 MVT::v8i16, R, ShiftAmt,
14022 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
14023 // Zero out the rightmost bits.
14024 SmallVector<SDValue, 16> V(16,
14025 DAG.getConstant(uint8_t(-1U << ShiftAmt),
14027 return DAG.getNode(ISD::AND, dl, VT, SHL,
14028 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14030 if (Op.getOpcode() == ISD::SRL) {
14031 // Make a large shift.
14032 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
14033 MVT::v8i16, R, ShiftAmt,
14035 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
14036 // Zero out the leftmost bits.
14037 SmallVector<SDValue, 16> V(16,
14038 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
14040 return DAG.getNode(ISD::AND, dl, VT, SRL,
14041 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14043 if (Op.getOpcode() == ISD::SRA) {
14044 if (ShiftAmt == 7) {
14045 // R s>> 7 === R s< 0
14046 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14047 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
14050 // R s>> a === ((R u>> a) ^ m) - m
14051 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
14052 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
14054 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
14055 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
14056 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
14059 llvm_unreachable("Unknown shift opcode.");
14062 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
14063 if (Op.getOpcode() == ISD::SHL) {
14064 // Make a large shift.
14065 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
14066 MVT::v16i16, R, ShiftAmt,
14068 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
14069 // Zero out the rightmost bits.
14070 SmallVector<SDValue, 32> V(32,
14071 DAG.getConstant(uint8_t(-1U << ShiftAmt),
14073 return DAG.getNode(ISD::AND, dl, VT, SHL,
14074 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14076 if (Op.getOpcode() == ISD::SRL) {
14077 // Make a large shift.
14078 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
14079 MVT::v16i16, R, ShiftAmt,
14081 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
14082 // Zero out the leftmost bits.
14083 SmallVector<SDValue, 32> V(32,
14084 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
14086 return DAG.getNode(ISD::AND, dl, VT, SRL,
14087 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14089 if (Op.getOpcode() == ISD::SRA) {
14090 if (ShiftAmt == 7) {
14091 // R s>> 7 === R s< 0
14092 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14093 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
14096 // R s>> a === ((R u>> a) ^ m) - m
14097 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
14098 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
14100 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
14101 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
14102 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
14105 llvm_unreachable("Unknown shift opcode.");
14110 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14111 if (!Subtarget->is64Bit() &&
14112 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
14113 Amt.getOpcode() == ISD::BITCAST &&
14114 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14115 Amt = Amt.getOperand(0);
14116 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14117 VT.getVectorNumElements();
14118 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
14119 uint64_t ShiftAmt = 0;
14120 for (unsigned i = 0; i != Ratio; ++i) {
14121 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
14125 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
14127 // Check remaining shift amounts.
14128 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14129 uint64_t ShAmt = 0;
14130 for (unsigned j = 0; j != Ratio; ++j) {
14131 ConstantSDNode *C =
14132 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
14136 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
14138 if (ShAmt != ShiftAmt)
14141 switch (Op.getOpcode()) {
14143 llvm_unreachable("Unknown shift opcode!");
14145 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
14148 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
14151 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
14159 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
14160 const X86Subtarget* Subtarget) {
14161 MVT VT = Op.getSimpleValueType();
14163 SDValue R = Op.getOperand(0);
14164 SDValue Amt = Op.getOperand(1);
14166 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
14167 VT == MVT::v4i32 || VT == MVT::v8i16 ||
14168 (Subtarget->hasInt256() &&
14169 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
14170 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
14171 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
14173 EVT EltVT = VT.getVectorElementType();
14175 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14176 unsigned NumElts = VT.getVectorNumElements();
14178 for (i = 0; i != NumElts; ++i) {
14179 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
14183 for (j = i; j != NumElts; ++j) {
14184 SDValue Arg = Amt.getOperand(j);
14185 if (Arg.getOpcode() == ISD::UNDEF) continue;
14186 if (Arg != Amt.getOperand(i))
14189 if (i != NumElts && j == NumElts)
14190 BaseShAmt = Amt.getOperand(i);
14192 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14193 Amt = Amt.getOperand(0);
14194 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
14195 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
14196 SDValue InVec = Amt.getOperand(0);
14197 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14198 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14200 for (; i != NumElts; ++i) {
14201 SDValue Arg = InVec.getOperand(i);
14202 if (Arg.getOpcode() == ISD::UNDEF) continue;
14206 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14207 if (ConstantSDNode *C =
14208 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14209 unsigned SplatIdx =
14210 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
14211 if (C->getZExtValue() == SplatIdx)
14212 BaseShAmt = InVec.getOperand(1);
14215 if (!BaseShAmt.getNode())
14216 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
14217 DAG.getIntPtrConstant(0));
14221 if (BaseShAmt.getNode()) {
14222 if (EltVT.bitsGT(MVT::i32))
14223 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
14224 else if (EltVT.bitsLT(MVT::i32))
14225 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
14227 switch (Op.getOpcode()) {
14229 llvm_unreachable("Unknown shift opcode!");
14231 switch (VT.SimpleTy) {
14232 default: return SDValue();
14241 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
14244 switch (VT.SimpleTy) {
14245 default: return SDValue();
14252 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
14255 switch (VT.SimpleTy) {
14256 default: return SDValue();
14265 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
14271 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14272 if (!Subtarget->is64Bit() &&
14273 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
14274 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
14275 Amt.getOpcode() == ISD::BITCAST &&
14276 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14277 Amt = Amt.getOperand(0);
14278 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14279 VT.getVectorNumElements();
14280 std::vector<SDValue> Vals(Ratio);
14281 for (unsigned i = 0; i != Ratio; ++i)
14282 Vals[i] = Amt.getOperand(i);
14283 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14284 for (unsigned j = 0; j != Ratio; ++j)
14285 if (Vals[j] != Amt.getOperand(i + j))
14288 switch (Op.getOpcode()) {
14290 llvm_unreachable("Unknown shift opcode!");
14292 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
14294 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
14296 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
14303 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
14304 SelectionDAG &DAG) {
14306 MVT VT = Op.getSimpleValueType();
14308 SDValue R = Op.getOperand(0);
14309 SDValue Amt = Op.getOperand(1);
14312 if (!Subtarget->hasSSE2())
14315 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14319 V = LowerScalarVariableShift(Op, DAG, Subtarget);
14323 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14325 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14326 if (Subtarget->hasInt256()) {
14327 if (Op.getOpcode() == ISD::SRL &&
14328 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14329 VT == MVT::v4i64 || VT == MVT::v8i32))
14331 if (Op.getOpcode() == ISD::SHL &&
14332 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14333 VT == MVT::v4i64 || VT == MVT::v8i32))
14335 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14339 // If possible, lower this packed shift into a vector multiply instead of
14340 // expanding it into a sequence of scalar shifts.
14341 // Do this only if the vector shift count is a constant build_vector.
14342 if (Op.getOpcode() == ISD::SHL &&
14343 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14344 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14345 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14346 SmallVector<SDValue, 8> Elts;
14347 EVT SVT = VT.getScalarType();
14348 unsigned SVTBits = SVT.getSizeInBits();
14349 const APInt &One = APInt(SVTBits, 1);
14350 unsigned NumElems = VT.getVectorNumElements();
14352 for (unsigned i=0; i !=NumElems; ++i) {
14353 SDValue Op = Amt->getOperand(i);
14354 if (Op->getOpcode() == ISD::UNDEF) {
14355 Elts.push_back(Op);
14359 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14360 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14361 uint64_t ShAmt = C.getZExtValue();
14362 if (ShAmt >= SVTBits) {
14363 Elts.push_back(DAG.getUNDEF(SVT));
14366 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14368 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14369 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14372 // Lower SHL with variable shift amount.
14373 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14374 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14376 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14377 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14378 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14379 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14382 // If possible, lower this shift as a sequence of two shifts by
14383 // constant plus a MOVSS/MOVSD instead of scalarizing it.
14385 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14387 // Could be rewritten as:
14388 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14390 // The advantage is that the two shifts from the example would be
14391 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14392 // the vector shift into four scalar shifts plus four pairs of vector
14394 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14395 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14396 unsigned TargetOpcode = X86ISD::MOVSS;
14397 bool CanBeSimplified;
14398 // The splat value for the first packed shift (the 'X' from the example).
14399 SDValue Amt1 = Amt->getOperand(0);
14400 // The splat value for the second packed shift (the 'Y' from the example).
14401 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14402 Amt->getOperand(2);
14404 // See if it is possible to replace this node with a sequence of
14405 // two shifts followed by a MOVSS/MOVSD
14406 if (VT == MVT::v4i32) {
14407 // Check if it is legal to use a MOVSS.
14408 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14409 Amt2 == Amt->getOperand(3);
14410 if (!CanBeSimplified) {
14411 // Otherwise, check if we can still simplify this node using a MOVSD.
14412 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14413 Amt->getOperand(2) == Amt->getOperand(3);
14414 TargetOpcode = X86ISD::MOVSD;
14415 Amt2 = Amt->getOperand(2);
14418 // Do similar checks for the case where the machine value type
14420 CanBeSimplified = Amt1 == Amt->getOperand(1);
14421 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14422 CanBeSimplified = Amt2 == Amt->getOperand(i);
14424 if (!CanBeSimplified) {
14425 TargetOpcode = X86ISD::MOVSD;
14426 CanBeSimplified = true;
14427 Amt2 = Amt->getOperand(4);
14428 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14429 CanBeSimplified = Amt1 == Amt->getOperand(i);
14430 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14431 CanBeSimplified = Amt2 == Amt->getOperand(j);
14435 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14436 isa<ConstantSDNode>(Amt2)) {
14437 // Replace this node with two shifts followed by a MOVSS/MOVSD.
14438 EVT CastVT = MVT::v4i32;
14440 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14441 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14443 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14444 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14445 if (TargetOpcode == X86ISD::MOVSD)
14446 CastVT = MVT::v2i64;
14447 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14448 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14449 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14451 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14455 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14456 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14459 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14460 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14462 // Turn 'a' into a mask suitable for VSELECT
14463 SDValue VSelM = DAG.getConstant(0x80, VT);
14464 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14465 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14467 SDValue CM1 = DAG.getConstant(0x0f, VT);
14468 SDValue CM2 = DAG.getConstant(0x3f, VT);
14470 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14471 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14472 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14473 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14474 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14477 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14478 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14479 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14481 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14482 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14483 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14484 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14485 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14488 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14489 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14490 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14492 // return VSELECT(r, r+r, a);
14493 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14494 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14498 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14499 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14500 // solution better.
14501 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14502 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14504 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14505 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14506 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14507 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14508 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14511 // Decompose 256-bit shifts into smaller 128-bit shifts.
14512 if (VT.is256BitVector()) {
14513 unsigned NumElems = VT.getVectorNumElements();
14514 MVT EltVT = VT.getVectorElementType();
14515 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14517 // Extract the two vectors
14518 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14519 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14521 // Recreate the shift amount vectors
14522 SDValue Amt1, Amt2;
14523 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14524 // Constant shift amount
14525 SmallVector<SDValue, 4> Amt1Csts;
14526 SmallVector<SDValue, 4> Amt2Csts;
14527 for (unsigned i = 0; i != NumElems/2; ++i)
14528 Amt1Csts.push_back(Amt->getOperand(i));
14529 for (unsigned i = NumElems/2; i != NumElems; ++i)
14530 Amt2Csts.push_back(Amt->getOperand(i));
14532 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14533 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14535 // Variable shift amount
14536 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14537 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14540 // Issue new vector shifts for the smaller types
14541 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14542 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14544 // Concatenate the result back
14545 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14551 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14552 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14553 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14554 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14555 // has only one use.
14556 SDNode *N = Op.getNode();
14557 SDValue LHS = N->getOperand(0);
14558 SDValue RHS = N->getOperand(1);
14559 unsigned BaseOp = 0;
14562 switch (Op.getOpcode()) {
14563 default: llvm_unreachable("Unknown ovf instruction!");
14565 // A subtract of one will be selected as a INC. Note that INC doesn't
14566 // set CF, so we can't do this for UADDO.
14567 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14569 BaseOp = X86ISD::INC;
14570 Cond = X86::COND_O;
14573 BaseOp = X86ISD::ADD;
14574 Cond = X86::COND_O;
14577 BaseOp = X86ISD::ADD;
14578 Cond = X86::COND_B;
14581 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14582 // set CF, so we can't do this for USUBO.
14583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14585 BaseOp = X86ISD::DEC;
14586 Cond = X86::COND_O;
14589 BaseOp = X86ISD::SUB;
14590 Cond = X86::COND_O;
14593 BaseOp = X86ISD::SUB;
14594 Cond = X86::COND_B;
14597 BaseOp = X86ISD::SMUL;
14598 Cond = X86::COND_O;
14600 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14601 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14603 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14606 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14607 DAG.getConstant(X86::COND_O, MVT::i32),
14608 SDValue(Sum.getNode(), 2));
14610 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14614 // Also sets EFLAGS.
14615 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14616 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14619 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14620 DAG.getConstant(Cond, MVT::i32),
14621 SDValue(Sum.getNode(), 1));
14623 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14626 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14627 SelectionDAG &DAG) const {
14629 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14630 MVT VT = Op.getSimpleValueType();
14632 if (!Subtarget->hasSSE2() || !VT.isVector())
14635 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14636 ExtraVT.getScalarType().getSizeInBits();
14638 switch (VT.SimpleTy) {
14639 default: return SDValue();
14642 if (!Subtarget->hasFp256())
14644 if (!Subtarget->hasInt256()) {
14645 // needs to be split
14646 unsigned NumElems = VT.getVectorNumElements();
14648 // Extract the LHS vectors
14649 SDValue LHS = Op.getOperand(0);
14650 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14651 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14653 MVT EltVT = VT.getVectorElementType();
14654 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14656 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14657 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14658 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14660 SDValue Extra = DAG.getValueType(ExtraVT);
14662 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14663 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14665 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14670 SDValue Op0 = Op.getOperand(0);
14671 SDValue Op00 = Op0.getOperand(0);
14673 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14674 if (Op0.getOpcode() == ISD::BITCAST &&
14675 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14676 // (sext (vzext x)) -> (vsext x)
14677 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14678 if (Tmp1.getNode()) {
14679 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14680 // This folding is only valid when the in-reg type is a vector of i8,
14682 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14683 ExtraEltVT == MVT::i32) {
14684 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14685 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14686 "This optimization is invalid without a VZEXT.");
14687 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14693 // If the above didn't work, then just use Shift-Left + Shift-Right.
14694 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14696 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14702 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14703 SelectionDAG &DAG) {
14705 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14706 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14707 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14708 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14710 // The only fence that needs an instruction is a sequentially-consistent
14711 // cross-thread fence.
14712 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14713 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14714 // no-sse2). There isn't any reason to disable it if the target processor
14716 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14717 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14719 SDValue Chain = Op.getOperand(0);
14720 SDValue Zero = DAG.getConstant(0, MVT::i32);
14722 DAG.getRegister(X86::ESP, MVT::i32), // Base
14723 DAG.getTargetConstant(1, MVT::i8), // Scale
14724 DAG.getRegister(0, MVT::i32), // Index
14725 DAG.getTargetConstant(0, MVT::i32), // Disp
14726 DAG.getRegister(0, MVT::i32), // Segment.
14730 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14731 return SDValue(Res, 0);
14734 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14735 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14738 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14739 SelectionDAG &DAG) {
14740 MVT T = Op.getSimpleValueType();
14744 switch(T.SimpleTy) {
14745 default: llvm_unreachable("Invalid value type!");
14746 case MVT::i8: Reg = X86::AL; size = 1; break;
14747 case MVT::i16: Reg = X86::AX; size = 2; break;
14748 case MVT::i32: Reg = X86::EAX; size = 4; break;
14750 assert(Subtarget->is64Bit() && "Node not type legal!");
14751 Reg = X86::RAX; size = 8;
14754 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14755 Op.getOperand(2), SDValue());
14756 SDValue Ops[] = { cpIn.getValue(0),
14759 DAG.getTargetConstant(size, MVT::i8),
14760 cpIn.getValue(1) };
14761 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14762 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14763 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14767 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14768 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
14769 MVT::i32, cpOut.getValue(2));
14770 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
14771 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
14773 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
14774 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
14775 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
14779 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14780 SelectionDAG &DAG) {
14781 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14782 MVT DstVT = Op.getSimpleValueType();
14784 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14785 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14786 if (DstVT != MVT::f64)
14787 // This conversion needs to be expanded.
14790 SDValue InVec = Op->getOperand(0);
14792 unsigned NumElts = SrcVT.getVectorNumElements();
14793 EVT SVT = SrcVT.getVectorElementType();
14795 // Widen the vector in input in the case of MVT::v2i32.
14796 // Example: from MVT::v2i32 to MVT::v4i32.
14797 SmallVector<SDValue, 16> Elts;
14798 for (unsigned i = 0, e = NumElts; i != e; ++i)
14799 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14800 DAG.getIntPtrConstant(i)));
14802 // Explicitly mark the extra elements as Undef.
14803 SDValue Undef = DAG.getUNDEF(SVT);
14804 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14805 Elts.push_back(Undef);
14807 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14808 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14809 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14810 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14811 DAG.getIntPtrConstant(0));
14814 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14815 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14816 assert((DstVT == MVT::i64 ||
14817 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14818 "Unexpected custom BITCAST");
14819 // i64 <=> MMX conversions are Legal.
14820 if (SrcVT==MVT::i64 && DstVT.isVector())
14822 if (DstVT==MVT::i64 && SrcVT.isVector())
14824 // MMX <=> MMX conversions are Legal.
14825 if (SrcVT.isVector() && DstVT.isVector())
14827 // All other conversions need to be expanded.
14831 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14832 SDNode *Node = Op.getNode();
14834 EVT T = Node->getValueType(0);
14835 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14836 DAG.getConstant(0, T), Node->getOperand(2));
14837 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14838 cast<AtomicSDNode>(Node)->getMemoryVT(),
14839 Node->getOperand(0),
14840 Node->getOperand(1), negOp,
14841 cast<AtomicSDNode>(Node)->getMemOperand(),
14842 cast<AtomicSDNode>(Node)->getOrdering(),
14843 cast<AtomicSDNode>(Node)->getSynchScope());
14846 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14847 SDNode *Node = Op.getNode();
14849 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14851 // Convert seq_cst store -> xchg
14852 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14853 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14854 // (The only way to get a 16-byte store is cmpxchg16b)
14855 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14856 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14857 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14858 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14859 cast<AtomicSDNode>(Node)->getMemoryVT(),
14860 Node->getOperand(0),
14861 Node->getOperand(1), Node->getOperand(2),
14862 cast<AtomicSDNode>(Node)->getMemOperand(),
14863 cast<AtomicSDNode>(Node)->getOrdering(),
14864 cast<AtomicSDNode>(Node)->getSynchScope());
14865 return Swap.getValue(1);
14867 // Other atomic stores have a simple pattern.
14871 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14872 EVT VT = Op.getNode()->getSimpleValueType(0);
14874 // Let legalize expand this if it isn't a legal type yet.
14875 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14878 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14881 bool ExtraOp = false;
14882 switch (Op.getOpcode()) {
14883 default: llvm_unreachable("Invalid code");
14884 case ISD::ADDC: Opc = X86ISD::ADD; break;
14885 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14886 case ISD::SUBC: Opc = X86ISD::SUB; break;
14887 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14891 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14893 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14894 Op.getOperand(1), Op.getOperand(2));
14897 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14898 SelectionDAG &DAG) {
14899 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14901 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14902 // which returns the values as { float, float } (in XMM0) or
14903 // { double, double } (which is returned in XMM0, XMM1).
14905 SDValue Arg = Op.getOperand(0);
14906 EVT ArgVT = Arg.getValueType();
14907 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14909 TargetLowering::ArgListTy Args;
14910 TargetLowering::ArgListEntry Entry;
14914 Entry.isSExt = false;
14915 Entry.isZExt = false;
14916 Args.push_back(Entry);
14918 bool isF64 = ArgVT == MVT::f64;
14919 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14920 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14921 // the results are returned via SRet in memory.
14922 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14924 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14926 Type *RetTy = isF64
14927 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14928 : (Type*)VectorType::get(ArgTy, 4);
14930 TargetLowering::CallLoweringInfo CLI(DAG);
14931 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14932 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14934 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14937 // Returned in xmm0 and xmm1.
14938 return CallResult.first;
14940 // Returned in bits 0:31 and 32:64 xmm0.
14941 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14942 CallResult.first, DAG.getIntPtrConstant(0));
14943 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14944 CallResult.first, DAG.getIntPtrConstant(1));
14945 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14946 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14949 /// LowerOperation - Provide custom lowering hooks for some operations.
14951 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14952 switch (Op.getOpcode()) {
14953 default: llvm_unreachable("Should not custom lower this!");
14954 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14955 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14956 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
14957 return LowerCMP_SWAP(Op, Subtarget, DAG);
14958 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14959 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14960 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14961 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14962 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14963 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14964 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14965 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14966 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14967 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14968 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14969 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14970 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14971 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14972 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14973 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14974 case ISD::SHL_PARTS:
14975 case ISD::SRA_PARTS:
14976 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14977 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14978 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14979 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14980 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14981 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14982 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14983 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14984 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14985 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14986 case ISD::FABS: return LowerFABS(Op, DAG);
14987 case ISD::FNEG: return LowerFNEG(Op, DAG);
14988 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14989 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14990 case ISD::SETCC: return LowerSETCC(Op, DAG);
14991 case ISD::SELECT: return LowerSELECT(Op, DAG);
14992 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14993 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14994 case ISD::VASTART: return LowerVASTART(Op, DAG);
14995 case ISD::VAARG: return LowerVAARG(Op, DAG);
14996 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14997 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14998 case ISD::INTRINSIC_VOID:
14999 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
15000 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
15001 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
15002 case ISD::FRAME_TO_ARGS_OFFSET:
15003 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
15004 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
15005 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
15006 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
15007 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
15008 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
15009 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
15010 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
15011 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
15012 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
15013 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
15014 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
15015 case ISD::UMUL_LOHI:
15016 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
15019 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
15025 case ISD::UMULO: return LowerXALUO(Op, DAG);
15026 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
15027 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
15031 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
15032 case ISD::ADD: return LowerADD(Op, DAG);
15033 case ISD::SUB: return LowerSUB(Op, DAG);
15034 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
15038 static void ReplaceATOMIC_LOAD(SDNode *Node,
15039 SmallVectorImpl<SDValue> &Results,
15040 SelectionDAG &DAG) {
15042 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
15044 // Convert wide load -> cmpxchg8b/cmpxchg16b
15045 // FIXME: On 32-bit, load -> fild or movq would be more efficient
15046 // (The only way to get a 16-byte load is cmpxchg16b)
15047 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
15048 SDValue Zero = DAG.getConstant(0, VT);
15049 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
15051 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
15052 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
15053 cast<AtomicSDNode>(Node)->getMemOperand(),
15054 cast<AtomicSDNode>(Node)->getOrdering(),
15055 cast<AtomicSDNode>(Node)->getOrdering(),
15056 cast<AtomicSDNode>(Node)->getSynchScope());
15057 Results.push_back(Swap.getValue(0));
15058 Results.push_back(Swap.getValue(2));
15062 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
15063 SelectionDAG &DAG, unsigned NewOp) {
15065 assert (Node->getValueType(0) == MVT::i64 &&
15066 "Only know how to expand i64 atomics");
15068 SDValue Chain = Node->getOperand(0);
15069 SDValue In1 = Node->getOperand(1);
15070 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
15071 Node->getOperand(2), DAG.getIntPtrConstant(0));
15072 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
15073 Node->getOperand(2), DAG.getIntPtrConstant(1));
15074 SDValue Ops[] = { Chain, In1, In2L, In2H };
15075 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
15077 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
15078 cast<MemSDNode>(Node)->getMemOperand());
15079 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
15080 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
15081 Results.push_back(Result.getValue(2));
15084 /// ReplaceNodeResults - Replace a node with an illegal result type
15085 /// with a new node built out of custom code.
15086 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
15087 SmallVectorImpl<SDValue>&Results,
15088 SelectionDAG &DAG) const {
15090 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15091 switch (N->getOpcode()) {
15093 llvm_unreachable("Do not know how to custom type legalize this operation!");
15094 case ISD::SIGN_EXTEND_INREG:
15099 // We don't want to expand or promote these.
15106 case ISD::UDIVREM: {
15107 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
15108 Results.push_back(V);
15111 case ISD::FP_TO_SINT:
15112 case ISD::FP_TO_UINT: {
15113 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
15115 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
15118 std::pair<SDValue,SDValue> Vals =
15119 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
15120 SDValue FIST = Vals.first, StackSlot = Vals.second;
15121 if (FIST.getNode()) {
15122 EVT VT = N->getValueType(0);
15123 // Return a load from the stack slot.
15124 if (StackSlot.getNode())
15125 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
15126 MachinePointerInfo(),
15127 false, false, false, 0));
15129 Results.push_back(FIST);
15133 case ISD::UINT_TO_FP: {
15134 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15135 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
15136 N->getValueType(0) != MVT::v2f32)
15138 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
15140 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
15142 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
15143 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
15144 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
15145 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
15146 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
15147 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
15150 case ISD::FP_ROUND: {
15151 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
15153 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
15154 Results.push_back(V);
15157 case ISD::INTRINSIC_W_CHAIN: {
15158 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15160 default : llvm_unreachable("Do not know how to custom type "
15161 "legalize this intrinsic operation!");
15162 case Intrinsic::x86_rdtsc:
15163 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15165 case Intrinsic::x86_rdtscp:
15166 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
15170 case ISD::READCYCLECOUNTER: {
15171 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15174 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
15175 EVT T = N->getValueType(0);
15176 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
15177 bool Regs64bit = T == MVT::i128;
15178 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
15179 SDValue cpInL, cpInH;
15180 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15181 DAG.getConstant(0, HalfT));
15182 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15183 DAG.getConstant(1, HalfT));
15184 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
15185 Regs64bit ? X86::RAX : X86::EAX,
15187 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
15188 Regs64bit ? X86::RDX : X86::EDX,
15189 cpInH, cpInL.getValue(1));
15190 SDValue swapInL, swapInH;
15191 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15192 DAG.getConstant(0, HalfT));
15193 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15194 DAG.getConstant(1, HalfT));
15195 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
15196 Regs64bit ? X86::RBX : X86::EBX,
15197 swapInL, cpInH.getValue(1));
15198 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
15199 Regs64bit ? X86::RCX : X86::ECX,
15200 swapInH, swapInL.getValue(1));
15201 SDValue Ops[] = { swapInH.getValue(0),
15203 swapInH.getValue(1) };
15204 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15205 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
15206 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
15207 X86ISD::LCMPXCHG8_DAG;
15208 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
15209 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
15210 Regs64bit ? X86::RAX : X86::EAX,
15211 HalfT, Result.getValue(1));
15212 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
15213 Regs64bit ? X86::RDX : X86::EDX,
15214 HalfT, cpOutL.getValue(2));
15215 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
15217 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
15218 MVT::i32, cpOutH.getValue(2));
15220 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15221 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15222 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
15224 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
15225 Results.push_back(Success);
15226 Results.push_back(EFLAGS.getValue(1));
15229 case ISD::ATOMIC_LOAD_ADD:
15230 case ISD::ATOMIC_LOAD_AND:
15231 case ISD::ATOMIC_LOAD_NAND:
15232 case ISD::ATOMIC_LOAD_OR:
15233 case ISD::ATOMIC_LOAD_SUB:
15234 case ISD::ATOMIC_LOAD_XOR:
15235 case ISD::ATOMIC_LOAD_MAX:
15236 case ISD::ATOMIC_LOAD_MIN:
15237 case ISD::ATOMIC_LOAD_UMAX:
15238 case ISD::ATOMIC_LOAD_UMIN:
15239 case ISD::ATOMIC_SWAP: {
15241 switch (N->getOpcode()) {
15242 default: llvm_unreachable("Unexpected opcode");
15243 case ISD::ATOMIC_LOAD_ADD:
15244 Opc = X86ISD::ATOMADD64_DAG;
15246 case ISD::ATOMIC_LOAD_AND:
15247 Opc = X86ISD::ATOMAND64_DAG;
15249 case ISD::ATOMIC_LOAD_NAND:
15250 Opc = X86ISD::ATOMNAND64_DAG;
15252 case ISD::ATOMIC_LOAD_OR:
15253 Opc = X86ISD::ATOMOR64_DAG;
15255 case ISD::ATOMIC_LOAD_SUB:
15256 Opc = X86ISD::ATOMSUB64_DAG;
15258 case ISD::ATOMIC_LOAD_XOR:
15259 Opc = X86ISD::ATOMXOR64_DAG;
15261 case ISD::ATOMIC_LOAD_MAX:
15262 Opc = X86ISD::ATOMMAX64_DAG;
15264 case ISD::ATOMIC_LOAD_MIN:
15265 Opc = X86ISD::ATOMMIN64_DAG;
15267 case ISD::ATOMIC_LOAD_UMAX:
15268 Opc = X86ISD::ATOMUMAX64_DAG;
15270 case ISD::ATOMIC_LOAD_UMIN:
15271 Opc = X86ISD::ATOMUMIN64_DAG;
15273 case ISD::ATOMIC_SWAP:
15274 Opc = X86ISD::ATOMSWAP64_DAG;
15277 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
15280 case ISD::ATOMIC_LOAD: {
15281 ReplaceATOMIC_LOAD(N, Results, DAG);
15284 case ISD::BITCAST: {
15285 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15286 EVT DstVT = N->getValueType(0);
15287 EVT SrcVT = N->getOperand(0)->getValueType(0);
15289 if (SrcVT != MVT::f64 ||
15290 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
15293 unsigned NumElts = DstVT.getVectorNumElements();
15294 EVT SVT = DstVT.getVectorElementType();
15295 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15296 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
15297 MVT::v2f64, N->getOperand(0));
15298 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
15300 SmallVector<SDValue, 8> Elts;
15301 for (unsigned i = 0, e = NumElts; i != e; ++i)
15302 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
15303 ToVecInt, DAG.getIntPtrConstant(i)));
15305 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
15310 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
15312 default: return nullptr;
15313 case X86ISD::BSF: return "X86ISD::BSF";
15314 case X86ISD::BSR: return "X86ISD::BSR";
15315 case X86ISD::SHLD: return "X86ISD::SHLD";
15316 case X86ISD::SHRD: return "X86ISD::SHRD";
15317 case X86ISD::FAND: return "X86ISD::FAND";
15318 case X86ISD::FANDN: return "X86ISD::FANDN";
15319 case X86ISD::FOR: return "X86ISD::FOR";
15320 case X86ISD::FXOR: return "X86ISD::FXOR";
15321 case X86ISD::FSRL: return "X86ISD::FSRL";
15322 case X86ISD::FILD: return "X86ISD::FILD";
15323 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
15324 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
15325 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
15326 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
15327 case X86ISD::FLD: return "X86ISD::FLD";
15328 case X86ISD::FST: return "X86ISD::FST";
15329 case X86ISD::CALL: return "X86ISD::CALL";
15330 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
15331 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
15332 case X86ISD::BT: return "X86ISD::BT";
15333 case X86ISD::CMP: return "X86ISD::CMP";
15334 case X86ISD::COMI: return "X86ISD::COMI";
15335 case X86ISD::UCOMI: return "X86ISD::UCOMI";
15336 case X86ISD::CMPM: return "X86ISD::CMPM";
15337 case X86ISD::CMPMU: return "X86ISD::CMPMU";
15338 case X86ISD::SETCC: return "X86ISD::SETCC";
15339 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
15340 case X86ISD::FSETCC: return "X86ISD::FSETCC";
15341 case X86ISD::CMOV: return "X86ISD::CMOV";
15342 case X86ISD::BRCOND: return "X86ISD::BRCOND";
15343 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
15344 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
15345 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
15346 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
15347 case X86ISD::Wrapper: return "X86ISD::Wrapper";
15348 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
15349 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
15350 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
15351 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
15352 case X86ISD::PINSRB: return "X86ISD::PINSRB";
15353 case X86ISD::PINSRW: return "X86ISD::PINSRW";
15354 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
15355 case X86ISD::ANDNP: return "X86ISD::ANDNP";
15356 case X86ISD::PSIGN: return "X86ISD::PSIGN";
15357 case X86ISD::BLENDV: return "X86ISD::BLENDV";
15358 case X86ISD::BLENDI: return "X86ISD::BLENDI";
15359 case X86ISD::SUBUS: return "X86ISD::SUBUS";
15360 case X86ISD::HADD: return "X86ISD::HADD";
15361 case X86ISD::HSUB: return "X86ISD::HSUB";
15362 case X86ISD::FHADD: return "X86ISD::FHADD";
15363 case X86ISD::FHSUB: return "X86ISD::FHSUB";
15364 case X86ISD::UMAX: return "X86ISD::UMAX";
15365 case X86ISD::UMIN: return "X86ISD::UMIN";
15366 case X86ISD::SMAX: return "X86ISD::SMAX";
15367 case X86ISD::SMIN: return "X86ISD::SMIN";
15368 case X86ISD::FMAX: return "X86ISD::FMAX";
15369 case X86ISD::FMIN: return "X86ISD::FMIN";
15370 case X86ISD::FMAXC: return "X86ISD::FMAXC";
15371 case X86ISD::FMINC: return "X86ISD::FMINC";
15372 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
15373 case X86ISD::FRCP: return "X86ISD::FRCP";
15374 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
15375 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
15376 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
15377 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
15378 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
15379 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
15380 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
15381 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
15382 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
15383 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
15384 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
15385 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
15386 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
15387 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
15388 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
15389 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
15390 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
15391 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
15392 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
15393 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
15394 case X86ISD::VZEXT: return "X86ISD::VZEXT";
15395 case X86ISD::VSEXT: return "X86ISD::VSEXT";
15396 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
15397 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
15398 case X86ISD::VINSERT: return "X86ISD::VINSERT";
15399 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
15400 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
15401 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
15402 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
15403 case X86ISD::VSHL: return "X86ISD::VSHL";
15404 case X86ISD::VSRL: return "X86ISD::VSRL";
15405 case X86ISD::VSRA: return "X86ISD::VSRA";
15406 case X86ISD::VSHLI: return "X86ISD::VSHLI";
15407 case X86ISD::VSRLI: return "X86ISD::VSRLI";
15408 case X86ISD::VSRAI: return "X86ISD::VSRAI";
15409 case X86ISD::CMPP: return "X86ISD::CMPP";
15410 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
15411 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
15412 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
15413 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
15414 case X86ISD::ADD: return "X86ISD::ADD";
15415 case X86ISD::SUB: return "X86ISD::SUB";
15416 case X86ISD::ADC: return "X86ISD::ADC";
15417 case X86ISD::SBB: return "X86ISD::SBB";
15418 case X86ISD::SMUL: return "X86ISD::SMUL";
15419 case X86ISD::UMUL: return "X86ISD::UMUL";
15420 case X86ISD::INC: return "X86ISD::INC";
15421 case X86ISD::DEC: return "X86ISD::DEC";
15422 case X86ISD::OR: return "X86ISD::OR";
15423 case X86ISD::XOR: return "X86ISD::XOR";
15424 case X86ISD::AND: return "X86ISD::AND";
15425 case X86ISD::BEXTR: return "X86ISD::BEXTR";
15426 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
15427 case X86ISD::PTEST: return "X86ISD::PTEST";
15428 case X86ISD::TESTP: return "X86ISD::TESTP";
15429 case X86ISD::TESTM: return "X86ISD::TESTM";
15430 case X86ISD::TESTNM: return "X86ISD::TESTNM";
15431 case X86ISD::KORTEST: return "X86ISD::KORTEST";
15432 case X86ISD::PACKSS: return "X86ISD::PACKSS";
15433 case X86ISD::PACKUS: return "X86ISD::PACKUS";
15434 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
15435 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
15436 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
15437 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
15438 case X86ISD::SHUFP: return "X86ISD::SHUFP";
15439 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
15440 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
15441 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
15442 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
15443 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
15444 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
15445 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
15446 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
15447 case X86ISD::MOVSD: return "X86ISD::MOVSD";
15448 case X86ISD::MOVSS: return "X86ISD::MOVSS";
15449 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
15450 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
15451 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
15452 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
15453 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
15454 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
15455 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
15456 case X86ISD::VPERMV: return "X86ISD::VPERMV";
15457 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
15458 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
15459 case X86ISD::VPERMI: return "X86ISD::VPERMI";
15460 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
15461 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
15462 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15463 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
15464 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
15465 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
15466 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
15467 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
15468 case X86ISD::SAHF: return "X86ISD::SAHF";
15469 case X86ISD::RDRAND: return "X86ISD::RDRAND";
15470 case X86ISD::RDSEED: return "X86ISD::RDSEED";
15471 case X86ISD::FMADD: return "X86ISD::FMADD";
15472 case X86ISD::FMSUB: return "X86ISD::FMSUB";
15473 case X86ISD::FNMADD: return "X86ISD::FNMADD";
15474 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
15475 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
15476 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
15477 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
15478 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
15479 case X86ISD::XTEST: return "X86ISD::XTEST";
15483 // isLegalAddressingMode - Return true if the addressing mode represented
15484 // by AM is legal for this target, for a load/store of the specified type.
15485 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15487 // X86 supports extremely general addressing modes.
15488 CodeModel::Model M = getTargetMachine().getCodeModel();
15489 Reloc::Model R = getTargetMachine().getRelocationModel();
15491 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15492 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15497 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15499 // If a reference to this global requires an extra load, we can't fold it.
15500 if (isGlobalStubReference(GVFlags))
15503 // If BaseGV requires a register for the PIC base, we cannot also have a
15504 // BaseReg specified.
15505 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15508 // If lower 4G is not available, then we must use rip-relative addressing.
15509 if ((M != CodeModel::Small || R != Reloc::Static) &&
15510 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15514 switch (AM.Scale) {
15520 // These scales always work.
15525 // These scales are formed with basereg+scalereg. Only accept if there is
15530 default: // Other stuff never works.
15537 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15538 unsigned Bits = Ty->getScalarSizeInBits();
15540 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15541 // particularly cheaper than those without.
15545 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15546 // variable shifts just as cheap as scalar ones.
15547 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15550 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15551 // fully general vector.
15555 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15556 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15558 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15559 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15560 return NumBits1 > NumBits2;
15563 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15564 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15567 if (!isTypeLegal(EVT::getEVT(Ty1)))
15570 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15572 // Assuming the caller doesn't have a zeroext or signext return parameter,
15573 // truncation all the way down to i1 is valid.
15577 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15578 return isInt<32>(Imm);
15581 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15582 // Can also use sub to handle negated immediates.
15583 return isInt<32>(Imm);
15586 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15587 if (!VT1.isInteger() || !VT2.isInteger())
15589 unsigned NumBits1 = VT1.getSizeInBits();
15590 unsigned NumBits2 = VT2.getSizeInBits();
15591 return NumBits1 > NumBits2;
15594 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15595 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15596 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15599 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15600 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15601 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15604 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15605 EVT VT1 = Val.getValueType();
15606 if (isZExtFree(VT1, VT2))
15609 if (Val.getOpcode() != ISD::LOAD)
15612 if (!VT1.isSimple() || !VT1.isInteger() ||
15613 !VT2.isSimple() || !VT2.isInteger())
15616 switch (VT1.getSimpleVT().SimpleTy) {
15621 // X86 has 8, 16, and 32-bit zero-extending loads.
15629 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15630 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15633 VT = VT.getScalarType();
15635 if (!VT.isSimple())
15638 switch (VT.getSimpleVT().SimpleTy) {
15649 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15650 // i16 instructions are longer (0x66 prefix) and potentially slower.
15651 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15654 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15655 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15656 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15657 /// are assumed to be legal.
15659 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15661 if (!VT.isSimple())
15664 MVT SVT = VT.getSimpleVT();
15666 // Very little shuffling can be done for 64-bit vectors right now.
15667 if (VT.getSizeInBits() == 64)
15670 // If this is a single-input shuffle with no 128 bit lane crossings we can
15671 // lower it into pshufb.
15672 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15673 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15674 bool isLegal = true;
15675 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15676 if (M[I] >= (int)SVT.getVectorNumElements() ||
15677 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15686 // FIXME: blends, shifts.
15687 return (SVT.getVectorNumElements() == 2 ||
15688 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15689 isMOVLMask(M, SVT) ||
15690 isSHUFPMask(M, SVT) ||
15691 isPSHUFDMask(M, SVT) ||
15692 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15693 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15694 isPALIGNRMask(M, SVT, Subtarget) ||
15695 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15696 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15697 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15698 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15699 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15703 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15705 if (!VT.isSimple())
15708 MVT SVT = VT.getSimpleVT();
15709 unsigned NumElts = SVT.getVectorNumElements();
15710 // FIXME: This collection of masks seems suspect.
15713 if (NumElts == 4 && SVT.is128BitVector()) {
15714 return (isMOVLMask(Mask, SVT) ||
15715 isCommutedMOVLMask(Mask, SVT, true) ||
15716 isSHUFPMask(Mask, SVT) ||
15717 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15722 //===----------------------------------------------------------------------===//
15723 // X86 Scheduler Hooks
15724 //===----------------------------------------------------------------------===//
15726 /// Utility function to emit xbegin specifying the start of an RTM region.
15727 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15728 const TargetInstrInfo *TII) {
15729 DebugLoc DL = MI->getDebugLoc();
15731 const BasicBlock *BB = MBB->getBasicBlock();
15732 MachineFunction::iterator I = MBB;
15735 // For the v = xbegin(), we generate
15746 MachineBasicBlock *thisMBB = MBB;
15747 MachineFunction *MF = MBB->getParent();
15748 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15749 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15750 MF->insert(I, mainMBB);
15751 MF->insert(I, sinkMBB);
15753 // Transfer the remainder of BB and its successor edges to sinkMBB.
15754 sinkMBB->splice(sinkMBB->begin(), MBB,
15755 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15756 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15760 // # fallthrough to mainMBB
15761 // # abortion to sinkMBB
15762 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15763 thisMBB->addSuccessor(mainMBB);
15764 thisMBB->addSuccessor(sinkMBB);
15768 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15769 mainMBB->addSuccessor(sinkMBB);
15772 // EAX is live into the sinkMBB
15773 sinkMBB->addLiveIn(X86::EAX);
15774 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15775 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15778 MI->eraseFromParent();
15782 // Get CMPXCHG opcode for the specified data type.
15783 static unsigned getCmpXChgOpcode(EVT VT) {
15784 switch (VT.getSimpleVT().SimpleTy) {
15785 case MVT::i8: return X86::LCMPXCHG8;
15786 case MVT::i16: return X86::LCMPXCHG16;
15787 case MVT::i32: return X86::LCMPXCHG32;
15788 case MVT::i64: return X86::LCMPXCHG64;
15792 llvm_unreachable("Invalid operand size!");
15795 // Get LOAD opcode for the specified data type.
15796 static unsigned getLoadOpcode(EVT VT) {
15797 switch (VT.getSimpleVT().SimpleTy) {
15798 case MVT::i8: return X86::MOV8rm;
15799 case MVT::i16: return X86::MOV16rm;
15800 case MVT::i32: return X86::MOV32rm;
15801 case MVT::i64: return X86::MOV64rm;
15805 llvm_unreachable("Invalid operand size!");
15808 // Get opcode of the non-atomic one from the specified atomic instruction.
15809 static unsigned getNonAtomicOpcode(unsigned Opc) {
15811 case X86::ATOMAND8: return X86::AND8rr;
15812 case X86::ATOMAND16: return X86::AND16rr;
15813 case X86::ATOMAND32: return X86::AND32rr;
15814 case X86::ATOMAND64: return X86::AND64rr;
15815 case X86::ATOMOR8: return X86::OR8rr;
15816 case X86::ATOMOR16: return X86::OR16rr;
15817 case X86::ATOMOR32: return X86::OR32rr;
15818 case X86::ATOMOR64: return X86::OR64rr;
15819 case X86::ATOMXOR8: return X86::XOR8rr;
15820 case X86::ATOMXOR16: return X86::XOR16rr;
15821 case X86::ATOMXOR32: return X86::XOR32rr;
15822 case X86::ATOMXOR64: return X86::XOR64rr;
15824 llvm_unreachable("Unhandled atomic-load-op opcode!");
15827 // Get opcode of the non-atomic one from the specified atomic instruction with
15829 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15830 unsigned &ExtraOpc) {
15832 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15833 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15834 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15835 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15836 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15837 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15838 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15839 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15840 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15841 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15842 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15843 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15844 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15845 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15846 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15847 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15848 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15849 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15850 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15851 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15853 llvm_unreachable("Unhandled atomic-load-op opcode!");
15856 // Get opcode of the non-atomic one from the specified atomic instruction for
15857 // 64-bit data type on 32-bit target.
15858 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15860 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15861 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15862 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15863 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15864 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15865 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15866 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15867 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15868 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15869 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15871 llvm_unreachable("Unhandled atomic-load-op opcode!");
15874 // Get opcode of the non-atomic one from the specified atomic instruction for
15875 // 64-bit data type on 32-bit target with extra opcode.
15876 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15878 unsigned &ExtraOpc) {
15880 case X86::ATOMNAND6432:
15881 ExtraOpc = X86::NOT32r;
15882 HiOpc = X86::AND32rr;
15883 return X86::AND32rr;
15885 llvm_unreachable("Unhandled atomic-load-op opcode!");
15888 // Get pseudo CMOV opcode from the specified data type.
15889 static unsigned getPseudoCMOVOpc(EVT VT) {
15890 switch (VT.getSimpleVT().SimpleTy) {
15891 case MVT::i8: return X86::CMOV_GR8;
15892 case MVT::i16: return X86::CMOV_GR16;
15893 case MVT::i32: return X86::CMOV_GR32;
15897 llvm_unreachable("Unknown CMOV opcode!");
15900 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15901 // They will be translated into a spin-loop or compare-exchange loop from
15904 // dst = atomic-fetch-op MI.addr, MI.val
15910 // t1 = LOAD MI.addr
15912 // t4 = phi(t1, t3 / loop)
15913 // t2 = OP MI.val, t4
15915 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15921 MachineBasicBlock *
15922 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15923 MachineBasicBlock *MBB) const {
15924 MachineFunction *MF = MBB->getParent();
15925 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15926 DebugLoc DL = MI->getDebugLoc();
15928 MachineRegisterInfo &MRI = MF->getRegInfo();
15930 const BasicBlock *BB = MBB->getBasicBlock();
15931 MachineFunction::iterator I = MBB;
15934 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15935 "Unexpected number of operands");
15937 assert(MI->hasOneMemOperand() &&
15938 "Expected atomic-load-op to have one memoperand");
15940 // Memory Reference
15941 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15942 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15944 unsigned DstReg, SrcReg;
15945 unsigned MemOpndSlot;
15947 unsigned CurOp = 0;
15949 DstReg = MI->getOperand(CurOp++).getReg();
15950 MemOpndSlot = CurOp;
15951 CurOp += X86::AddrNumOperands;
15952 SrcReg = MI->getOperand(CurOp++).getReg();
15954 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15955 MVT::SimpleValueType VT = *RC->vt_begin();
15956 unsigned t1 = MRI.createVirtualRegister(RC);
15957 unsigned t2 = MRI.createVirtualRegister(RC);
15958 unsigned t3 = MRI.createVirtualRegister(RC);
15959 unsigned t4 = MRI.createVirtualRegister(RC);
15960 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15962 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15963 unsigned LOADOpc = getLoadOpcode(VT);
15965 // For the atomic load-arith operator, we generate
15968 // t1 = LOAD [MI.addr]
15970 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15971 // t1 = OP MI.val, EAX
15973 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15979 MachineBasicBlock *thisMBB = MBB;
15980 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15981 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15982 MF->insert(I, mainMBB);
15983 MF->insert(I, sinkMBB);
15985 MachineInstrBuilder MIB;
15987 // Transfer the remainder of BB and its successor edges to sinkMBB.
15988 sinkMBB->splice(sinkMBB->begin(), MBB,
15989 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15990 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15993 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15994 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15995 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15997 NewMO.setIsKill(false);
15998 MIB.addOperand(NewMO);
16000 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16001 unsigned flags = (*MMOI)->getFlags();
16002 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16003 MachineMemOperand *MMO =
16004 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16005 (*MMOI)->getSize(),
16006 (*MMOI)->getBaseAlignment(),
16007 (*MMOI)->getTBAAInfo(),
16008 (*MMOI)->getRanges());
16009 MIB.addMemOperand(MMO);
16012 thisMBB->addSuccessor(mainMBB);
16015 MachineBasicBlock *origMainMBB = mainMBB;
16018 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
16019 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
16021 unsigned Opc = MI->getOpcode();
16024 llvm_unreachable("Unhandled atomic-load-op opcode!");
16025 case X86::ATOMAND8:
16026 case X86::ATOMAND16:
16027 case X86::ATOMAND32:
16028 case X86::ATOMAND64:
16030 case X86::ATOMOR16:
16031 case X86::ATOMOR32:
16032 case X86::ATOMOR64:
16033 case X86::ATOMXOR8:
16034 case X86::ATOMXOR16:
16035 case X86::ATOMXOR32:
16036 case X86::ATOMXOR64: {
16037 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
16038 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
16042 case X86::ATOMNAND8:
16043 case X86::ATOMNAND16:
16044 case X86::ATOMNAND32:
16045 case X86::ATOMNAND64: {
16046 unsigned Tmp = MRI.createVirtualRegister(RC);
16048 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
16049 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
16051 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
16054 case X86::ATOMMAX8:
16055 case X86::ATOMMAX16:
16056 case X86::ATOMMAX32:
16057 case X86::ATOMMAX64:
16058 case X86::ATOMMIN8:
16059 case X86::ATOMMIN16:
16060 case X86::ATOMMIN32:
16061 case X86::ATOMMIN64:
16062 case X86::ATOMUMAX8:
16063 case X86::ATOMUMAX16:
16064 case X86::ATOMUMAX32:
16065 case X86::ATOMUMAX64:
16066 case X86::ATOMUMIN8:
16067 case X86::ATOMUMIN16:
16068 case X86::ATOMUMIN32:
16069 case X86::ATOMUMIN64: {
16071 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
16073 BuildMI(mainMBB, DL, TII->get(CMPOpc))
16077 if (Subtarget->hasCMov()) {
16078 if (VT != MVT::i8) {
16080 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
16084 // Promote i8 to i32 to use CMOV32
16085 const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
16086 const TargetRegisterClass *RC32 =
16087 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
16088 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
16089 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
16090 unsigned Tmp = MRI.createVirtualRegister(RC32);
16092 unsigned Undef = MRI.createVirtualRegister(RC32);
16093 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
16095 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
16098 .addImm(X86::sub_8bit);
16099 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
16102 .addImm(X86::sub_8bit);
16104 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
16108 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
16109 .addReg(Tmp, 0, X86::sub_8bit);
16112 // Use pseudo select and lower them.
16113 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
16114 "Invalid atomic-load-op transformation!");
16115 unsigned SelOpc = getPseudoCMOVOpc(VT);
16116 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
16117 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
16118 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
16119 .addReg(SrcReg).addReg(t4)
16121 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16122 // Replace the original PHI node as mainMBB is changed after CMOV
16124 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
16125 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
16126 Phi->eraseFromParent();
16132 // Copy PhyReg back from virtual register.
16133 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
16136 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16137 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16138 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16140 NewMO.setIsKill(false);
16141 MIB.addOperand(NewMO);
16144 MIB.setMemRefs(MMOBegin, MMOEnd);
16146 // Copy PhyReg back to virtual register.
16147 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
16150 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16152 mainMBB->addSuccessor(origMainMBB);
16153 mainMBB->addSuccessor(sinkMBB);
16156 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16157 TII->get(TargetOpcode::COPY), DstReg)
16160 MI->eraseFromParent();
16164 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
16165 // instructions. They will be translated into a spin-loop or compare-exchange
16169 // dst = atomic-fetch-op MI.addr, MI.val
16175 // t1L = LOAD [MI.addr + 0]
16176 // t1H = LOAD [MI.addr + 4]
16178 // t4L = phi(t1L, t3L / loop)
16179 // t4H = phi(t1H, t3H / loop)
16180 // t2L = OP MI.val.lo, t4L
16181 // t2H = OP MI.val.hi, t4H
16186 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16194 MachineBasicBlock *
16195 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
16196 MachineBasicBlock *MBB) const {
16197 MachineFunction *MF = MBB->getParent();
16198 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16199 DebugLoc DL = MI->getDebugLoc();
16201 MachineRegisterInfo &MRI = MF->getRegInfo();
16203 const BasicBlock *BB = MBB->getBasicBlock();
16204 MachineFunction::iterator I = MBB;
16207 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
16208 "Unexpected number of operands");
16210 assert(MI->hasOneMemOperand() &&
16211 "Expected atomic-load-op32 to have one memoperand");
16213 // Memory Reference
16214 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16215 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16217 unsigned DstLoReg, DstHiReg;
16218 unsigned SrcLoReg, SrcHiReg;
16219 unsigned MemOpndSlot;
16221 unsigned CurOp = 0;
16223 DstLoReg = MI->getOperand(CurOp++).getReg();
16224 DstHiReg = MI->getOperand(CurOp++).getReg();
16225 MemOpndSlot = CurOp;
16226 CurOp += X86::AddrNumOperands;
16227 SrcLoReg = MI->getOperand(CurOp++).getReg();
16228 SrcHiReg = MI->getOperand(CurOp++).getReg();
16230 const TargetRegisterClass *RC = &X86::GR32RegClass;
16231 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
16233 unsigned t1L = MRI.createVirtualRegister(RC);
16234 unsigned t1H = MRI.createVirtualRegister(RC);
16235 unsigned t2L = MRI.createVirtualRegister(RC);
16236 unsigned t2H = MRI.createVirtualRegister(RC);
16237 unsigned t3L = MRI.createVirtualRegister(RC);
16238 unsigned t3H = MRI.createVirtualRegister(RC);
16239 unsigned t4L = MRI.createVirtualRegister(RC);
16240 unsigned t4H = MRI.createVirtualRegister(RC);
16242 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
16243 unsigned LOADOpc = X86::MOV32rm;
16245 // For the atomic load-arith operator, we generate
16248 // t1L = LOAD [MI.addr + 0]
16249 // t1H = LOAD [MI.addr + 4]
16251 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
16252 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
16253 // t2L = OP MI.val.lo, t4L
16254 // t2H = OP MI.val.hi, t4H
16257 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16265 MachineBasicBlock *thisMBB = MBB;
16266 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16267 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16268 MF->insert(I, mainMBB);
16269 MF->insert(I, sinkMBB);
16271 MachineInstrBuilder MIB;
16273 // Transfer the remainder of BB and its successor edges to sinkMBB.
16274 sinkMBB->splice(sinkMBB->begin(), MBB,
16275 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16276 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16280 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
16281 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16282 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16284 NewMO.setIsKill(false);
16285 MIB.addOperand(NewMO);
16287 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16288 unsigned flags = (*MMOI)->getFlags();
16289 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16290 MachineMemOperand *MMO =
16291 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16292 (*MMOI)->getSize(),
16293 (*MMOI)->getBaseAlignment(),
16294 (*MMOI)->getTBAAInfo(),
16295 (*MMOI)->getRanges());
16296 MIB.addMemOperand(MMO);
16298 MachineInstr *LowMI = MIB;
16301 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
16302 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16303 if (i == X86::AddrDisp) {
16304 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
16306 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16308 NewMO.setIsKill(false);
16309 MIB.addOperand(NewMO);
16312 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
16314 thisMBB->addSuccessor(mainMBB);
16317 MachineBasicBlock *origMainMBB = mainMBB;
16320 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
16321 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16322 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
16323 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16325 unsigned Opc = MI->getOpcode();
16328 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
16329 case X86::ATOMAND6432:
16330 case X86::ATOMOR6432:
16331 case X86::ATOMXOR6432:
16332 case X86::ATOMADD6432:
16333 case X86::ATOMSUB6432: {
16335 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16336 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
16338 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
16342 case X86::ATOMNAND6432: {
16343 unsigned HiOpc, NOTOpc;
16344 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
16345 unsigned TmpL = MRI.createVirtualRegister(RC);
16346 unsigned TmpH = MRI.createVirtualRegister(RC);
16347 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16349 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16351 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16352 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16355 case X86::ATOMMAX6432:
16356 case X86::ATOMMIN6432:
16357 case X86::ATOMUMAX6432:
16358 case X86::ATOMUMIN6432: {
16360 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16361 unsigned cL = MRI.createVirtualRegister(RC8);
16362 unsigned cH = MRI.createVirtualRegister(RC8);
16363 unsigned cL32 = MRI.createVirtualRegister(RC);
16364 unsigned cH32 = MRI.createVirtualRegister(RC);
16365 unsigned cc = MRI.createVirtualRegister(RC);
16366 // cl := cmp src_lo, lo
16367 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16368 .addReg(SrcLoReg).addReg(t4L);
16369 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16370 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16371 // ch := cmp src_hi, hi
16372 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16373 .addReg(SrcHiReg).addReg(t4H);
16374 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16375 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16376 // cc := if (src_hi == hi) ? cl : ch;
16377 if (Subtarget->hasCMov()) {
16378 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16379 .addReg(cH32).addReg(cL32);
16381 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16382 .addReg(cH32).addReg(cL32)
16383 .addImm(X86::COND_E);
16384 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16386 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16387 if (Subtarget->hasCMov()) {
16388 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16389 .addReg(SrcLoReg).addReg(t4L);
16390 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16391 .addReg(SrcHiReg).addReg(t4H);
16393 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16394 .addReg(SrcLoReg).addReg(t4L)
16395 .addImm(X86::COND_NE);
16396 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16397 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16398 // 2nd CMOV lowering.
16399 mainMBB->addLiveIn(X86::EFLAGS);
16400 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16401 .addReg(SrcHiReg).addReg(t4H)
16402 .addImm(X86::COND_NE);
16403 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16404 // Replace the original PHI node as mainMBB is changed after CMOV
16406 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16407 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16408 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16409 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16410 PhiL->eraseFromParent();
16411 PhiH->eraseFromParent();
16415 case X86::ATOMSWAP6432: {
16417 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16418 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16419 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16424 // Copy EDX:EAX back from HiReg:LoReg
16425 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16426 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16427 // Copy ECX:EBX from t1H:t1L
16428 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16429 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16431 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16432 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16433 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16435 NewMO.setIsKill(false);
16436 MIB.addOperand(NewMO);
16438 MIB.setMemRefs(MMOBegin, MMOEnd);
16440 // Copy EDX:EAX back to t3H:t3L
16441 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16442 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16444 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16446 mainMBB->addSuccessor(origMainMBB);
16447 mainMBB->addSuccessor(sinkMBB);
16450 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16451 TII->get(TargetOpcode::COPY), DstLoReg)
16453 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16454 TII->get(TargetOpcode::COPY), DstHiReg)
16457 MI->eraseFromParent();
16461 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16462 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16463 // in the .td file.
16464 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16465 const TargetInstrInfo *TII) {
16467 switch (MI->getOpcode()) {
16468 default: llvm_unreachable("illegal opcode!");
16469 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16470 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16471 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16472 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16473 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16474 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16475 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16476 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16479 DebugLoc dl = MI->getDebugLoc();
16480 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16482 unsigned NumArgs = MI->getNumOperands();
16483 for (unsigned i = 1; i < NumArgs; ++i) {
16484 MachineOperand &Op = MI->getOperand(i);
16485 if (!(Op.isReg() && Op.isImplicit()))
16486 MIB.addOperand(Op);
16488 if (MI->hasOneMemOperand())
16489 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16491 BuildMI(*BB, MI, dl,
16492 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16493 .addReg(X86::XMM0);
16495 MI->eraseFromParent();
16499 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16500 // defs in an instruction pattern
16501 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16502 const TargetInstrInfo *TII) {
16504 switch (MI->getOpcode()) {
16505 default: llvm_unreachable("illegal opcode!");
16506 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16507 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16508 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16509 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16510 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16511 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16512 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16513 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16516 DebugLoc dl = MI->getDebugLoc();
16517 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16519 unsigned NumArgs = MI->getNumOperands(); // remove the results
16520 for (unsigned i = 1; i < NumArgs; ++i) {
16521 MachineOperand &Op = MI->getOperand(i);
16522 if (!(Op.isReg() && Op.isImplicit()))
16523 MIB.addOperand(Op);
16525 if (MI->hasOneMemOperand())
16526 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16528 BuildMI(*BB, MI, dl,
16529 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16532 MI->eraseFromParent();
16536 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16537 const TargetInstrInfo *TII,
16538 const X86Subtarget* Subtarget) {
16539 DebugLoc dl = MI->getDebugLoc();
16541 // Address into RAX/EAX, other two args into ECX, EDX.
16542 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16543 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16544 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16545 for (int i = 0; i < X86::AddrNumOperands; ++i)
16546 MIB.addOperand(MI->getOperand(i));
16548 unsigned ValOps = X86::AddrNumOperands;
16549 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16550 .addReg(MI->getOperand(ValOps).getReg());
16551 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16552 .addReg(MI->getOperand(ValOps+1).getReg());
16554 // The instruction doesn't actually take any operands though.
16555 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16557 MI->eraseFromParent(); // The pseudo is gone now.
16561 MachineBasicBlock *
16562 X86TargetLowering::EmitVAARG64WithCustomInserter(
16564 MachineBasicBlock *MBB) const {
16565 // Emit va_arg instruction on X86-64.
16567 // Operands to this pseudo-instruction:
16568 // 0 ) Output : destination address (reg)
16569 // 1-5) Input : va_list address (addr, i64mem)
16570 // 6 ) ArgSize : Size (in bytes) of vararg type
16571 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16572 // 8 ) Align : Alignment of type
16573 // 9 ) EFLAGS (implicit-def)
16575 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16576 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16578 unsigned DestReg = MI->getOperand(0).getReg();
16579 MachineOperand &Base = MI->getOperand(1);
16580 MachineOperand &Scale = MI->getOperand(2);
16581 MachineOperand &Index = MI->getOperand(3);
16582 MachineOperand &Disp = MI->getOperand(4);
16583 MachineOperand &Segment = MI->getOperand(5);
16584 unsigned ArgSize = MI->getOperand(6).getImm();
16585 unsigned ArgMode = MI->getOperand(7).getImm();
16586 unsigned Align = MI->getOperand(8).getImm();
16588 // Memory Reference
16589 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16590 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16591 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16593 // Machine Information
16594 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16595 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16596 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16597 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16598 DebugLoc DL = MI->getDebugLoc();
16600 // struct va_list {
16603 // i64 overflow_area (address)
16604 // i64 reg_save_area (address)
16606 // sizeof(va_list) = 24
16607 // alignment(va_list) = 8
16609 unsigned TotalNumIntRegs = 6;
16610 unsigned TotalNumXMMRegs = 8;
16611 bool UseGPOffset = (ArgMode == 1);
16612 bool UseFPOffset = (ArgMode == 2);
16613 unsigned MaxOffset = TotalNumIntRegs * 8 +
16614 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16616 /* Align ArgSize to a multiple of 8 */
16617 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16618 bool NeedsAlign = (Align > 8);
16620 MachineBasicBlock *thisMBB = MBB;
16621 MachineBasicBlock *overflowMBB;
16622 MachineBasicBlock *offsetMBB;
16623 MachineBasicBlock *endMBB;
16625 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16626 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16627 unsigned OffsetReg = 0;
16629 if (!UseGPOffset && !UseFPOffset) {
16630 // If we only pull from the overflow region, we don't create a branch.
16631 // We don't need to alter control flow.
16632 OffsetDestReg = 0; // unused
16633 OverflowDestReg = DestReg;
16635 offsetMBB = nullptr;
16636 overflowMBB = thisMBB;
16639 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16640 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16641 // If not, pull from overflow_area. (branch to overflowMBB)
16646 // offsetMBB overflowMBB
16651 // Registers for the PHI in endMBB
16652 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16653 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16655 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16656 MachineFunction *MF = MBB->getParent();
16657 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16658 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16659 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16661 MachineFunction::iterator MBBIter = MBB;
16664 // Insert the new basic blocks
16665 MF->insert(MBBIter, offsetMBB);
16666 MF->insert(MBBIter, overflowMBB);
16667 MF->insert(MBBIter, endMBB);
16669 // Transfer the remainder of MBB and its successor edges to endMBB.
16670 endMBB->splice(endMBB->begin(), thisMBB,
16671 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16672 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16674 // Make offsetMBB and overflowMBB successors of thisMBB
16675 thisMBB->addSuccessor(offsetMBB);
16676 thisMBB->addSuccessor(overflowMBB);
16678 // endMBB is a successor of both offsetMBB and overflowMBB
16679 offsetMBB->addSuccessor(endMBB);
16680 overflowMBB->addSuccessor(endMBB);
16682 // Load the offset value into a register
16683 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16684 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16688 .addDisp(Disp, UseFPOffset ? 4 : 0)
16689 .addOperand(Segment)
16690 .setMemRefs(MMOBegin, MMOEnd);
16692 // Check if there is enough room left to pull this argument.
16693 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16695 .addImm(MaxOffset + 8 - ArgSizeA8);
16697 // Branch to "overflowMBB" if offset >= max
16698 // Fall through to "offsetMBB" otherwise
16699 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16700 .addMBB(overflowMBB);
16703 // In offsetMBB, emit code to use the reg_save_area.
16705 assert(OffsetReg != 0);
16707 // Read the reg_save_area address.
16708 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16709 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16714 .addOperand(Segment)
16715 .setMemRefs(MMOBegin, MMOEnd);
16717 // Zero-extend the offset
16718 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16719 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16722 .addImm(X86::sub_32bit);
16724 // Add the offset to the reg_save_area to get the final address.
16725 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16726 .addReg(OffsetReg64)
16727 .addReg(RegSaveReg);
16729 // Compute the offset for the next argument
16730 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16731 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16733 .addImm(UseFPOffset ? 16 : 8);
16735 // Store it back into the va_list.
16736 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16740 .addDisp(Disp, UseFPOffset ? 4 : 0)
16741 .addOperand(Segment)
16742 .addReg(NextOffsetReg)
16743 .setMemRefs(MMOBegin, MMOEnd);
16746 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16751 // Emit code to use overflow area
16754 // Load the overflow_area address into a register.
16755 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16756 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16761 .addOperand(Segment)
16762 .setMemRefs(MMOBegin, MMOEnd);
16764 // If we need to align it, do so. Otherwise, just copy the address
16765 // to OverflowDestReg.
16767 // Align the overflow address
16768 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16769 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16771 // aligned_addr = (addr + (align-1)) & ~(align-1)
16772 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16773 .addReg(OverflowAddrReg)
16776 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16778 .addImm(~(uint64_t)(Align-1));
16780 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16781 .addReg(OverflowAddrReg);
16784 // Compute the next overflow address after this argument.
16785 // (the overflow address should be kept 8-byte aligned)
16786 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16787 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16788 .addReg(OverflowDestReg)
16789 .addImm(ArgSizeA8);
16791 // Store the new overflow address.
16792 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16797 .addOperand(Segment)
16798 .addReg(NextAddrReg)
16799 .setMemRefs(MMOBegin, MMOEnd);
16801 // If we branched, emit the PHI to the front of endMBB.
16803 BuildMI(*endMBB, endMBB->begin(), DL,
16804 TII->get(X86::PHI), DestReg)
16805 .addReg(OffsetDestReg).addMBB(offsetMBB)
16806 .addReg(OverflowDestReg).addMBB(overflowMBB);
16809 // Erase the pseudo instruction
16810 MI->eraseFromParent();
16815 MachineBasicBlock *
16816 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16818 MachineBasicBlock *MBB) const {
16819 // Emit code to save XMM registers to the stack. The ABI says that the
16820 // number of registers to save is given in %al, so it's theoretically
16821 // possible to do an indirect jump trick to avoid saving all of them,
16822 // however this code takes a simpler approach and just executes all
16823 // of the stores if %al is non-zero. It's less code, and it's probably
16824 // easier on the hardware branch predictor, and stores aren't all that
16825 // expensive anyway.
16827 // Create the new basic blocks. One block contains all the XMM stores,
16828 // and one block is the final destination regardless of whether any
16829 // stores were performed.
16830 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16831 MachineFunction *F = MBB->getParent();
16832 MachineFunction::iterator MBBIter = MBB;
16834 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16835 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16836 F->insert(MBBIter, XMMSaveMBB);
16837 F->insert(MBBIter, EndMBB);
16839 // Transfer the remainder of MBB and its successor edges to EndMBB.
16840 EndMBB->splice(EndMBB->begin(), MBB,
16841 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16842 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16844 // The original block will now fall through to the XMM save block.
16845 MBB->addSuccessor(XMMSaveMBB);
16846 // The XMMSaveMBB will fall through to the end block.
16847 XMMSaveMBB->addSuccessor(EndMBB);
16849 // Now add the instructions.
16850 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16851 DebugLoc DL = MI->getDebugLoc();
16853 unsigned CountReg = MI->getOperand(0).getReg();
16854 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16855 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16857 if (!Subtarget->isTargetWin64()) {
16858 // If %al is 0, branch around the XMM save block.
16859 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16860 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16861 MBB->addSuccessor(EndMBB);
16864 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16865 // that was just emitted, but clearly shouldn't be "saved".
16866 assert((MI->getNumOperands() <= 3 ||
16867 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16868 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16869 && "Expected last argument to be EFLAGS");
16870 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16871 // In the XMM save block, save all the XMM argument registers.
16872 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16873 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16874 MachineMemOperand *MMO =
16875 F->getMachineMemOperand(
16876 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16877 MachineMemOperand::MOStore,
16878 /*Size=*/16, /*Align=*/16);
16879 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16880 .addFrameIndex(RegSaveFrameIndex)
16881 .addImm(/*Scale=*/1)
16882 .addReg(/*IndexReg=*/0)
16883 .addImm(/*Disp=*/Offset)
16884 .addReg(/*Segment=*/0)
16885 .addReg(MI->getOperand(i).getReg())
16886 .addMemOperand(MMO);
16889 MI->eraseFromParent(); // The pseudo instruction is gone now.
16894 // The EFLAGS operand of SelectItr might be missing a kill marker
16895 // because there were multiple uses of EFLAGS, and ISel didn't know
16896 // which to mark. Figure out whether SelectItr should have had a
16897 // kill marker, and set it if it should. Returns the correct kill
16899 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16900 MachineBasicBlock* BB,
16901 const TargetRegisterInfo* TRI) {
16902 // Scan forward through BB for a use/def of EFLAGS.
16903 MachineBasicBlock::iterator miI(std::next(SelectItr));
16904 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16905 const MachineInstr& mi = *miI;
16906 if (mi.readsRegister(X86::EFLAGS))
16908 if (mi.definesRegister(X86::EFLAGS))
16909 break; // Should have kill-flag - update below.
16912 // If we hit the end of the block, check whether EFLAGS is live into a
16914 if (miI == BB->end()) {
16915 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16916 sEnd = BB->succ_end();
16917 sItr != sEnd; ++sItr) {
16918 MachineBasicBlock* succ = *sItr;
16919 if (succ->isLiveIn(X86::EFLAGS))
16924 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16925 // out. SelectMI should have a kill flag on EFLAGS.
16926 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16930 MachineBasicBlock *
16931 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16932 MachineBasicBlock *BB) const {
16933 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16934 DebugLoc DL = MI->getDebugLoc();
16936 // To "insert" a SELECT_CC instruction, we actually have to insert the
16937 // diamond control-flow pattern. The incoming instruction knows the
16938 // destination vreg to set, the condition code register to branch on, the
16939 // true/false values to select between, and a branch opcode to use.
16940 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16941 MachineFunction::iterator It = BB;
16947 // cmpTY ccX, r1, r2
16949 // fallthrough --> copy0MBB
16950 MachineBasicBlock *thisMBB = BB;
16951 MachineFunction *F = BB->getParent();
16952 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16953 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16954 F->insert(It, copy0MBB);
16955 F->insert(It, sinkMBB);
16957 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16958 // live into the sink and copy blocks.
16959 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16960 if (!MI->killsRegister(X86::EFLAGS) &&
16961 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16962 copy0MBB->addLiveIn(X86::EFLAGS);
16963 sinkMBB->addLiveIn(X86::EFLAGS);
16966 // Transfer the remainder of BB and its successor edges to sinkMBB.
16967 sinkMBB->splice(sinkMBB->begin(), BB,
16968 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16969 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16971 // Add the true and fallthrough blocks as its successors.
16972 BB->addSuccessor(copy0MBB);
16973 BB->addSuccessor(sinkMBB);
16975 // Create the conditional branch instruction.
16977 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16978 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16981 // %FalseValue = ...
16982 // # fallthrough to sinkMBB
16983 copy0MBB->addSuccessor(sinkMBB);
16986 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16988 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16989 TII->get(X86::PHI), MI->getOperand(0).getReg())
16990 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16991 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16993 MI->eraseFromParent(); // The pseudo instruction is gone now.
16997 MachineBasicBlock *
16998 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16999 bool Is64Bit) const {
17000 MachineFunction *MF = BB->getParent();
17001 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17002 DebugLoc DL = MI->getDebugLoc();
17003 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17005 assert(MF->shouldSplitStack());
17007 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17008 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17011 // ... [Till the alloca]
17012 // If stacklet is not large enough, jump to mallocMBB
17015 // Allocate by subtracting from RSP
17016 // Jump to continueMBB
17019 // Allocate by call to runtime
17023 // [rest of original BB]
17026 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17027 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17028 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17030 MachineRegisterInfo &MRI = MF->getRegInfo();
17031 const TargetRegisterClass *AddrRegClass =
17032 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17034 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17035 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17036 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17037 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17038 sizeVReg = MI->getOperand(1).getReg(),
17039 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17041 MachineFunction::iterator MBBIter = BB;
17044 MF->insert(MBBIter, bumpMBB);
17045 MF->insert(MBBIter, mallocMBB);
17046 MF->insert(MBBIter, continueMBB);
17048 continueMBB->splice(continueMBB->begin(), BB,
17049 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17050 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17052 // Add code to the main basic block to check if the stack limit has been hit,
17053 // and if so, jump to mallocMBB otherwise to bumpMBB.
17054 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17055 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17056 .addReg(tmpSPVReg).addReg(sizeVReg);
17057 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17058 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17059 .addReg(SPLimitVReg);
17060 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17062 // bumpMBB simply decreases the stack pointer, since we know the current
17063 // stacklet has enough space.
17064 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17065 .addReg(SPLimitVReg);
17066 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17067 .addReg(SPLimitVReg);
17068 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17070 // Calls into a routine in libgcc to allocate more space from the heap.
17071 const uint32_t *RegMask =
17072 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17074 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17076 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17077 .addExternalSymbol("__morestack_allocate_stack_space")
17078 .addRegMask(RegMask)
17079 .addReg(X86::RDI, RegState::Implicit)
17080 .addReg(X86::RAX, RegState::ImplicitDefine);
17082 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17084 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17085 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17086 .addExternalSymbol("__morestack_allocate_stack_space")
17087 .addRegMask(RegMask)
17088 .addReg(X86::EAX, RegState::ImplicitDefine);
17092 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17095 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17096 .addReg(Is64Bit ? X86::RAX : X86::EAX);
17097 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17099 // Set up the CFG correctly.
17100 BB->addSuccessor(bumpMBB);
17101 BB->addSuccessor(mallocMBB);
17102 mallocMBB->addSuccessor(continueMBB);
17103 bumpMBB->addSuccessor(continueMBB);
17105 // Take care of the PHI nodes.
17106 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17107 MI->getOperand(0).getReg())
17108 .addReg(mallocPtrVReg).addMBB(mallocMBB)
17109 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17111 // Delete the original pseudo instruction.
17112 MI->eraseFromParent();
17115 return continueMBB;
17118 MachineBasicBlock *
17119 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17120 MachineBasicBlock *BB) const {
17121 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17122 DebugLoc DL = MI->getDebugLoc();
17124 assert(!Subtarget->isTargetMacho());
17126 // The lowering is pretty easy: we're just emitting the call to _alloca. The
17127 // non-trivial part is impdef of ESP.
17129 if (Subtarget->isTargetWin64()) {
17130 if (Subtarget->isTargetCygMing()) {
17131 // ___chkstk(Mingw64):
17132 // Clobbers R10, R11, RAX and EFLAGS.
17134 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17135 .addExternalSymbol("___chkstk")
17136 .addReg(X86::RAX, RegState::Implicit)
17137 .addReg(X86::RSP, RegState::Implicit)
17138 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17139 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17140 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17142 // __chkstk(MSVCRT): does not update stack pointer.
17143 // Clobbers R10, R11 and EFLAGS.
17144 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17145 .addExternalSymbol("__chkstk")
17146 .addReg(X86::RAX, RegState::Implicit)
17147 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17148 // RAX has the offset to be subtracted from RSP.
17149 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17154 const char *StackProbeSymbol =
17155 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17157 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17158 .addExternalSymbol(StackProbeSymbol)
17159 .addReg(X86::EAX, RegState::Implicit)
17160 .addReg(X86::ESP, RegState::Implicit)
17161 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17162 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17163 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17166 MI->eraseFromParent(); // The pseudo instruction is gone now.
17170 MachineBasicBlock *
17171 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17172 MachineBasicBlock *BB) const {
17173 // This is pretty easy. We're taking the value that we received from
17174 // our load from the relocation, sticking it in either RDI (x86-64)
17175 // or EAX and doing an indirect call. The return value will then
17176 // be in the normal return register.
17177 MachineFunction *F = BB->getParent();
17178 const X86InstrInfo *TII
17179 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17180 DebugLoc DL = MI->getDebugLoc();
17182 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17183 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17185 // Get a register mask for the lowered call.
17186 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17187 // proper register mask.
17188 const uint32_t *RegMask =
17189 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17190 if (Subtarget->is64Bit()) {
17191 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17192 TII->get(X86::MOV64rm), X86::RDI)
17194 .addImm(0).addReg(0)
17195 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17196 MI->getOperand(3).getTargetFlags())
17198 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17199 addDirectMem(MIB, X86::RDI);
17200 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17201 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17202 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17203 TII->get(X86::MOV32rm), X86::EAX)
17205 .addImm(0).addReg(0)
17206 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17207 MI->getOperand(3).getTargetFlags())
17209 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17210 addDirectMem(MIB, X86::EAX);
17211 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17213 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17214 TII->get(X86::MOV32rm), X86::EAX)
17215 .addReg(TII->getGlobalBaseReg(F))
17216 .addImm(0).addReg(0)
17217 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17218 MI->getOperand(3).getTargetFlags())
17220 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17221 addDirectMem(MIB, X86::EAX);
17222 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17225 MI->eraseFromParent(); // The pseudo instruction is gone now.
17229 MachineBasicBlock *
17230 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17231 MachineBasicBlock *MBB) const {
17232 DebugLoc DL = MI->getDebugLoc();
17233 MachineFunction *MF = MBB->getParent();
17234 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17235 MachineRegisterInfo &MRI = MF->getRegInfo();
17237 const BasicBlock *BB = MBB->getBasicBlock();
17238 MachineFunction::iterator I = MBB;
17241 // Memory Reference
17242 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17243 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17246 unsigned MemOpndSlot = 0;
17248 unsigned CurOp = 0;
17250 DstReg = MI->getOperand(CurOp++).getReg();
17251 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17252 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17253 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17254 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17256 MemOpndSlot = CurOp;
17258 MVT PVT = getPointerTy();
17259 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17260 "Invalid Pointer Size!");
17262 // For v = setjmp(buf), we generate
17265 // buf[LabelOffset] = restoreMBB
17266 // SjLjSetup restoreMBB
17272 // v = phi(main, restore)
17277 MachineBasicBlock *thisMBB = MBB;
17278 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17279 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17280 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17281 MF->insert(I, mainMBB);
17282 MF->insert(I, sinkMBB);
17283 MF->push_back(restoreMBB);
17285 MachineInstrBuilder MIB;
17287 // Transfer the remainder of BB and its successor edges to sinkMBB.
17288 sinkMBB->splice(sinkMBB->begin(), MBB,
17289 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17290 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17293 unsigned PtrStoreOpc = 0;
17294 unsigned LabelReg = 0;
17295 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17296 Reloc::Model RM = MF->getTarget().getRelocationModel();
17297 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17298 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17300 // Prepare IP either in reg or imm.
17301 if (!UseImmLabel) {
17302 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17303 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17304 LabelReg = MRI.createVirtualRegister(PtrRC);
17305 if (Subtarget->is64Bit()) {
17306 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17310 .addMBB(restoreMBB)
17313 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17314 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17315 .addReg(XII->getGlobalBaseReg(MF))
17318 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17322 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17324 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17325 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17326 if (i == X86::AddrDisp)
17327 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17329 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17332 MIB.addReg(LabelReg);
17334 MIB.addMBB(restoreMBB);
17335 MIB.setMemRefs(MMOBegin, MMOEnd);
17337 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17338 .addMBB(restoreMBB);
17340 const X86RegisterInfo *RegInfo =
17341 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17342 MIB.addRegMask(RegInfo->getNoPreservedMask());
17343 thisMBB->addSuccessor(mainMBB);
17344 thisMBB->addSuccessor(restoreMBB);
17348 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17349 mainMBB->addSuccessor(sinkMBB);
17352 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17353 TII->get(X86::PHI), DstReg)
17354 .addReg(mainDstReg).addMBB(mainMBB)
17355 .addReg(restoreDstReg).addMBB(restoreMBB);
17358 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17359 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17360 restoreMBB->addSuccessor(sinkMBB);
17362 MI->eraseFromParent();
17366 MachineBasicBlock *
17367 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17368 MachineBasicBlock *MBB) const {
17369 DebugLoc DL = MI->getDebugLoc();
17370 MachineFunction *MF = MBB->getParent();
17371 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17372 MachineRegisterInfo &MRI = MF->getRegInfo();
17374 // Memory Reference
17375 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17376 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17378 MVT PVT = getPointerTy();
17379 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17380 "Invalid Pointer Size!");
17382 const TargetRegisterClass *RC =
17383 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17384 unsigned Tmp = MRI.createVirtualRegister(RC);
17385 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17386 const X86RegisterInfo *RegInfo =
17387 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17388 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17389 unsigned SP = RegInfo->getStackRegister();
17391 MachineInstrBuilder MIB;
17393 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17394 const int64_t SPOffset = 2 * PVT.getStoreSize();
17396 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17397 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17400 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17401 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17402 MIB.addOperand(MI->getOperand(i));
17403 MIB.setMemRefs(MMOBegin, MMOEnd);
17405 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17406 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17407 if (i == X86::AddrDisp)
17408 MIB.addDisp(MI->getOperand(i), LabelOffset);
17410 MIB.addOperand(MI->getOperand(i));
17412 MIB.setMemRefs(MMOBegin, MMOEnd);
17414 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17415 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17416 if (i == X86::AddrDisp)
17417 MIB.addDisp(MI->getOperand(i), SPOffset);
17419 MIB.addOperand(MI->getOperand(i));
17421 MIB.setMemRefs(MMOBegin, MMOEnd);
17423 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17425 MI->eraseFromParent();
17429 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17430 // accumulator loops. Writing back to the accumulator allows the coalescer
17431 // to remove extra copies in the loop.
17432 MachineBasicBlock *
17433 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17434 MachineBasicBlock *MBB) const {
17435 MachineOperand &AddendOp = MI->getOperand(3);
17437 // Bail out early if the addend isn't a register - we can't switch these.
17438 if (!AddendOp.isReg())
17441 MachineFunction &MF = *MBB->getParent();
17442 MachineRegisterInfo &MRI = MF.getRegInfo();
17444 // Check whether the addend is defined by a PHI:
17445 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17446 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17447 if (!AddendDef.isPHI())
17450 // Look for the following pattern:
17452 // %addend = phi [%entry, 0], [%loop, %result]
17454 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17458 // %addend = phi [%entry, 0], [%loop, %result]
17460 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17462 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17463 assert(AddendDef.getOperand(i).isReg());
17464 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17465 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17466 if (&PHISrcInst == MI) {
17467 // Found a matching instruction.
17468 unsigned NewFMAOpc = 0;
17469 switch (MI->getOpcode()) {
17470 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17471 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17472 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17473 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17474 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17475 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17476 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17477 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17478 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17479 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17480 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17481 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17482 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17483 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17484 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17485 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17486 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17487 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17488 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17489 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17490 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17491 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17492 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17493 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17494 default: llvm_unreachable("Unrecognized FMA variant.");
17497 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17498 MachineInstrBuilder MIB =
17499 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17500 .addOperand(MI->getOperand(0))
17501 .addOperand(MI->getOperand(3))
17502 .addOperand(MI->getOperand(2))
17503 .addOperand(MI->getOperand(1));
17504 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17505 MI->eraseFromParent();
17512 MachineBasicBlock *
17513 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17514 MachineBasicBlock *BB) const {
17515 switch (MI->getOpcode()) {
17516 default: llvm_unreachable("Unexpected instr type to insert");
17517 case X86::TAILJMPd64:
17518 case X86::TAILJMPr64:
17519 case X86::TAILJMPm64:
17520 llvm_unreachable("TAILJMP64 would not be touched here.");
17521 case X86::TCRETURNdi64:
17522 case X86::TCRETURNri64:
17523 case X86::TCRETURNmi64:
17525 case X86::WIN_ALLOCA:
17526 return EmitLoweredWinAlloca(MI, BB);
17527 case X86::SEG_ALLOCA_32:
17528 return EmitLoweredSegAlloca(MI, BB, false);
17529 case X86::SEG_ALLOCA_64:
17530 return EmitLoweredSegAlloca(MI, BB, true);
17531 case X86::TLSCall_32:
17532 case X86::TLSCall_64:
17533 return EmitLoweredTLSCall(MI, BB);
17534 case X86::CMOV_GR8:
17535 case X86::CMOV_FR32:
17536 case X86::CMOV_FR64:
17537 case X86::CMOV_V4F32:
17538 case X86::CMOV_V2F64:
17539 case X86::CMOV_V2I64:
17540 case X86::CMOV_V8F32:
17541 case X86::CMOV_V4F64:
17542 case X86::CMOV_V4I64:
17543 case X86::CMOV_V16F32:
17544 case X86::CMOV_V8F64:
17545 case X86::CMOV_V8I64:
17546 case X86::CMOV_GR16:
17547 case X86::CMOV_GR32:
17548 case X86::CMOV_RFP32:
17549 case X86::CMOV_RFP64:
17550 case X86::CMOV_RFP80:
17551 return EmitLoweredSelect(MI, BB);
17553 case X86::FP32_TO_INT16_IN_MEM:
17554 case X86::FP32_TO_INT32_IN_MEM:
17555 case X86::FP32_TO_INT64_IN_MEM:
17556 case X86::FP64_TO_INT16_IN_MEM:
17557 case X86::FP64_TO_INT32_IN_MEM:
17558 case X86::FP64_TO_INT64_IN_MEM:
17559 case X86::FP80_TO_INT16_IN_MEM:
17560 case X86::FP80_TO_INT32_IN_MEM:
17561 case X86::FP80_TO_INT64_IN_MEM: {
17562 MachineFunction *F = BB->getParent();
17563 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17564 DebugLoc DL = MI->getDebugLoc();
17566 // Change the floating point control register to use "round towards zero"
17567 // mode when truncating to an integer value.
17568 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17569 addFrameReference(BuildMI(*BB, MI, DL,
17570 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17572 // Load the old value of the high byte of the control word...
17574 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17575 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17578 // Set the high part to be round to zero...
17579 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17582 // Reload the modified control word now...
17583 addFrameReference(BuildMI(*BB, MI, DL,
17584 TII->get(X86::FLDCW16m)), CWFrameIdx);
17586 // Restore the memory image of control word to original value
17587 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17590 // Get the X86 opcode to use.
17592 switch (MI->getOpcode()) {
17593 default: llvm_unreachable("illegal opcode!");
17594 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17595 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17596 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17597 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17598 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17599 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17600 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17601 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17602 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17606 MachineOperand &Op = MI->getOperand(0);
17608 AM.BaseType = X86AddressMode::RegBase;
17609 AM.Base.Reg = Op.getReg();
17611 AM.BaseType = X86AddressMode::FrameIndexBase;
17612 AM.Base.FrameIndex = Op.getIndex();
17614 Op = MI->getOperand(1);
17616 AM.Scale = Op.getImm();
17617 Op = MI->getOperand(2);
17619 AM.IndexReg = Op.getImm();
17620 Op = MI->getOperand(3);
17621 if (Op.isGlobal()) {
17622 AM.GV = Op.getGlobal();
17624 AM.Disp = Op.getImm();
17626 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17627 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17629 // Reload the original control word now.
17630 addFrameReference(BuildMI(*BB, MI, DL,
17631 TII->get(X86::FLDCW16m)), CWFrameIdx);
17633 MI->eraseFromParent(); // The pseudo instruction is gone now.
17636 // String/text processing lowering.
17637 case X86::PCMPISTRM128REG:
17638 case X86::VPCMPISTRM128REG:
17639 case X86::PCMPISTRM128MEM:
17640 case X86::VPCMPISTRM128MEM:
17641 case X86::PCMPESTRM128REG:
17642 case X86::VPCMPESTRM128REG:
17643 case X86::PCMPESTRM128MEM:
17644 case X86::VPCMPESTRM128MEM:
17645 assert(Subtarget->hasSSE42() &&
17646 "Target must have SSE4.2 or AVX features enabled");
17647 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17649 // String/text processing lowering.
17650 case X86::PCMPISTRIREG:
17651 case X86::VPCMPISTRIREG:
17652 case X86::PCMPISTRIMEM:
17653 case X86::VPCMPISTRIMEM:
17654 case X86::PCMPESTRIREG:
17655 case X86::VPCMPESTRIREG:
17656 case X86::PCMPESTRIMEM:
17657 case X86::VPCMPESTRIMEM:
17658 assert(Subtarget->hasSSE42() &&
17659 "Target must have SSE4.2 or AVX features enabled");
17660 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17662 // Thread synchronization.
17664 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17668 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17670 // Atomic Lowering.
17671 case X86::ATOMAND8:
17672 case X86::ATOMAND16:
17673 case X86::ATOMAND32:
17674 case X86::ATOMAND64:
17677 case X86::ATOMOR16:
17678 case X86::ATOMOR32:
17679 case X86::ATOMOR64:
17681 case X86::ATOMXOR16:
17682 case X86::ATOMXOR8:
17683 case X86::ATOMXOR32:
17684 case X86::ATOMXOR64:
17686 case X86::ATOMNAND8:
17687 case X86::ATOMNAND16:
17688 case X86::ATOMNAND32:
17689 case X86::ATOMNAND64:
17691 case X86::ATOMMAX8:
17692 case X86::ATOMMAX16:
17693 case X86::ATOMMAX32:
17694 case X86::ATOMMAX64:
17696 case X86::ATOMMIN8:
17697 case X86::ATOMMIN16:
17698 case X86::ATOMMIN32:
17699 case X86::ATOMMIN64:
17701 case X86::ATOMUMAX8:
17702 case X86::ATOMUMAX16:
17703 case X86::ATOMUMAX32:
17704 case X86::ATOMUMAX64:
17706 case X86::ATOMUMIN8:
17707 case X86::ATOMUMIN16:
17708 case X86::ATOMUMIN32:
17709 case X86::ATOMUMIN64:
17710 return EmitAtomicLoadArith(MI, BB);
17712 // This group does 64-bit operations on a 32-bit host.
17713 case X86::ATOMAND6432:
17714 case X86::ATOMOR6432:
17715 case X86::ATOMXOR6432:
17716 case X86::ATOMNAND6432:
17717 case X86::ATOMADD6432:
17718 case X86::ATOMSUB6432:
17719 case X86::ATOMMAX6432:
17720 case X86::ATOMMIN6432:
17721 case X86::ATOMUMAX6432:
17722 case X86::ATOMUMIN6432:
17723 case X86::ATOMSWAP6432:
17724 return EmitAtomicLoadArith6432(MI, BB);
17726 case X86::VASTART_SAVE_XMM_REGS:
17727 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17729 case X86::VAARG_64:
17730 return EmitVAARG64WithCustomInserter(MI, BB);
17732 case X86::EH_SjLj_SetJmp32:
17733 case X86::EH_SjLj_SetJmp64:
17734 return emitEHSjLjSetJmp(MI, BB);
17736 case X86::EH_SjLj_LongJmp32:
17737 case X86::EH_SjLj_LongJmp64:
17738 return emitEHSjLjLongJmp(MI, BB);
17740 case TargetOpcode::STACKMAP:
17741 case TargetOpcode::PATCHPOINT:
17742 return emitPatchPoint(MI, BB);
17744 case X86::VFMADDPDr213r:
17745 case X86::VFMADDPSr213r:
17746 case X86::VFMADDSDr213r:
17747 case X86::VFMADDSSr213r:
17748 case X86::VFMSUBPDr213r:
17749 case X86::VFMSUBPSr213r:
17750 case X86::VFMSUBSDr213r:
17751 case X86::VFMSUBSSr213r:
17752 case X86::VFNMADDPDr213r:
17753 case X86::VFNMADDPSr213r:
17754 case X86::VFNMADDSDr213r:
17755 case X86::VFNMADDSSr213r:
17756 case X86::VFNMSUBPDr213r:
17757 case X86::VFNMSUBPSr213r:
17758 case X86::VFNMSUBSDr213r:
17759 case X86::VFNMSUBSSr213r:
17760 case X86::VFMADDPDr213rY:
17761 case X86::VFMADDPSr213rY:
17762 case X86::VFMSUBPDr213rY:
17763 case X86::VFMSUBPSr213rY:
17764 case X86::VFNMADDPDr213rY:
17765 case X86::VFNMADDPSr213rY:
17766 case X86::VFNMSUBPDr213rY:
17767 case X86::VFNMSUBPSr213rY:
17768 return emitFMA3Instr(MI, BB);
17772 //===----------------------------------------------------------------------===//
17773 // X86 Optimization Hooks
17774 //===----------------------------------------------------------------------===//
17776 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17779 const SelectionDAG &DAG,
17780 unsigned Depth) const {
17781 unsigned BitWidth = KnownZero.getBitWidth();
17782 unsigned Opc = Op.getOpcode();
17783 assert((Opc >= ISD::BUILTIN_OP_END ||
17784 Opc == ISD::INTRINSIC_WO_CHAIN ||
17785 Opc == ISD::INTRINSIC_W_CHAIN ||
17786 Opc == ISD::INTRINSIC_VOID) &&
17787 "Should use MaskedValueIsZero if you don't know whether Op"
17788 " is a target node!");
17790 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17804 // These nodes' second result is a boolean.
17805 if (Op.getResNo() == 0)
17808 case X86ISD::SETCC:
17809 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17811 case ISD::INTRINSIC_WO_CHAIN: {
17812 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17813 unsigned NumLoBits = 0;
17816 case Intrinsic::x86_sse_movmsk_ps:
17817 case Intrinsic::x86_avx_movmsk_ps_256:
17818 case Intrinsic::x86_sse2_movmsk_pd:
17819 case Intrinsic::x86_avx_movmsk_pd_256:
17820 case Intrinsic::x86_mmx_pmovmskb:
17821 case Intrinsic::x86_sse2_pmovmskb_128:
17822 case Intrinsic::x86_avx2_pmovmskb: {
17823 // High bits of movmskp{s|d}, pmovmskb are known zero.
17825 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17826 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17827 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17828 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17829 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17830 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17831 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17832 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17834 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17843 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17845 const SelectionDAG &,
17846 unsigned Depth) const {
17847 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17848 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17849 return Op.getValueType().getScalarType().getSizeInBits();
17855 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17856 /// node is a GlobalAddress + offset.
17857 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17858 const GlobalValue* &GA,
17859 int64_t &Offset) const {
17860 if (N->getOpcode() == X86ISD::Wrapper) {
17861 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17862 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17863 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17867 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17870 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17871 /// same as extracting the high 128-bit part of 256-bit vector and then
17872 /// inserting the result into the low part of a new 256-bit vector
17873 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17874 EVT VT = SVOp->getValueType(0);
17875 unsigned NumElems = VT.getVectorNumElements();
17877 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17878 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17879 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17880 SVOp->getMaskElt(j) >= 0)
17886 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17887 /// same as extracting the low 128-bit part of 256-bit vector and then
17888 /// inserting the result into the high part of a new 256-bit vector
17889 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17890 EVT VT = SVOp->getValueType(0);
17891 unsigned NumElems = VT.getVectorNumElements();
17893 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17894 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17895 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17896 SVOp->getMaskElt(j) >= 0)
17902 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17903 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17904 TargetLowering::DAGCombinerInfo &DCI,
17905 const X86Subtarget* Subtarget) {
17907 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17908 SDValue V1 = SVOp->getOperand(0);
17909 SDValue V2 = SVOp->getOperand(1);
17910 EVT VT = SVOp->getValueType(0);
17911 unsigned NumElems = VT.getVectorNumElements();
17913 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17914 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17918 // V UNDEF BUILD_VECTOR UNDEF
17920 // CONCAT_VECTOR CONCAT_VECTOR
17923 // RESULT: V + zero extended
17925 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17926 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17927 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17930 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17933 // To match the shuffle mask, the first half of the mask should
17934 // be exactly the first vector, and all the rest a splat with the
17935 // first element of the second one.
17936 for (unsigned i = 0; i != NumElems/2; ++i)
17937 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17938 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17941 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17942 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17943 if (Ld->hasNUsesOfValue(1, 0)) {
17944 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17945 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17947 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17949 Ld->getPointerInfo(),
17950 Ld->getAlignment(),
17951 false/*isVolatile*/, true/*ReadMem*/,
17952 false/*WriteMem*/);
17954 // Make sure the newly-created LOAD is in the same position as Ld in
17955 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17956 // and update uses of Ld's output chain to use the TokenFactor.
17957 if (Ld->hasAnyUseOfValue(1)) {
17958 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17959 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17960 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17961 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17962 SDValue(ResNode.getNode(), 1));
17965 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17969 // Emit a zeroed vector and insert the desired subvector on its
17971 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17972 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17973 return DCI.CombineTo(N, InsV);
17976 //===--------------------------------------------------------------------===//
17977 // Combine some shuffles into subvector extracts and inserts:
17980 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17981 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17982 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17983 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17984 return DCI.CombineTo(N, InsV);
17987 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17988 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17989 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17990 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17991 return DCI.CombineTo(N, InsV);
17997 /// PerformShuffleCombine - Performs several different shuffle combines.
17998 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17999 TargetLowering::DAGCombinerInfo &DCI,
18000 const X86Subtarget *Subtarget) {
18002 SDValue N0 = N->getOperand(0);
18003 SDValue N1 = N->getOperand(1);
18004 EVT VT = N->getValueType(0);
18006 // Don't create instructions with illegal types after legalize types has run.
18007 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18008 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18011 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18012 if (Subtarget->hasFp256() && VT.is256BitVector() &&
18013 N->getOpcode() == ISD::VECTOR_SHUFFLE)
18014 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18016 // During Type Legalization, when promoting illegal vector types,
18017 // the backend might introduce new shuffle dag nodes and bitcasts.
18019 // This code performs the following transformation:
18020 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18021 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18023 // We do this only if both the bitcast and the BINOP dag nodes have
18024 // one use. Also, perform this transformation only if the new binary
18025 // operation is legal. This is to avoid introducing dag nodes that
18026 // potentially need to be further expanded (or custom lowered) into a
18027 // less optimal sequence of dag nodes.
18028 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18029 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18030 N0.getOpcode() == ISD::BITCAST) {
18031 SDValue BC0 = N0.getOperand(0);
18032 EVT SVT = BC0.getValueType();
18033 unsigned Opcode = BC0.getOpcode();
18034 unsigned NumElts = VT.getVectorNumElements();
18036 if (BC0.hasOneUse() && SVT.isVector() &&
18037 SVT.getVectorNumElements() * 2 == NumElts &&
18038 TLI.isOperationLegal(Opcode, VT)) {
18039 bool CanFold = false;
18051 unsigned SVTNumElts = SVT.getVectorNumElements();
18052 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18053 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18054 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18055 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18056 CanFold = SVOp->getMaskElt(i) < 0;
18059 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18060 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18061 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18062 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18067 // Only handle 128 wide vector from here on.
18068 if (!VT.is128BitVector())
18071 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18072 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18073 // consecutive, non-overlapping, and in the right order.
18074 SmallVector<SDValue, 16> Elts;
18075 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18076 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18078 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18081 /// PerformTruncateCombine - Converts truncate operation to
18082 /// a sequence of vector shuffle operations.
18083 /// It is possible when we truncate 256-bit vector to 128-bit vector
18084 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18085 TargetLowering::DAGCombinerInfo &DCI,
18086 const X86Subtarget *Subtarget) {
18090 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18091 /// specific shuffle of a load can be folded into a single element load.
18092 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18093 /// shuffles have been customed lowered so we need to handle those here.
18094 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18095 TargetLowering::DAGCombinerInfo &DCI) {
18096 if (DCI.isBeforeLegalizeOps())
18099 SDValue InVec = N->getOperand(0);
18100 SDValue EltNo = N->getOperand(1);
18102 if (!isa<ConstantSDNode>(EltNo))
18105 EVT VT = InVec.getValueType();
18107 bool HasShuffleIntoBitcast = false;
18108 if (InVec.getOpcode() == ISD::BITCAST) {
18109 // Don't duplicate a load with other uses.
18110 if (!InVec.hasOneUse())
18112 EVT BCVT = InVec.getOperand(0).getValueType();
18113 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18115 InVec = InVec.getOperand(0);
18116 HasShuffleIntoBitcast = true;
18119 if (!isTargetShuffle(InVec.getOpcode()))
18122 // Don't duplicate a load with other uses.
18123 if (!InVec.hasOneUse())
18126 SmallVector<int, 16> ShuffleMask;
18128 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18132 // Select the input vector, guarding against out of range extract vector.
18133 unsigned NumElems = VT.getVectorNumElements();
18134 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18135 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18136 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18137 : InVec.getOperand(1);
18139 // If inputs to shuffle are the same for both ops, then allow 2 uses
18140 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18142 if (LdNode.getOpcode() == ISD::BITCAST) {
18143 // Don't duplicate a load with other uses.
18144 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18147 AllowedUses = 1; // only allow 1 load use if we have a bitcast
18148 LdNode = LdNode.getOperand(0);
18151 if (!ISD::isNormalLoad(LdNode.getNode()))
18154 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18156 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18159 if (HasShuffleIntoBitcast) {
18160 // If there's a bitcast before the shuffle, check if the load type and
18161 // alignment is valid.
18162 unsigned Align = LN0->getAlignment();
18163 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18164 unsigned NewAlign = TLI.getDataLayout()->
18165 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18167 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18171 // All checks match so transform back to vector_shuffle so that DAG combiner
18172 // can finish the job
18175 // Create shuffle node taking into account the case that its a unary shuffle
18176 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18177 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18178 InVec.getOperand(0), Shuffle,
18180 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18181 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18185 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18186 /// generation and convert it from being a bunch of shuffles and extracts
18187 /// to a simple store and scalar loads to extract the elements.
18188 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18189 TargetLowering::DAGCombinerInfo &DCI) {
18190 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18191 if (NewOp.getNode())
18194 SDValue InputVector = N->getOperand(0);
18196 // Detect whether we are trying to convert from mmx to i32 and the bitcast
18197 // from mmx to v2i32 has a single usage.
18198 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18199 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18200 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18201 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18202 N->getValueType(0),
18203 InputVector.getNode()->getOperand(0));
18205 // Only operate on vectors of 4 elements, where the alternative shuffling
18206 // gets to be more expensive.
18207 if (InputVector.getValueType() != MVT::v4i32)
18210 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18211 // single use which is a sign-extend or zero-extend, and all elements are
18213 SmallVector<SDNode *, 4> Uses;
18214 unsigned ExtractedElements = 0;
18215 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18216 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18217 if (UI.getUse().getResNo() != InputVector.getResNo())
18220 SDNode *Extract = *UI;
18221 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18224 if (Extract->getValueType(0) != MVT::i32)
18226 if (!Extract->hasOneUse())
18228 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18229 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18231 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18234 // Record which element was extracted.
18235 ExtractedElements |=
18236 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18238 Uses.push_back(Extract);
18241 // If not all the elements were used, this may not be worthwhile.
18242 if (ExtractedElements != 15)
18245 // Ok, we've now decided to do the transformation.
18246 SDLoc dl(InputVector);
18248 // Store the value to a temporary stack slot.
18249 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18250 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18251 MachinePointerInfo(), false, false, 0);
18253 // Replace each use (extract) with a load of the appropriate element.
18254 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18255 UE = Uses.end(); UI != UE; ++UI) {
18256 SDNode *Extract = *UI;
18258 // cOMpute the element's address.
18259 SDValue Idx = Extract->getOperand(1);
18261 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18262 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18263 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18264 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18266 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18267 StackPtr, OffsetVal);
18269 // Load the scalar.
18270 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18271 ScalarAddr, MachinePointerInfo(),
18272 false, false, false, 0);
18274 // Replace the exact with the load.
18275 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18278 // The replacement was made in place; don't return anything.
18282 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18283 static std::pair<unsigned, bool>
18284 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18285 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18286 if (!VT.isVector())
18287 return std::make_pair(0, false);
18289 bool NeedSplit = false;
18290 switch (VT.getSimpleVT().SimpleTy) {
18291 default: return std::make_pair(0, false);
18295 if (!Subtarget->hasAVX2())
18297 if (!Subtarget->hasAVX())
18298 return std::make_pair(0, false);
18303 if (!Subtarget->hasSSE2())
18304 return std::make_pair(0, false);
18307 // SSE2 has only a small subset of the operations.
18308 bool hasUnsigned = Subtarget->hasSSE41() ||
18309 (Subtarget->hasSSE2() && VT == MVT::v16i8);
18310 bool hasSigned = Subtarget->hasSSE41() ||
18311 (Subtarget->hasSSE2() && VT == MVT::v8i16);
18313 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18316 // Check for x CC y ? x : y.
18317 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18318 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18323 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18326 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18329 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18332 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18334 // Check for x CC y ? y : x -- a min/max with reversed arms.
18335 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18336 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18341 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18344 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18347 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18350 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18354 return std::make_pair(Opc, NeedSplit);
18358 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18359 const X86Subtarget *Subtarget) {
18361 SDValue Cond = N->getOperand(0);
18362 SDValue LHS = N->getOperand(1);
18363 SDValue RHS = N->getOperand(2);
18365 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18366 SDValue CondSrc = Cond->getOperand(0);
18367 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18368 Cond = CondSrc->getOperand(0);
18371 MVT VT = N->getSimpleValueType(0);
18372 MVT EltVT = VT.getVectorElementType();
18373 unsigned NumElems = VT.getVectorNumElements();
18374 // There is no blend with immediate in AVX-512.
18375 if (VT.is512BitVector())
18378 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18380 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18383 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18386 unsigned MaskValue = 0;
18387 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18390 SmallVector<int, 8> ShuffleMask(NumElems, -1);
18391 for (unsigned i = 0; i < NumElems; ++i) {
18392 // Be sure we emit undef where we can.
18393 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18394 ShuffleMask[i] = -1;
18396 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18399 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18402 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18404 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18405 TargetLowering::DAGCombinerInfo &DCI,
18406 const X86Subtarget *Subtarget) {
18408 SDValue Cond = N->getOperand(0);
18409 // Get the LHS/RHS of the select.
18410 SDValue LHS = N->getOperand(1);
18411 SDValue RHS = N->getOperand(2);
18412 EVT VT = LHS.getValueType();
18413 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18415 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18416 // instructions match the semantics of the common C idiom x<y?x:y but not
18417 // x<=y?x:y, because of how they handle negative zero (which can be
18418 // ignored in unsafe-math mode).
18419 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18420 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18421 (Subtarget->hasSSE2() ||
18422 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18423 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18425 unsigned Opcode = 0;
18426 // Check for x CC y ? x : y.
18427 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18428 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18432 // Converting this to a min would handle NaNs incorrectly, and swapping
18433 // the operands would cause it to handle comparisons between positive
18434 // and negative zero incorrectly.
18435 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18436 if (!DAG.getTarget().Options.UnsafeFPMath &&
18437 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18439 std::swap(LHS, RHS);
18441 Opcode = X86ISD::FMIN;
18444 // Converting this to a min would handle comparisons between positive
18445 // and negative zero incorrectly.
18446 if (!DAG.getTarget().Options.UnsafeFPMath &&
18447 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18449 Opcode = X86ISD::FMIN;
18452 // Converting this to a min would handle both negative zeros and NaNs
18453 // incorrectly, but we can swap the operands to fix both.
18454 std::swap(LHS, RHS);
18458 Opcode = X86ISD::FMIN;
18462 // Converting this to a max would handle comparisons between positive
18463 // and negative zero incorrectly.
18464 if (!DAG.getTarget().Options.UnsafeFPMath &&
18465 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18467 Opcode = X86ISD::FMAX;
18470 // Converting this to a max would handle NaNs incorrectly, and swapping
18471 // the operands would cause it to handle comparisons between positive
18472 // and negative zero incorrectly.
18473 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18474 if (!DAG.getTarget().Options.UnsafeFPMath &&
18475 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18477 std::swap(LHS, RHS);
18479 Opcode = X86ISD::FMAX;
18482 // Converting this to a max would handle both negative zeros and NaNs
18483 // incorrectly, but we can swap the operands to fix both.
18484 std::swap(LHS, RHS);
18488 Opcode = X86ISD::FMAX;
18491 // Check for x CC y ? y : x -- a min/max with reversed arms.
18492 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18493 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18497 // Converting this to a min would handle comparisons between positive
18498 // and negative zero incorrectly, and swapping the operands would
18499 // cause it to handle NaNs incorrectly.
18500 if (!DAG.getTarget().Options.UnsafeFPMath &&
18501 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18502 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18504 std::swap(LHS, RHS);
18506 Opcode = X86ISD::FMIN;
18509 // Converting this to a min would handle NaNs incorrectly.
18510 if (!DAG.getTarget().Options.UnsafeFPMath &&
18511 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18513 Opcode = X86ISD::FMIN;
18516 // Converting this to a min would handle both negative zeros and NaNs
18517 // incorrectly, but we can swap the operands to fix both.
18518 std::swap(LHS, RHS);
18522 Opcode = X86ISD::FMIN;
18526 // Converting this to a max would handle NaNs incorrectly.
18527 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18529 Opcode = X86ISD::FMAX;
18532 // Converting this to a max would handle comparisons between positive
18533 // and negative zero incorrectly, and swapping the operands would
18534 // cause it to handle NaNs incorrectly.
18535 if (!DAG.getTarget().Options.UnsafeFPMath &&
18536 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18537 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18539 std::swap(LHS, RHS);
18541 Opcode = X86ISD::FMAX;
18544 // Converting this to a max would handle both negative zeros and NaNs
18545 // incorrectly, but we can swap the operands to fix both.
18546 std::swap(LHS, RHS);
18550 Opcode = X86ISD::FMAX;
18556 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18559 EVT CondVT = Cond.getValueType();
18560 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18561 CondVT.getVectorElementType() == MVT::i1) {
18562 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18563 // lowering on AVX-512. In this case we convert it to
18564 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18565 // The same situation for all 128 and 256-bit vectors of i8 and i16
18566 EVT OpVT = LHS.getValueType();
18567 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18568 (OpVT.getVectorElementType() == MVT::i8 ||
18569 OpVT.getVectorElementType() == MVT::i16)) {
18570 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18571 DCI.AddToWorklist(Cond.getNode());
18572 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18575 // If this is a select between two integer constants, try to do some
18577 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18578 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18579 // Don't do this for crazy integer types.
18580 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18581 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18582 // so that TrueC (the true value) is larger than FalseC.
18583 bool NeedsCondInvert = false;
18585 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18586 // Efficiently invertible.
18587 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18588 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18589 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18590 NeedsCondInvert = true;
18591 std::swap(TrueC, FalseC);
18594 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18595 if (FalseC->getAPIntValue() == 0 &&
18596 TrueC->getAPIntValue().isPowerOf2()) {
18597 if (NeedsCondInvert) // Invert the condition if needed.
18598 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18599 DAG.getConstant(1, Cond.getValueType()));
18601 // Zero extend the condition if needed.
18602 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18604 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18605 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18606 DAG.getConstant(ShAmt, MVT::i8));
18609 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18610 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18611 if (NeedsCondInvert) // Invert the condition if needed.
18612 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18613 DAG.getConstant(1, Cond.getValueType()));
18615 // Zero extend the condition if needed.
18616 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18617 FalseC->getValueType(0), Cond);
18618 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18619 SDValue(FalseC, 0));
18622 // Optimize cases that will turn into an LEA instruction. This requires
18623 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18624 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18625 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18626 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18628 bool isFastMultiplier = false;
18630 switch ((unsigned char)Diff) {
18632 case 1: // result = add base, cond
18633 case 2: // result = lea base( , cond*2)
18634 case 3: // result = lea base(cond, cond*2)
18635 case 4: // result = lea base( , cond*4)
18636 case 5: // result = lea base(cond, cond*4)
18637 case 8: // result = lea base( , cond*8)
18638 case 9: // result = lea base(cond, cond*8)
18639 isFastMultiplier = true;
18644 if (isFastMultiplier) {
18645 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18646 if (NeedsCondInvert) // Invert the condition if needed.
18647 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18648 DAG.getConstant(1, Cond.getValueType()));
18650 // Zero extend the condition if needed.
18651 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18653 // Scale the condition by the difference.
18655 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18656 DAG.getConstant(Diff, Cond.getValueType()));
18658 // Add the base if non-zero.
18659 if (FalseC->getAPIntValue() != 0)
18660 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18661 SDValue(FalseC, 0));
18668 // Canonicalize max and min:
18669 // (x > y) ? x : y -> (x >= y) ? x : y
18670 // (x < y) ? x : y -> (x <= y) ? x : y
18671 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18672 // the need for an extra compare
18673 // against zero. e.g.
18674 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18676 // testl %edi, %edi
18678 // cmovgl %edi, %eax
18682 // cmovsl %eax, %edi
18683 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18684 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18685 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18686 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18691 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18692 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18693 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18694 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18699 // Early exit check
18700 if (!TLI.isTypeLegal(VT))
18703 // Match VSELECTs into subs with unsigned saturation.
18704 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18705 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18706 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18707 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18708 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18710 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18711 // left side invert the predicate to simplify logic below.
18713 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18715 CC = ISD::getSetCCInverse(CC, true);
18716 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18720 if (Other.getNode() && Other->getNumOperands() == 2 &&
18721 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18722 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18723 SDValue CondRHS = Cond->getOperand(1);
18725 // Look for a general sub with unsigned saturation first.
18726 // x >= y ? x-y : 0 --> subus x, y
18727 // x > y ? x-y : 0 --> subus x, y
18728 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18729 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18730 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18732 // If the RHS is a constant we have to reverse the const canonicalization.
18733 // x > C-1 ? x+-C : 0 --> subus x, C
18734 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18735 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18736 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18737 if (CondRHS.getConstantOperandVal(0) == -A-1)
18738 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18739 DAG.getConstant(-A, VT));
18742 // Another special case: If C was a sign bit, the sub has been
18743 // canonicalized into a xor.
18744 // FIXME: Would it be better to use computeKnownBits to determine whether
18745 // it's safe to decanonicalize the xor?
18746 // x s< 0 ? x^C : 0 --> subus x, C
18747 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18748 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18749 isSplatVector(OpRHS.getNode())) {
18750 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18752 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18757 // Try to match a min/max vector operation.
18758 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18759 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18760 unsigned Opc = ret.first;
18761 bool NeedSplit = ret.second;
18763 if (Opc && NeedSplit) {
18764 unsigned NumElems = VT.getVectorNumElements();
18765 // Extract the LHS vectors
18766 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18767 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18769 // Extract the RHS vectors
18770 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18771 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18773 // Create min/max for each subvector
18774 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18775 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18777 // Merge the result
18778 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18780 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18783 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18784 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18785 // Check if SETCC has already been promoted
18786 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18787 // Check that condition value type matches vselect operand type
18790 assert(Cond.getValueType().isVector() &&
18791 "vector select expects a vector selector!");
18793 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18794 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18796 if (!TValIsAllOnes && !FValIsAllZeros) {
18797 // Try invert the condition if true value is not all 1s and false value
18799 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18800 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18802 if (TValIsAllZeros || FValIsAllOnes) {
18803 SDValue CC = Cond.getOperand(2);
18804 ISD::CondCode NewCC =
18805 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18806 Cond.getOperand(0).getValueType().isInteger());
18807 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18808 std::swap(LHS, RHS);
18809 TValIsAllOnes = FValIsAllOnes;
18810 FValIsAllZeros = TValIsAllZeros;
18814 if (TValIsAllOnes || FValIsAllZeros) {
18817 if (TValIsAllOnes && FValIsAllZeros)
18819 else if (TValIsAllOnes)
18820 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18821 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18822 else if (FValIsAllZeros)
18823 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18824 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18826 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18830 // Try to fold this VSELECT into a MOVSS/MOVSD
18831 if (N->getOpcode() == ISD::VSELECT &&
18832 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18833 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18834 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18835 bool CanFold = false;
18836 unsigned NumElems = Cond.getNumOperands();
18840 if (isZero(Cond.getOperand(0))) {
18843 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18844 // fold (vselect <0,-1> -> (movsd A, B)
18845 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18846 CanFold = isAllOnes(Cond.getOperand(i));
18847 } else if (isAllOnes(Cond.getOperand(0))) {
18851 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18852 // fold (vselect <-1,0> -> (movsd B, A)
18853 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18854 CanFold = isZero(Cond.getOperand(i));
18858 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18859 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18860 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18863 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18864 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18865 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18866 // (v2i64 (bitcast B)))))
18868 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18869 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18870 // (v2f64 (bitcast B)))))
18872 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18873 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18874 // (v2i64 (bitcast A)))))
18876 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18877 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18878 // (v2f64 (bitcast A)))))
18880 CanFold = (isZero(Cond.getOperand(0)) &&
18881 isZero(Cond.getOperand(1)) &&
18882 isAllOnes(Cond.getOperand(2)) &&
18883 isAllOnes(Cond.getOperand(3)));
18885 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18886 isAllOnes(Cond.getOperand(1)) &&
18887 isZero(Cond.getOperand(2)) &&
18888 isZero(Cond.getOperand(3))) {
18890 std::swap(LHS, RHS);
18894 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18895 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18896 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18897 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18899 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18905 // If we know that this node is legal then we know that it is going to be
18906 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18907 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18908 // to simplify previous instructions.
18909 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18910 !DCI.isBeforeLegalize() &&
18911 // We explicitly check against v8i16 and v16i16 because, although
18912 // they're marked as Custom, they might only be legal when Cond is a
18913 // build_vector of constants. This will be taken care in a later
18915 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18916 VT != MVT::v8i16)) {
18917 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18919 // Don't optimize vector selects that map to mask-registers.
18923 // Check all uses of that condition operand to check whether it will be
18924 // consumed by non-BLEND instructions, which may depend on all bits are set
18926 for (SDNode::use_iterator I = Cond->use_begin(),
18927 E = Cond->use_end(); I != E; ++I)
18928 if (I->getOpcode() != ISD::VSELECT)
18929 // TODO: Add other opcodes eventually lowered into BLEND.
18932 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18933 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18935 APInt KnownZero, KnownOne;
18936 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18937 DCI.isBeforeLegalizeOps());
18938 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18939 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18940 DCI.CommitTargetLoweringOpt(TLO);
18943 // We should generate an X86ISD::BLENDI from a vselect if its argument
18944 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18945 // constants. This specific pattern gets generated when we split a
18946 // selector for a 512 bit vector in a machine without AVX512 (but with
18947 // 256-bit vectors), during legalization:
18949 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18951 // Iff we find this pattern and the build_vectors are built from
18952 // constants, we translate the vselect into a shuffle_vector that we
18953 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18954 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18955 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18956 if (Shuffle.getNode())
18963 // Check whether a boolean test is testing a boolean value generated by
18964 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18967 // Simplify the following patterns:
18968 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18969 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18970 // to (Op EFLAGS Cond)
18972 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18973 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18974 // to (Op EFLAGS !Cond)
18976 // where Op could be BRCOND or CMOV.
18978 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18979 // Quit if not CMP and SUB with its value result used.
18980 if (Cmp.getOpcode() != X86ISD::CMP &&
18981 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18984 // Quit if not used as a boolean value.
18985 if (CC != X86::COND_E && CC != X86::COND_NE)
18988 // Check CMP operands. One of them should be 0 or 1 and the other should be
18989 // an SetCC or extended from it.
18990 SDValue Op1 = Cmp.getOperand(0);
18991 SDValue Op2 = Cmp.getOperand(1);
18994 const ConstantSDNode* C = nullptr;
18995 bool needOppositeCond = (CC == X86::COND_E);
18996 bool checkAgainstTrue = false; // Is it a comparison against 1?
18998 if ((C = dyn_cast<ConstantSDNode>(Op1)))
19000 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19002 else // Quit if all operands are not constants.
19005 if (C->getZExtValue() == 1) {
19006 needOppositeCond = !needOppositeCond;
19007 checkAgainstTrue = true;
19008 } else if (C->getZExtValue() != 0)
19009 // Quit if the constant is neither 0 or 1.
19012 bool truncatedToBoolWithAnd = false;
19013 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19014 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19015 SetCC.getOpcode() == ISD::TRUNCATE ||
19016 SetCC.getOpcode() == ISD::AND) {
19017 if (SetCC.getOpcode() == ISD::AND) {
19019 ConstantSDNode *CS;
19020 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19021 CS->getZExtValue() == 1)
19023 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19024 CS->getZExtValue() == 1)
19028 SetCC = SetCC.getOperand(OpIdx);
19029 truncatedToBoolWithAnd = true;
19031 SetCC = SetCC.getOperand(0);
19034 switch (SetCC.getOpcode()) {
19035 case X86ISD::SETCC_CARRY:
19036 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19037 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19038 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19039 // truncated to i1 using 'and'.
19040 if (checkAgainstTrue && !truncatedToBoolWithAnd)
19042 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19043 "Invalid use of SETCC_CARRY!");
19045 case X86ISD::SETCC:
19046 // Set the condition code or opposite one if necessary.
19047 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19048 if (needOppositeCond)
19049 CC = X86::GetOppositeBranchCondition(CC);
19050 return SetCC.getOperand(1);
19051 case X86ISD::CMOV: {
19052 // Check whether false/true value has canonical one, i.e. 0 or 1.
19053 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19054 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19055 // Quit if true value is not a constant.
19058 // Quit if false value is not a constant.
19060 SDValue Op = SetCC.getOperand(0);
19061 // Skip 'zext' or 'trunc' node.
19062 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19063 Op.getOpcode() == ISD::TRUNCATE)
19064 Op = Op.getOperand(0);
19065 // A special case for rdrand/rdseed, where 0 is set if false cond is
19067 if ((Op.getOpcode() != X86ISD::RDRAND &&
19068 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19071 // Quit if false value is not the constant 0 or 1.
19072 bool FValIsFalse = true;
19073 if (FVal && FVal->getZExtValue() != 0) {
19074 if (FVal->getZExtValue() != 1)
19076 // If FVal is 1, opposite cond is needed.
19077 needOppositeCond = !needOppositeCond;
19078 FValIsFalse = false;
19080 // Quit if TVal is not the constant opposite of FVal.
19081 if (FValIsFalse && TVal->getZExtValue() != 1)
19083 if (!FValIsFalse && TVal->getZExtValue() != 0)
19085 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19086 if (needOppositeCond)
19087 CC = X86::GetOppositeBranchCondition(CC);
19088 return SetCC.getOperand(3);
19095 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19096 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19097 TargetLowering::DAGCombinerInfo &DCI,
19098 const X86Subtarget *Subtarget) {
19101 // If the flag operand isn't dead, don't touch this CMOV.
19102 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19105 SDValue FalseOp = N->getOperand(0);
19106 SDValue TrueOp = N->getOperand(1);
19107 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19108 SDValue Cond = N->getOperand(3);
19110 if (CC == X86::COND_E || CC == X86::COND_NE) {
19111 switch (Cond.getOpcode()) {
19115 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19116 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19117 return (CC == X86::COND_E) ? FalseOp : TrueOp;
19123 Flags = checkBoolTestSetCCCombine(Cond, CC);
19124 if (Flags.getNode() &&
19125 // Extra check as FCMOV only supports a subset of X86 cond.
19126 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19127 SDValue Ops[] = { FalseOp, TrueOp,
19128 DAG.getConstant(CC, MVT::i8), Flags };
19129 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19132 // If this is a select between two integer constants, try to do some
19133 // optimizations. Note that the operands are ordered the opposite of SELECT
19135 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19136 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19137 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19138 // larger than FalseC (the false value).
19139 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19140 CC = X86::GetOppositeBranchCondition(CC);
19141 std::swap(TrueC, FalseC);
19142 std::swap(TrueOp, FalseOp);
19145 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
19146 // This is efficient for any integer data type (including i8/i16) and
19148 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19149 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19150 DAG.getConstant(CC, MVT::i8), Cond);
19152 // Zero extend the condition if needed.
19153 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19155 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19156 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19157 DAG.getConstant(ShAmt, MVT::i8));
19158 if (N->getNumValues() == 2) // Dead flag value?
19159 return DCI.CombineTo(N, Cond, SDValue());
19163 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
19164 // for any integer data type, including i8/i16.
19165 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19166 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19167 DAG.getConstant(CC, MVT::i8), Cond);
19169 // Zero extend the condition if needed.
19170 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19171 FalseC->getValueType(0), Cond);
19172 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19173 SDValue(FalseC, 0));
19175 if (N->getNumValues() == 2) // Dead flag value?
19176 return DCI.CombineTo(N, Cond, SDValue());
19180 // Optimize cases that will turn into an LEA instruction. This requires
19181 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19182 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19183 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19184 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19186 bool isFastMultiplier = false;
19188 switch ((unsigned char)Diff) {
19190 case 1: // result = add base, cond
19191 case 2: // result = lea base( , cond*2)
19192 case 3: // result = lea base(cond, cond*2)
19193 case 4: // result = lea base( , cond*4)
19194 case 5: // result = lea base(cond, cond*4)
19195 case 8: // result = lea base( , cond*8)
19196 case 9: // result = lea base(cond, cond*8)
19197 isFastMultiplier = true;
19202 if (isFastMultiplier) {
19203 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19204 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19205 DAG.getConstant(CC, MVT::i8), Cond);
19206 // Zero extend the condition if needed.
19207 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19209 // Scale the condition by the difference.
19211 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19212 DAG.getConstant(Diff, Cond.getValueType()));
19214 // Add the base if non-zero.
19215 if (FalseC->getAPIntValue() != 0)
19216 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19217 SDValue(FalseC, 0));
19218 if (N->getNumValues() == 2) // Dead flag value?
19219 return DCI.CombineTo(N, Cond, SDValue());
19226 // Handle these cases:
19227 // (select (x != c), e, c) -> select (x != c), e, x),
19228 // (select (x == c), c, e) -> select (x == c), x, e)
19229 // where the c is an integer constant, and the "select" is the combination
19230 // of CMOV and CMP.
19232 // The rationale for this change is that the conditional-move from a constant
19233 // needs two instructions, however, conditional-move from a register needs
19234 // only one instruction.
19236 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19237 // some instruction-combining opportunities. This opt needs to be
19238 // postponed as late as possible.
19240 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19241 // the DCI.xxxx conditions are provided to postpone the optimization as
19242 // late as possible.
19244 ConstantSDNode *CmpAgainst = nullptr;
19245 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19246 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19247 !isa<ConstantSDNode>(Cond.getOperand(0))) {
19249 if (CC == X86::COND_NE &&
19250 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19251 CC = X86::GetOppositeBranchCondition(CC);
19252 std::swap(TrueOp, FalseOp);
19255 if (CC == X86::COND_E &&
19256 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19257 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19258 DAG.getConstant(CC, MVT::i8), Cond };
19259 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19267 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19268 const X86Subtarget *Subtarget) {
19269 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19271 default: return SDValue();
19272 // SSE/AVX/AVX2 blend intrinsics.
19273 case Intrinsic::x86_avx2_pblendvb:
19274 case Intrinsic::x86_avx2_pblendw:
19275 case Intrinsic::x86_avx2_pblendd_128:
19276 case Intrinsic::x86_avx2_pblendd_256:
19277 // Don't try to simplify this intrinsic if we don't have AVX2.
19278 if (!Subtarget->hasAVX2())
19281 case Intrinsic::x86_avx_blend_pd_256:
19282 case Intrinsic::x86_avx_blend_ps_256:
19283 case Intrinsic::x86_avx_blendv_pd_256:
19284 case Intrinsic::x86_avx_blendv_ps_256:
19285 // Don't try to simplify this intrinsic if we don't have AVX.
19286 if (!Subtarget->hasAVX())
19289 case Intrinsic::x86_sse41_pblendw:
19290 case Intrinsic::x86_sse41_blendpd:
19291 case Intrinsic::x86_sse41_blendps:
19292 case Intrinsic::x86_sse41_blendvps:
19293 case Intrinsic::x86_sse41_blendvpd:
19294 case Intrinsic::x86_sse41_pblendvb: {
19295 SDValue Op0 = N->getOperand(1);
19296 SDValue Op1 = N->getOperand(2);
19297 SDValue Mask = N->getOperand(3);
19299 // Don't try to simplify this intrinsic if we don't have SSE4.1.
19300 if (!Subtarget->hasSSE41())
19303 // fold (blend A, A, Mask) -> A
19306 // fold (blend A, B, allZeros) -> A
19307 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19309 // fold (blend A, B, allOnes) -> B
19310 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19313 // Simplify the case where the mask is a constant i32 value.
19314 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19315 if (C->isNullValue())
19317 if (C->isAllOnesValue())
19324 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19325 case Intrinsic::x86_sse2_psrai_w:
19326 case Intrinsic::x86_sse2_psrai_d:
19327 case Intrinsic::x86_avx2_psrai_w:
19328 case Intrinsic::x86_avx2_psrai_d:
19329 case Intrinsic::x86_sse2_psra_w:
19330 case Intrinsic::x86_sse2_psra_d:
19331 case Intrinsic::x86_avx2_psra_w:
19332 case Intrinsic::x86_avx2_psra_d: {
19333 SDValue Op0 = N->getOperand(1);
19334 SDValue Op1 = N->getOperand(2);
19335 EVT VT = Op0.getValueType();
19336 assert(VT.isVector() && "Expected a vector type!");
19338 if (isa<BuildVectorSDNode>(Op1))
19339 Op1 = Op1.getOperand(0);
19341 if (!isa<ConstantSDNode>(Op1))
19344 EVT SVT = VT.getVectorElementType();
19345 unsigned SVTBits = SVT.getSizeInBits();
19347 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19348 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19349 uint64_t ShAmt = C.getZExtValue();
19351 // Don't try to convert this shift into a ISD::SRA if the shift
19352 // count is bigger than or equal to the element size.
19353 if (ShAmt >= SVTBits)
19356 // Trivial case: if the shift count is zero, then fold this
19357 // into the first operand.
19361 // Replace this packed shift intrinsic with a target independent
19363 SDValue Splat = DAG.getConstant(C, VT);
19364 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19369 /// PerformMulCombine - Optimize a single multiply with constant into two
19370 /// in order to implement it with two cheaper instructions, e.g.
19371 /// LEA + SHL, LEA + LEA.
19372 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19373 TargetLowering::DAGCombinerInfo &DCI) {
19374 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19377 EVT VT = N->getValueType(0);
19378 if (VT != MVT::i64)
19381 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19384 uint64_t MulAmt = C->getZExtValue();
19385 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19388 uint64_t MulAmt1 = 0;
19389 uint64_t MulAmt2 = 0;
19390 if ((MulAmt % 9) == 0) {
19392 MulAmt2 = MulAmt / 9;
19393 } else if ((MulAmt % 5) == 0) {
19395 MulAmt2 = MulAmt / 5;
19396 } else if ((MulAmt % 3) == 0) {
19398 MulAmt2 = MulAmt / 3;
19401 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19404 if (isPowerOf2_64(MulAmt2) &&
19405 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19406 // If second multiplifer is pow2, issue it first. We want the multiply by
19407 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19409 std::swap(MulAmt1, MulAmt2);
19412 if (isPowerOf2_64(MulAmt1))
19413 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19414 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19416 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19417 DAG.getConstant(MulAmt1, VT));
19419 if (isPowerOf2_64(MulAmt2))
19420 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19421 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19423 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19424 DAG.getConstant(MulAmt2, VT));
19426 // Do not add new nodes to DAG combiner worklist.
19427 DCI.CombineTo(N, NewMul, false);
19432 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19433 SDValue N0 = N->getOperand(0);
19434 SDValue N1 = N->getOperand(1);
19435 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19436 EVT VT = N0.getValueType();
19438 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19439 // since the result of setcc_c is all zero's or all ones.
19440 if (VT.isInteger() && !VT.isVector() &&
19441 N1C && N0.getOpcode() == ISD::AND &&
19442 N0.getOperand(1).getOpcode() == ISD::Constant) {
19443 SDValue N00 = N0.getOperand(0);
19444 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19445 ((N00.getOpcode() == ISD::ANY_EXTEND ||
19446 N00.getOpcode() == ISD::ZERO_EXTEND) &&
19447 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19448 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19449 APInt ShAmt = N1C->getAPIntValue();
19450 Mask = Mask.shl(ShAmt);
19452 return DAG.getNode(ISD::AND, SDLoc(N), VT,
19453 N00, DAG.getConstant(Mask, VT));
19457 // Hardware support for vector shifts is sparse which makes us scalarize the
19458 // vector operations in many cases. Also, on sandybridge ADD is faster than
19460 // (shl V, 1) -> add V,V
19461 if (isSplatVector(N1.getNode())) {
19462 assert(N0.getValueType().isVector() && "Invalid vector shift type");
19463 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19464 // We shift all of the values by one. In many cases we do not have
19465 // hardware support for this operation. This is better expressed as an ADD
19467 if (N1C && (1 == N1C->getZExtValue())) {
19468 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19475 /// \brief Returns a vector of 0s if the node in input is a vector logical
19476 /// shift by a constant amount which is known to be bigger than or equal
19477 /// to the vector element size in bits.
19478 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19479 const X86Subtarget *Subtarget) {
19480 EVT VT = N->getValueType(0);
19482 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19483 (!Subtarget->hasInt256() ||
19484 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19487 SDValue Amt = N->getOperand(1);
19489 if (isSplatVector(Amt.getNode())) {
19490 SDValue SclrAmt = Amt->getOperand(0);
19491 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19492 APInt ShiftAmt = C->getAPIntValue();
19493 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19495 // SSE2/AVX2 logical shifts always return a vector of 0s
19496 // if the shift amount is bigger than or equal to
19497 // the element size. The constant shift amount will be
19498 // encoded as a 8-bit immediate.
19499 if (ShiftAmt.trunc(8).uge(MaxAmount))
19500 return getZeroVector(VT, Subtarget, DAG, DL);
19507 /// PerformShiftCombine - Combine shifts.
19508 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19509 TargetLowering::DAGCombinerInfo &DCI,
19510 const X86Subtarget *Subtarget) {
19511 if (N->getOpcode() == ISD::SHL) {
19512 SDValue V = PerformSHLCombine(N, DAG);
19513 if (V.getNode()) return V;
19516 if (N->getOpcode() != ISD::SRA) {
19517 // Try to fold this logical shift into a zero vector.
19518 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19519 if (V.getNode()) return V;
19525 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19526 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19527 // and friends. Likewise for OR -> CMPNEQSS.
19528 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19529 TargetLowering::DAGCombinerInfo &DCI,
19530 const X86Subtarget *Subtarget) {
19533 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19534 // we're requiring SSE2 for both.
19535 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19536 SDValue N0 = N->getOperand(0);
19537 SDValue N1 = N->getOperand(1);
19538 SDValue CMP0 = N0->getOperand(1);
19539 SDValue CMP1 = N1->getOperand(1);
19542 // The SETCCs should both refer to the same CMP.
19543 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19546 SDValue CMP00 = CMP0->getOperand(0);
19547 SDValue CMP01 = CMP0->getOperand(1);
19548 EVT VT = CMP00.getValueType();
19550 if (VT == MVT::f32 || VT == MVT::f64) {
19551 bool ExpectingFlags = false;
19552 // Check for any users that want flags:
19553 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19554 !ExpectingFlags && UI != UE; ++UI)
19555 switch (UI->getOpcode()) {
19560 ExpectingFlags = true;
19562 case ISD::CopyToReg:
19563 case ISD::SIGN_EXTEND:
19564 case ISD::ZERO_EXTEND:
19565 case ISD::ANY_EXTEND:
19569 if (!ExpectingFlags) {
19570 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19571 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19573 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19574 X86::CondCode tmp = cc0;
19579 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19580 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19581 // FIXME: need symbolic constants for these magic numbers.
19582 // See X86ATTInstPrinter.cpp:printSSECC().
19583 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19584 if (Subtarget->hasAVX512()) {
19585 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19586 CMP01, DAG.getConstant(x86cc, MVT::i8));
19587 if (N->getValueType(0) != MVT::i1)
19588 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19592 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19593 CMP00.getValueType(), CMP00, CMP01,
19594 DAG.getConstant(x86cc, MVT::i8));
19596 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19597 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19599 if (is64BitFP && !Subtarget->is64Bit()) {
19600 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19601 // 64-bit integer, since that's not a legal type. Since
19602 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19603 // bits, but can do this little dance to extract the lowest 32 bits
19604 // and work with those going forward.
19605 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19607 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19609 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19610 Vector32, DAG.getIntPtrConstant(0));
19614 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19615 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19616 DAG.getConstant(1, IntVT));
19617 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19618 return OneBitOfTruth;
19626 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19627 /// so it can be folded inside ANDNP.
19628 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19629 EVT VT = N->getValueType(0);
19631 // Match direct AllOnes for 128 and 256-bit vectors
19632 if (ISD::isBuildVectorAllOnes(N))
19635 // Look through a bit convert.
19636 if (N->getOpcode() == ISD::BITCAST)
19637 N = N->getOperand(0).getNode();
19639 // Sometimes the operand may come from a insert_subvector building a 256-bit
19641 if (VT.is256BitVector() &&
19642 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19643 SDValue V1 = N->getOperand(0);
19644 SDValue V2 = N->getOperand(1);
19646 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19647 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19648 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19649 ISD::isBuildVectorAllOnes(V2.getNode()))
19656 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19657 // register. In most cases we actually compare or select YMM-sized registers
19658 // and mixing the two types creates horrible code. This method optimizes
19659 // some of the transition sequences.
19660 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19661 TargetLowering::DAGCombinerInfo &DCI,
19662 const X86Subtarget *Subtarget) {
19663 EVT VT = N->getValueType(0);
19664 if (!VT.is256BitVector())
19667 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19668 N->getOpcode() == ISD::ZERO_EXTEND ||
19669 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19671 SDValue Narrow = N->getOperand(0);
19672 EVT NarrowVT = Narrow->getValueType(0);
19673 if (!NarrowVT.is128BitVector())
19676 if (Narrow->getOpcode() != ISD::XOR &&
19677 Narrow->getOpcode() != ISD::AND &&
19678 Narrow->getOpcode() != ISD::OR)
19681 SDValue N0 = Narrow->getOperand(0);
19682 SDValue N1 = Narrow->getOperand(1);
19685 // The Left side has to be a trunc.
19686 if (N0.getOpcode() != ISD::TRUNCATE)
19689 // The type of the truncated inputs.
19690 EVT WideVT = N0->getOperand(0)->getValueType(0);
19694 // The right side has to be a 'trunc' or a constant vector.
19695 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19696 bool RHSConst = (isSplatVector(N1.getNode()) &&
19697 isa<ConstantSDNode>(N1->getOperand(0)));
19698 if (!RHSTrunc && !RHSConst)
19701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19703 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19706 // Set N0 and N1 to hold the inputs to the new wide operation.
19707 N0 = N0->getOperand(0);
19709 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19710 N1->getOperand(0));
19711 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19712 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19713 } else if (RHSTrunc) {
19714 N1 = N1->getOperand(0);
19717 // Generate the wide operation.
19718 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19719 unsigned Opcode = N->getOpcode();
19721 case ISD::ANY_EXTEND:
19723 case ISD::ZERO_EXTEND: {
19724 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19725 APInt Mask = APInt::getAllOnesValue(InBits);
19726 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19727 return DAG.getNode(ISD::AND, DL, VT,
19728 Op, DAG.getConstant(Mask, VT));
19730 case ISD::SIGN_EXTEND:
19731 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19732 Op, DAG.getValueType(NarrowVT));
19734 llvm_unreachable("Unexpected opcode");
19738 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19739 TargetLowering::DAGCombinerInfo &DCI,
19740 const X86Subtarget *Subtarget) {
19741 EVT VT = N->getValueType(0);
19742 if (DCI.isBeforeLegalizeOps())
19745 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19749 // Create BEXTR instructions
19750 // BEXTR is ((X >> imm) & (2**size-1))
19751 if (VT == MVT::i32 || VT == MVT::i64) {
19752 SDValue N0 = N->getOperand(0);
19753 SDValue N1 = N->getOperand(1);
19756 // Check for BEXTR.
19757 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19758 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19759 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19760 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19761 if (MaskNode && ShiftNode) {
19762 uint64_t Mask = MaskNode->getZExtValue();
19763 uint64_t Shift = ShiftNode->getZExtValue();
19764 if (isMask_64(Mask)) {
19765 uint64_t MaskSize = CountPopulation_64(Mask);
19766 if (Shift + MaskSize <= VT.getSizeInBits())
19767 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19768 DAG.getConstant(Shift | (MaskSize << 8), VT));
19776 // Want to form ANDNP nodes:
19777 // 1) In the hopes of then easily combining them with OR and AND nodes
19778 // to form PBLEND/PSIGN.
19779 // 2) To match ANDN packed intrinsics
19780 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19783 SDValue N0 = N->getOperand(0);
19784 SDValue N1 = N->getOperand(1);
19787 // Check LHS for vnot
19788 if (N0.getOpcode() == ISD::XOR &&
19789 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19790 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19791 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19793 // Check RHS for vnot
19794 if (N1.getOpcode() == ISD::XOR &&
19795 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19796 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19797 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19802 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19803 TargetLowering::DAGCombinerInfo &DCI,
19804 const X86Subtarget *Subtarget) {
19805 if (DCI.isBeforeLegalizeOps())
19808 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19812 SDValue N0 = N->getOperand(0);
19813 SDValue N1 = N->getOperand(1);
19814 EVT VT = N->getValueType(0);
19816 // look for psign/blend
19817 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19818 if (!Subtarget->hasSSSE3() ||
19819 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19822 // Canonicalize pandn to RHS
19823 if (N0.getOpcode() == X86ISD::ANDNP)
19825 // or (and (m, y), (pandn m, x))
19826 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19827 SDValue Mask = N1.getOperand(0);
19828 SDValue X = N1.getOperand(1);
19830 if (N0.getOperand(0) == Mask)
19831 Y = N0.getOperand(1);
19832 if (N0.getOperand(1) == Mask)
19833 Y = N0.getOperand(0);
19835 // Check to see if the mask appeared in both the AND and ANDNP and
19839 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19840 // Look through mask bitcast.
19841 if (Mask.getOpcode() == ISD::BITCAST)
19842 Mask = Mask.getOperand(0);
19843 if (X.getOpcode() == ISD::BITCAST)
19844 X = X.getOperand(0);
19845 if (Y.getOpcode() == ISD::BITCAST)
19846 Y = Y.getOperand(0);
19848 EVT MaskVT = Mask.getValueType();
19850 // Validate that the Mask operand is a vector sra node.
19851 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19852 // there is no psrai.b
19853 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19854 unsigned SraAmt = ~0;
19855 if (Mask.getOpcode() == ISD::SRA) {
19856 SDValue Amt = Mask.getOperand(1);
19857 if (isSplatVector(Amt.getNode())) {
19858 SDValue SclrAmt = Amt->getOperand(0);
19859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19860 SraAmt = C->getZExtValue();
19862 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19863 SDValue SraC = Mask.getOperand(1);
19864 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19866 if ((SraAmt + 1) != EltBits)
19871 // Now we know we at least have a plendvb with the mask val. See if
19872 // we can form a psignb/w/d.
19873 // psign = x.type == y.type == mask.type && y = sub(0, x);
19874 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19875 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19876 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19877 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19878 "Unsupported VT for PSIGN");
19879 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19880 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19882 // PBLENDVB only available on SSE 4.1
19883 if (!Subtarget->hasSSE41())
19886 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19888 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19889 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19890 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19891 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19892 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19896 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19899 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19900 MachineFunction &MF = DAG.getMachineFunction();
19901 bool OptForSize = MF.getFunction()->getAttributes().
19902 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19904 // SHLD/SHRD instructions have lower register pressure, but on some
19905 // platforms they have higher latency than the equivalent
19906 // series of shifts/or that would otherwise be generated.
19907 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19908 // have higher latencies and we are not optimizing for size.
19909 if (!OptForSize && Subtarget->isSHLDSlow())
19912 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19914 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19916 if (!N0.hasOneUse() || !N1.hasOneUse())
19919 SDValue ShAmt0 = N0.getOperand(1);
19920 if (ShAmt0.getValueType() != MVT::i8)
19922 SDValue ShAmt1 = N1.getOperand(1);
19923 if (ShAmt1.getValueType() != MVT::i8)
19925 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19926 ShAmt0 = ShAmt0.getOperand(0);
19927 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19928 ShAmt1 = ShAmt1.getOperand(0);
19931 unsigned Opc = X86ISD::SHLD;
19932 SDValue Op0 = N0.getOperand(0);
19933 SDValue Op1 = N1.getOperand(0);
19934 if (ShAmt0.getOpcode() == ISD::SUB) {
19935 Opc = X86ISD::SHRD;
19936 std::swap(Op0, Op1);
19937 std::swap(ShAmt0, ShAmt1);
19940 unsigned Bits = VT.getSizeInBits();
19941 if (ShAmt1.getOpcode() == ISD::SUB) {
19942 SDValue Sum = ShAmt1.getOperand(0);
19943 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19944 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19945 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19946 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19947 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19948 return DAG.getNode(Opc, DL, VT,
19950 DAG.getNode(ISD::TRUNCATE, DL,
19953 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19954 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19956 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19957 return DAG.getNode(Opc, DL, VT,
19958 N0.getOperand(0), N1.getOperand(0),
19959 DAG.getNode(ISD::TRUNCATE, DL,
19966 // Generate NEG and CMOV for integer abs.
19967 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19968 EVT VT = N->getValueType(0);
19970 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19971 // 8-bit integer abs to NEG and CMOV.
19972 if (VT.isInteger() && VT.getSizeInBits() == 8)
19975 SDValue N0 = N->getOperand(0);
19976 SDValue N1 = N->getOperand(1);
19979 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19980 // and change it to SUB and CMOV.
19981 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19982 N0.getOpcode() == ISD::ADD &&
19983 N0.getOperand(1) == N1 &&
19984 N1.getOpcode() == ISD::SRA &&
19985 N1.getOperand(0) == N0.getOperand(0))
19986 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19987 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19988 // Generate SUB & CMOV.
19989 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19990 DAG.getConstant(0, VT), N0.getOperand(0));
19992 SDValue Ops[] = { N0.getOperand(0), Neg,
19993 DAG.getConstant(X86::COND_GE, MVT::i8),
19994 SDValue(Neg.getNode(), 1) };
19995 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20000 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20001 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20002 TargetLowering::DAGCombinerInfo &DCI,
20003 const X86Subtarget *Subtarget) {
20004 if (DCI.isBeforeLegalizeOps())
20007 if (Subtarget->hasCMov()) {
20008 SDValue RV = performIntegerAbsCombine(N, DAG);
20016 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20017 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20018 TargetLowering::DAGCombinerInfo &DCI,
20019 const X86Subtarget *Subtarget) {
20020 LoadSDNode *Ld = cast<LoadSDNode>(N);
20021 EVT RegVT = Ld->getValueType(0);
20022 EVT MemVT = Ld->getMemoryVT();
20024 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20025 unsigned RegSz = RegVT.getSizeInBits();
20027 // On Sandybridge unaligned 256bit loads are inefficient.
20028 ISD::LoadExtType Ext = Ld->getExtensionType();
20029 unsigned Alignment = Ld->getAlignment();
20030 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20031 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20032 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20033 unsigned NumElems = RegVT.getVectorNumElements();
20037 SDValue Ptr = Ld->getBasePtr();
20038 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20040 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20042 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20043 Ld->getPointerInfo(), Ld->isVolatile(),
20044 Ld->isNonTemporal(), Ld->isInvariant(),
20046 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20047 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20048 Ld->getPointerInfo(), Ld->isVolatile(),
20049 Ld->isNonTemporal(), Ld->isInvariant(),
20050 std::min(16U, Alignment));
20051 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20053 Load2.getValue(1));
20055 SDValue NewVec = DAG.getUNDEF(RegVT);
20056 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20057 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20058 return DCI.CombineTo(N, NewVec, TF, true);
20061 // If this is a vector EXT Load then attempt to optimize it using a
20062 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20063 // expansion is still better than scalar code.
20064 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20065 // emit a shuffle and a arithmetic shift.
20066 // TODO: It is possible to support ZExt by zeroing the undef values
20067 // during the shuffle phase or after the shuffle.
20068 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20069 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20070 assert(MemVT != RegVT && "Cannot extend to the same type");
20071 assert(MemVT.isVector() && "Must load a vector from memory");
20073 unsigned NumElems = RegVT.getVectorNumElements();
20074 unsigned MemSz = MemVT.getSizeInBits();
20075 assert(RegSz > MemSz && "Register size must be greater than the mem size");
20077 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20080 // All sizes must be a power of two.
20081 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20084 // Attempt to load the original value using scalar loads.
20085 // Find the largest scalar type that divides the total loaded size.
20086 MVT SclrLoadTy = MVT::i8;
20087 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20088 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20089 MVT Tp = (MVT::SimpleValueType)tp;
20090 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20095 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20096 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20098 SclrLoadTy = MVT::f64;
20100 // Calculate the number of scalar loads that we need to perform
20101 // in order to load our vector from memory.
20102 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20103 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20106 unsigned loadRegZize = RegSz;
20107 if (Ext == ISD::SEXTLOAD && RegSz == 256)
20110 // Represent our vector as a sequence of elements which are the
20111 // largest scalar that we can load.
20112 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20113 loadRegZize/SclrLoadTy.getSizeInBits());
20115 // Represent the data using the same element type that is stored in
20116 // memory. In practice, we ''widen'' MemVT.
20118 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20119 loadRegZize/MemVT.getScalarType().getSizeInBits());
20121 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20122 "Invalid vector type");
20124 // We can't shuffle using an illegal type.
20125 if (!TLI.isTypeLegal(WideVecVT))
20128 SmallVector<SDValue, 8> Chains;
20129 SDValue Ptr = Ld->getBasePtr();
20130 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20131 TLI.getPointerTy());
20132 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20134 for (unsigned i = 0; i < NumLoads; ++i) {
20135 // Perform a single load.
20136 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20137 Ptr, Ld->getPointerInfo(),
20138 Ld->isVolatile(), Ld->isNonTemporal(),
20139 Ld->isInvariant(), Ld->getAlignment());
20140 Chains.push_back(ScalarLoad.getValue(1));
20141 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20142 // another round of DAGCombining.
20144 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20146 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20147 ScalarLoad, DAG.getIntPtrConstant(i));
20149 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20152 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20154 // Bitcast the loaded value to a vector of the original element type, in
20155 // the size of the target vector type.
20156 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20157 unsigned SizeRatio = RegSz/MemSz;
20159 if (Ext == ISD::SEXTLOAD) {
20160 // If we have SSE4.1 we can directly emit a VSEXT node.
20161 if (Subtarget->hasSSE41()) {
20162 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20163 return DCI.CombineTo(N, Sext, TF, true);
20166 // Otherwise we'll shuffle the small elements in the high bits of the
20167 // larger type and perform an arithmetic shift. If the shift is not legal
20168 // it's better to scalarize.
20169 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20172 // Redistribute the loaded elements into the different locations.
20173 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20174 for (unsigned i = 0; i != NumElems; ++i)
20175 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20177 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20178 DAG.getUNDEF(WideVecVT),
20181 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20183 // Build the arithmetic shift.
20184 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20185 MemVT.getVectorElementType().getSizeInBits();
20186 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20187 DAG.getConstant(Amt, RegVT));
20189 return DCI.CombineTo(N, Shuff, TF, true);
20192 // Redistribute the loaded elements into the different locations.
20193 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20194 for (unsigned i = 0; i != NumElems; ++i)
20195 ShuffleVec[i*SizeRatio] = i;
20197 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20198 DAG.getUNDEF(WideVecVT),
20201 // Bitcast to the requested type.
20202 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20203 // Replace the original load with the new sequence
20204 // and return the new chain.
20205 return DCI.CombineTo(N, Shuff, TF, true);
20211 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20212 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20213 const X86Subtarget *Subtarget) {
20214 StoreSDNode *St = cast<StoreSDNode>(N);
20215 EVT VT = St->getValue().getValueType();
20216 EVT StVT = St->getMemoryVT();
20218 SDValue StoredVal = St->getOperand(1);
20219 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20221 // If we are saving a concatenation of two XMM registers, perform two stores.
20222 // On Sandy Bridge, 256-bit memory operations are executed by two
20223 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20224 // memory operation.
20225 unsigned Alignment = St->getAlignment();
20226 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20227 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20228 StVT == VT && !IsAligned) {
20229 unsigned NumElems = VT.getVectorNumElements();
20233 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20234 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20236 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20237 SDValue Ptr0 = St->getBasePtr();
20238 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20240 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20241 St->getPointerInfo(), St->isVolatile(),
20242 St->isNonTemporal(), Alignment);
20243 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20244 St->getPointerInfo(), St->isVolatile(),
20245 St->isNonTemporal(),
20246 std::min(16U, Alignment));
20247 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20250 // Optimize trunc store (of multiple scalars) to shuffle and store.
20251 // First, pack all of the elements in one place. Next, store to memory
20252 // in fewer chunks.
20253 if (St->isTruncatingStore() && VT.isVector()) {
20254 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20255 unsigned NumElems = VT.getVectorNumElements();
20256 assert(StVT != VT && "Cannot truncate to the same type");
20257 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20258 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20260 // From, To sizes and ElemCount must be pow of two
20261 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20262 // We are going to use the original vector elt for storing.
20263 // Accumulated smaller vector elements must be a multiple of the store size.
20264 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20266 unsigned SizeRatio = FromSz / ToSz;
20268 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20270 // Create a type on which we perform the shuffle
20271 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20272 StVT.getScalarType(), NumElems*SizeRatio);
20274 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20276 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20277 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20278 for (unsigned i = 0; i != NumElems; ++i)
20279 ShuffleVec[i] = i * SizeRatio;
20281 // Can't shuffle using an illegal type.
20282 if (!TLI.isTypeLegal(WideVecVT))
20285 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20286 DAG.getUNDEF(WideVecVT),
20288 // At this point all of the data is stored at the bottom of the
20289 // register. We now need to save it to mem.
20291 // Find the largest store unit
20292 MVT StoreType = MVT::i8;
20293 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20294 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20295 MVT Tp = (MVT::SimpleValueType)tp;
20296 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20300 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20301 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20302 (64 <= NumElems * ToSz))
20303 StoreType = MVT::f64;
20305 // Bitcast the original vector into a vector of store-size units
20306 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20307 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20308 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20309 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20310 SmallVector<SDValue, 8> Chains;
20311 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20312 TLI.getPointerTy());
20313 SDValue Ptr = St->getBasePtr();
20315 // Perform one or more big stores into memory.
20316 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20317 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20318 StoreType, ShuffWide,
20319 DAG.getIntPtrConstant(i));
20320 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20321 St->getPointerInfo(), St->isVolatile(),
20322 St->isNonTemporal(), St->getAlignment());
20323 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20324 Chains.push_back(Ch);
20327 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20330 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
20331 // the FP state in cases where an emms may be missing.
20332 // A preferable solution to the general problem is to figure out the right
20333 // places to insert EMMS. This qualifies as a quick hack.
20335 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
20336 if (VT.getSizeInBits() != 64)
20339 const Function *F = DAG.getMachineFunction().getFunction();
20340 bool NoImplicitFloatOps = F->getAttributes().
20341 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20342 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20343 && Subtarget->hasSSE2();
20344 if ((VT.isVector() ||
20345 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20346 isa<LoadSDNode>(St->getValue()) &&
20347 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20348 St->getChain().hasOneUse() && !St->isVolatile()) {
20349 SDNode* LdVal = St->getValue().getNode();
20350 LoadSDNode *Ld = nullptr;
20351 int TokenFactorIndex = -1;
20352 SmallVector<SDValue, 8> Ops;
20353 SDNode* ChainVal = St->getChain().getNode();
20354 // Must be a store of a load. We currently handle two cases: the load
20355 // is a direct child, and it's under an intervening TokenFactor. It is
20356 // possible to dig deeper under nested TokenFactors.
20357 if (ChainVal == LdVal)
20358 Ld = cast<LoadSDNode>(St->getChain());
20359 else if (St->getValue().hasOneUse() &&
20360 ChainVal->getOpcode() == ISD::TokenFactor) {
20361 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20362 if (ChainVal->getOperand(i).getNode() == LdVal) {
20363 TokenFactorIndex = i;
20364 Ld = cast<LoadSDNode>(St->getValue());
20366 Ops.push_back(ChainVal->getOperand(i));
20370 if (!Ld || !ISD::isNormalLoad(Ld))
20373 // If this is not the MMX case, i.e. we are just turning i64 load/store
20374 // into f64 load/store, avoid the transformation if there are multiple
20375 // uses of the loaded value.
20376 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20381 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20382 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20384 if (Subtarget->is64Bit() || F64IsLegal) {
20385 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20386 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20387 Ld->getPointerInfo(), Ld->isVolatile(),
20388 Ld->isNonTemporal(), Ld->isInvariant(),
20389 Ld->getAlignment());
20390 SDValue NewChain = NewLd.getValue(1);
20391 if (TokenFactorIndex != -1) {
20392 Ops.push_back(NewChain);
20393 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20395 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20396 St->getPointerInfo(),
20397 St->isVolatile(), St->isNonTemporal(),
20398 St->getAlignment());
20401 // Otherwise, lower to two pairs of 32-bit loads / stores.
20402 SDValue LoAddr = Ld->getBasePtr();
20403 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20404 DAG.getConstant(4, MVT::i32));
20406 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20407 Ld->getPointerInfo(),
20408 Ld->isVolatile(), Ld->isNonTemporal(),
20409 Ld->isInvariant(), Ld->getAlignment());
20410 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20411 Ld->getPointerInfo().getWithOffset(4),
20412 Ld->isVolatile(), Ld->isNonTemporal(),
20414 MinAlign(Ld->getAlignment(), 4));
20416 SDValue NewChain = LoLd.getValue(1);
20417 if (TokenFactorIndex != -1) {
20418 Ops.push_back(LoLd);
20419 Ops.push_back(HiLd);
20420 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20423 LoAddr = St->getBasePtr();
20424 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20425 DAG.getConstant(4, MVT::i32));
20427 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20428 St->getPointerInfo(),
20429 St->isVolatile(), St->isNonTemporal(),
20430 St->getAlignment());
20431 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20432 St->getPointerInfo().getWithOffset(4),
20434 St->isNonTemporal(),
20435 MinAlign(St->getAlignment(), 4));
20436 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20441 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20442 /// and return the operands for the horizontal operation in LHS and RHS. A
20443 /// horizontal operation performs the binary operation on successive elements
20444 /// of its first operand, then on successive elements of its second operand,
20445 /// returning the resulting values in a vector. For example, if
20446 /// A = < float a0, float a1, float a2, float a3 >
20448 /// B = < float b0, float b1, float b2, float b3 >
20449 /// then the result of doing a horizontal operation on A and B is
20450 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20451 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20452 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20453 /// set to A, RHS to B, and the routine returns 'true'.
20454 /// Note that the binary operation should have the property that if one of the
20455 /// operands is UNDEF then the result is UNDEF.
20456 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20457 // Look for the following pattern: if
20458 // A = < float a0, float a1, float a2, float a3 >
20459 // B = < float b0, float b1, float b2, float b3 >
20461 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20462 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20463 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20464 // which is A horizontal-op B.
20466 // At least one of the operands should be a vector shuffle.
20467 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20468 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20471 MVT VT = LHS.getSimpleValueType();
20473 assert((VT.is128BitVector() || VT.is256BitVector()) &&
20474 "Unsupported vector type for horizontal add/sub");
20476 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20477 // operate independently on 128-bit lanes.
20478 unsigned NumElts = VT.getVectorNumElements();
20479 unsigned NumLanes = VT.getSizeInBits()/128;
20480 unsigned NumLaneElts = NumElts / NumLanes;
20481 assert((NumLaneElts % 2 == 0) &&
20482 "Vector type should have an even number of elements in each lane");
20483 unsigned HalfLaneElts = NumLaneElts/2;
20485 // View LHS in the form
20486 // LHS = VECTOR_SHUFFLE A, B, LMask
20487 // If LHS is not a shuffle then pretend it is the shuffle
20488 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20489 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20492 SmallVector<int, 16> LMask(NumElts);
20493 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20494 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20495 A = LHS.getOperand(0);
20496 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20497 B = LHS.getOperand(1);
20498 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20499 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20501 if (LHS.getOpcode() != ISD::UNDEF)
20503 for (unsigned i = 0; i != NumElts; ++i)
20507 // Likewise, view RHS in the form
20508 // RHS = VECTOR_SHUFFLE C, D, RMask
20510 SmallVector<int, 16> RMask(NumElts);
20511 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20512 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20513 C = RHS.getOperand(0);
20514 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20515 D = RHS.getOperand(1);
20516 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20517 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20519 if (RHS.getOpcode() != ISD::UNDEF)
20521 for (unsigned i = 0; i != NumElts; ++i)
20525 // Check that the shuffles are both shuffling the same vectors.
20526 if (!(A == C && B == D) && !(A == D && B == C))
20529 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20530 if (!A.getNode() && !B.getNode())
20533 // If A and B occur in reverse order in RHS, then "swap" them (which means
20534 // rewriting the mask).
20536 CommuteVectorShuffleMask(RMask, NumElts);
20538 // At this point LHS and RHS are equivalent to
20539 // LHS = VECTOR_SHUFFLE A, B, LMask
20540 // RHS = VECTOR_SHUFFLE A, B, RMask
20541 // Check that the masks correspond to performing a horizontal operation.
20542 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20543 for (unsigned i = 0; i != NumLaneElts; ++i) {
20544 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20546 // Ignore any UNDEF components.
20547 if (LIdx < 0 || RIdx < 0 ||
20548 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20549 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20552 // Check that successive elements are being operated on. If not, this is
20553 // not a horizontal operation.
20554 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20555 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20556 if (!(LIdx == Index && RIdx == Index + 1) &&
20557 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20562 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20563 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20567 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20568 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20569 const X86Subtarget *Subtarget) {
20570 EVT VT = N->getValueType(0);
20571 SDValue LHS = N->getOperand(0);
20572 SDValue RHS = N->getOperand(1);
20574 // Try to synthesize horizontal adds from adds of shuffles.
20575 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20576 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20577 isHorizontalBinOp(LHS, RHS, true))
20578 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20582 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20583 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20584 const X86Subtarget *Subtarget) {
20585 EVT VT = N->getValueType(0);
20586 SDValue LHS = N->getOperand(0);
20587 SDValue RHS = N->getOperand(1);
20589 // Try to synthesize horizontal subs from subs of shuffles.
20590 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20591 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20592 isHorizontalBinOp(LHS, RHS, false))
20593 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20597 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20598 /// X86ISD::FXOR nodes.
20599 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20600 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20601 // F[X]OR(0.0, x) -> x
20602 // F[X]OR(x, 0.0) -> x
20603 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20604 if (C->getValueAPF().isPosZero())
20605 return N->getOperand(1);
20606 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20607 if (C->getValueAPF().isPosZero())
20608 return N->getOperand(0);
20612 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20613 /// X86ISD::FMAX nodes.
20614 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20615 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20617 // Only perform optimizations if UnsafeMath is used.
20618 if (!DAG.getTarget().Options.UnsafeFPMath)
20621 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20622 // into FMINC and FMAXC, which are Commutative operations.
20623 unsigned NewOp = 0;
20624 switch (N->getOpcode()) {
20625 default: llvm_unreachable("unknown opcode");
20626 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20627 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20630 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20631 N->getOperand(0), N->getOperand(1));
20634 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20635 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20636 // FAND(0.0, x) -> 0.0
20637 // FAND(x, 0.0) -> 0.0
20638 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20639 if (C->getValueAPF().isPosZero())
20640 return N->getOperand(0);
20641 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20642 if (C->getValueAPF().isPosZero())
20643 return N->getOperand(1);
20647 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20648 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20649 // FANDN(x, 0.0) -> 0.0
20650 // FANDN(0.0, x) -> x
20651 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20652 if (C->getValueAPF().isPosZero())
20653 return N->getOperand(1);
20654 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20655 if (C->getValueAPF().isPosZero())
20656 return N->getOperand(1);
20660 static SDValue PerformBTCombine(SDNode *N,
20662 TargetLowering::DAGCombinerInfo &DCI) {
20663 // BT ignores high bits in the bit index operand.
20664 SDValue Op1 = N->getOperand(1);
20665 if (Op1.hasOneUse()) {
20666 unsigned BitWidth = Op1.getValueSizeInBits();
20667 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20668 APInt KnownZero, KnownOne;
20669 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20670 !DCI.isBeforeLegalizeOps());
20671 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20672 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20673 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20674 DCI.CommitTargetLoweringOpt(TLO);
20679 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20680 SDValue Op = N->getOperand(0);
20681 if (Op.getOpcode() == ISD::BITCAST)
20682 Op = Op.getOperand(0);
20683 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20684 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20685 VT.getVectorElementType().getSizeInBits() ==
20686 OpVT.getVectorElementType().getSizeInBits()) {
20687 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20692 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20693 const X86Subtarget *Subtarget) {
20694 EVT VT = N->getValueType(0);
20695 if (!VT.isVector())
20698 SDValue N0 = N->getOperand(0);
20699 SDValue N1 = N->getOperand(1);
20700 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20703 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20704 // both SSE and AVX2 since there is no sign-extended shift right
20705 // operation on a vector with 64-bit elements.
20706 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20707 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20708 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20709 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20710 SDValue N00 = N0.getOperand(0);
20712 // EXTLOAD has a better solution on AVX2,
20713 // it may be replaced with X86ISD::VSEXT node.
20714 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20715 if (!ISD::isNormalLoad(N00.getNode()))
20718 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20719 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20721 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20727 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20728 TargetLowering::DAGCombinerInfo &DCI,
20729 const X86Subtarget *Subtarget) {
20730 if (!DCI.isBeforeLegalizeOps())
20733 if (!Subtarget->hasFp256())
20736 EVT VT = N->getValueType(0);
20737 if (VT.isVector() && VT.getSizeInBits() == 256) {
20738 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20746 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20747 const X86Subtarget* Subtarget) {
20749 EVT VT = N->getValueType(0);
20751 // Let legalize expand this if it isn't a legal type yet.
20752 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20755 EVT ScalarVT = VT.getScalarType();
20756 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20757 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20760 SDValue A = N->getOperand(0);
20761 SDValue B = N->getOperand(1);
20762 SDValue C = N->getOperand(2);
20764 bool NegA = (A.getOpcode() == ISD::FNEG);
20765 bool NegB = (B.getOpcode() == ISD::FNEG);
20766 bool NegC = (C.getOpcode() == ISD::FNEG);
20768 // Negative multiplication when NegA xor NegB
20769 bool NegMul = (NegA != NegB);
20771 A = A.getOperand(0);
20773 B = B.getOperand(0);
20775 C = C.getOperand(0);
20779 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20781 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20783 return DAG.getNode(Opcode, dl, VT, A, B, C);
20786 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20787 TargetLowering::DAGCombinerInfo &DCI,
20788 const X86Subtarget *Subtarget) {
20789 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20790 // (and (i32 x86isd::setcc_carry), 1)
20791 // This eliminates the zext. This transformation is necessary because
20792 // ISD::SETCC is always legalized to i8.
20794 SDValue N0 = N->getOperand(0);
20795 EVT VT = N->getValueType(0);
20797 if (N0.getOpcode() == ISD::AND &&
20799 N0.getOperand(0).hasOneUse()) {
20800 SDValue N00 = N0.getOperand(0);
20801 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20802 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20803 if (!C || C->getZExtValue() != 1)
20805 return DAG.getNode(ISD::AND, dl, VT,
20806 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20807 N00.getOperand(0), N00.getOperand(1)),
20808 DAG.getConstant(1, VT));
20812 if (N0.getOpcode() == ISD::TRUNCATE &&
20814 N0.getOperand(0).hasOneUse()) {
20815 SDValue N00 = N0.getOperand(0);
20816 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20817 return DAG.getNode(ISD::AND, dl, VT,
20818 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20819 N00.getOperand(0), N00.getOperand(1)),
20820 DAG.getConstant(1, VT));
20823 if (VT.is256BitVector()) {
20824 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20832 // Optimize x == -y --> x+y == 0
20833 // x != -y --> x+y != 0
20834 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20835 const X86Subtarget* Subtarget) {
20836 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20837 SDValue LHS = N->getOperand(0);
20838 SDValue RHS = N->getOperand(1);
20839 EVT VT = N->getValueType(0);
20842 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20843 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20844 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20845 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20846 LHS.getValueType(), RHS, LHS.getOperand(1));
20847 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20848 addV, DAG.getConstant(0, addV.getValueType()), CC);
20850 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20851 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20852 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20853 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20854 RHS.getValueType(), LHS, RHS.getOperand(1));
20855 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20856 addV, DAG.getConstant(0, addV.getValueType()), CC);
20859 if (VT.getScalarType() == MVT::i1) {
20860 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20861 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20862 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20863 if (!IsSEXT0 && !IsVZero0)
20865 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20866 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20867 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20869 if (!IsSEXT1 && !IsVZero1)
20872 if (IsSEXT0 && IsVZero1) {
20873 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20874 if (CC == ISD::SETEQ)
20875 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20876 return LHS.getOperand(0);
20878 if (IsSEXT1 && IsVZero0) {
20879 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20880 if (CC == ISD::SETEQ)
20881 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20882 return RHS.getOperand(0);
20889 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20890 const X86Subtarget *Subtarget) {
20892 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20893 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20894 "X86insertps is only defined for v4x32");
20896 SDValue Ld = N->getOperand(1);
20897 if (MayFoldLoad(Ld)) {
20898 // Extract the countS bits from the immediate so we can get the proper
20899 // address when narrowing the vector load to a specific element.
20900 // When the second source op is a memory address, interps doesn't use
20901 // countS and just gets an f32 from that address.
20902 unsigned DestIndex =
20903 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20904 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20908 // Create this as a scalar to vector to match the instruction pattern.
20909 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20910 // countS bits are ignored when loading from memory on insertps, which
20911 // means we don't need to explicitly set them to 0.
20912 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20913 LoadScalarToVector, N->getOperand(2));
20916 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20917 // as "sbb reg,reg", since it can be extended without zext and produces
20918 // an all-ones bit which is more useful than 0/1 in some cases.
20919 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20922 return DAG.getNode(ISD::AND, DL, VT,
20923 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20924 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20925 DAG.getConstant(1, VT));
20926 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20927 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20928 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20929 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20932 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20933 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20934 TargetLowering::DAGCombinerInfo &DCI,
20935 const X86Subtarget *Subtarget) {
20937 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20938 SDValue EFLAGS = N->getOperand(1);
20940 if (CC == X86::COND_A) {
20941 // Try to convert COND_A into COND_B in an attempt to facilitate
20942 // materializing "setb reg".
20944 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20945 // cannot take an immediate as its first operand.
20947 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20948 EFLAGS.getValueType().isInteger() &&
20949 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20950 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20951 EFLAGS.getNode()->getVTList(),
20952 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20953 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20954 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20958 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20959 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20961 if (CC == X86::COND_B)
20962 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20966 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20967 if (Flags.getNode()) {
20968 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20969 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20975 // Optimize branch condition evaluation.
20977 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20978 TargetLowering::DAGCombinerInfo &DCI,
20979 const X86Subtarget *Subtarget) {
20981 SDValue Chain = N->getOperand(0);
20982 SDValue Dest = N->getOperand(1);
20983 SDValue EFLAGS = N->getOperand(3);
20984 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20988 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20989 if (Flags.getNode()) {
20990 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20991 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20998 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20999 const X86TargetLowering *XTLI) {
21000 SDValue Op0 = N->getOperand(0);
21001 EVT InVT = Op0->getValueType(0);
21003 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21004 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21006 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21007 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21008 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21011 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21012 // a 32-bit target where SSE doesn't support i64->FP operations.
21013 if (Op0.getOpcode() == ISD::LOAD) {
21014 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21015 EVT VT = Ld->getValueType(0);
21016 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21017 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21018 !XTLI->getSubtarget()->is64Bit() &&
21020 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21021 Ld->getChain(), Op0, DAG);
21022 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21029 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21030 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21031 X86TargetLowering::DAGCombinerInfo &DCI) {
21032 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21033 // the result is either zero or one (depending on the input carry bit).
21034 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21035 if (X86::isZeroNode(N->getOperand(0)) &&
21036 X86::isZeroNode(N->getOperand(1)) &&
21037 // We don't have a good way to replace an EFLAGS use, so only do this when
21039 SDValue(N, 1).use_empty()) {
21041 EVT VT = N->getValueType(0);
21042 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21043 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21044 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21045 DAG.getConstant(X86::COND_B,MVT::i8),
21047 DAG.getConstant(1, VT));
21048 return DCI.CombineTo(N, Res1, CarryOut);
21054 // fold (add Y, (sete X, 0)) -> adc 0, Y
21055 // (add Y, (setne X, 0)) -> sbb -1, Y
21056 // (sub (sete X, 0), Y) -> sbb 0, Y
21057 // (sub (setne X, 0), Y) -> adc -1, Y
21058 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21061 // Look through ZExts.
21062 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21063 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21066 SDValue SetCC = Ext.getOperand(0);
21067 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21070 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21071 if (CC != X86::COND_E && CC != X86::COND_NE)
21074 SDValue Cmp = SetCC.getOperand(1);
21075 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21076 !X86::isZeroNode(Cmp.getOperand(1)) ||
21077 !Cmp.getOperand(0).getValueType().isInteger())
21080 SDValue CmpOp0 = Cmp.getOperand(0);
21081 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21082 DAG.getConstant(1, CmpOp0.getValueType()));
21084 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21085 if (CC == X86::COND_NE)
21086 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21087 DL, OtherVal.getValueType(), OtherVal,
21088 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21089 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21090 DL, OtherVal.getValueType(), OtherVal,
21091 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21094 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21095 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21096 const X86Subtarget *Subtarget) {
21097 EVT VT = N->getValueType(0);
21098 SDValue Op0 = N->getOperand(0);
21099 SDValue Op1 = N->getOperand(1);
21101 // Try to synthesize horizontal adds from adds of shuffles.
21102 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21103 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21104 isHorizontalBinOp(Op0, Op1, true))
21105 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21107 return OptimizeConditionalInDecrement(N, DAG);
21110 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21111 const X86Subtarget *Subtarget) {
21112 SDValue Op0 = N->getOperand(0);
21113 SDValue Op1 = N->getOperand(1);
21115 // X86 can't encode an immediate LHS of a sub. See if we can push the
21116 // negation into a preceding instruction.
21117 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21118 // If the RHS of the sub is a XOR with one use and a constant, invert the
21119 // immediate. Then add one to the LHS of the sub so we can turn
21120 // X-Y -> X+~Y+1, saving one register.
21121 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21122 isa<ConstantSDNode>(Op1.getOperand(1))) {
21123 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21124 EVT VT = Op0.getValueType();
21125 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21127 DAG.getConstant(~XorC, VT));
21128 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21129 DAG.getConstant(C->getAPIntValue()+1, VT));
21133 // Try to synthesize horizontal adds from adds of shuffles.
21134 EVT VT = N->getValueType(0);
21135 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21136 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21137 isHorizontalBinOp(Op0, Op1, true))
21138 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21140 return OptimizeConditionalInDecrement(N, DAG);
21143 /// performVZEXTCombine - Performs build vector combines
21144 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21145 TargetLowering::DAGCombinerInfo &DCI,
21146 const X86Subtarget *Subtarget) {
21147 // (vzext (bitcast (vzext (x)) -> (vzext x)
21148 SDValue In = N->getOperand(0);
21149 while (In.getOpcode() == ISD::BITCAST)
21150 In = In.getOperand(0);
21152 if (In.getOpcode() != X86ISD::VZEXT)
21155 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21159 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21160 DAGCombinerInfo &DCI) const {
21161 SelectionDAG &DAG = DCI.DAG;
21162 switch (N->getOpcode()) {
21164 case ISD::EXTRACT_VECTOR_ELT:
21165 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21167 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21168 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21169 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
21170 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
21171 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
21172 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
21175 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
21176 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
21177 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
21178 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
21179 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
21180 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
21181 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
21182 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
21183 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
21185 case X86ISD::FOR: return PerformFORCombine(N, DAG);
21187 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
21188 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
21189 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
21190 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
21191 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
21192 case ISD::ANY_EXTEND:
21193 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
21194 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
21195 case ISD::SIGN_EXTEND_INREG:
21196 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21197 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21198 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
21199 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21200 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21201 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
21202 case X86ISD::SHUFP: // Handle all target specific shuffles
21203 case X86ISD::PALIGNR:
21204 case X86ISD::UNPCKH:
21205 case X86ISD::UNPCKL:
21206 case X86ISD::MOVHLPS:
21207 case X86ISD::MOVLHPS:
21208 case X86ISD::PSHUFD:
21209 case X86ISD::PSHUFHW:
21210 case X86ISD::PSHUFLW:
21211 case X86ISD::MOVSS:
21212 case X86ISD::MOVSD:
21213 case X86ISD::VPERMILP:
21214 case X86ISD::VPERM2X128:
21215 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21216 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
21217 case ISD::INTRINSIC_WO_CHAIN:
21218 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21219 case X86ISD::INSERTPS:
21220 return PerformINSERTPSCombine(N, DAG, Subtarget);
21221 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21227 /// isTypeDesirableForOp - Return true if the target has native support for
21228 /// the specified value type and it is 'desirable' to use the type for the
21229 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21230 /// instruction encodings are longer and some i16 instructions are slow.
21231 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21232 if (!isTypeLegal(VT))
21234 if (VT != MVT::i16)
21241 case ISD::SIGN_EXTEND:
21242 case ISD::ZERO_EXTEND:
21243 case ISD::ANY_EXTEND:
21256 /// IsDesirableToPromoteOp - This method query the target whether it is
21257 /// beneficial for dag combiner to promote the specified node. If true, it
21258 /// should return the desired promotion type by reference.
21259 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21260 EVT VT = Op.getValueType();
21261 if (VT != MVT::i16)
21264 bool Promote = false;
21265 bool Commute = false;
21266 switch (Op.getOpcode()) {
21269 LoadSDNode *LD = cast<LoadSDNode>(Op);
21270 // If the non-extending load has a single use and it's not live out, then it
21271 // might be folded.
21272 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21273 Op.hasOneUse()*/) {
21274 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21275 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21276 // The only case where we'd want to promote LOAD (rather then it being
21277 // promoted as an operand is when it's only use is liveout.
21278 if (UI->getOpcode() != ISD::CopyToReg)
21285 case ISD::SIGN_EXTEND:
21286 case ISD::ZERO_EXTEND:
21287 case ISD::ANY_EXTEND:
21292 SDValue N0 = Op.getOperand(0);
21293 // Look out for (store (shl (load), x)).
21294 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21307 SDValue N0 = Op.getOperand(0);
21308 SDValue N1 = Op.getOperand(1);
21309 if (!Commute && MayFoldLoad(N1))
21311 // Avoid disabling potential load folding opportunities.
21312 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21314 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21324 //===----------------------------------------------------------------------===//
21325 // X86 Inline Assembly Support
21326 //===----------------------------------------------------------------------===//
21329 // Helper to match a string separated by whitespace.
21330 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21331 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21333 for (unsigned i = 0, e = args.size(); i != e; ++i) {
21334 StringRef piece(*args[i]);
21335 if (!s.startswith(piece)) // Check if the piece matches.
21338 s = s.substr(piece.size());
21339 StringRef::size_type pos = s.find_first_not_of(" \t");
21340 if (pos == 0) // We matched a prefix.
21348 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21351 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21353 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21354 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21355 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21356 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21358 if (AsmPieces.size() == 3)
21360 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21367 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21368 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21370 std::string AsmStr = IA->getAsmString();
21372 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21373 if (!Ty || Ty->getBitWidth() % 16 != 0)
21376 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21377 SmallVector<StringRef, 4> AsmPieces;
21378 SplitString(AsmStr, AsmPieces, ";\n");
21380 switch (AsmPieces.size()) {
21381 default: return false;
21383 // FIXME: this should verify that we are targeting a 486 or better. If not,
21384 // we will turn this bswap into something that will be lowered to logical
21385 // ops instead of emitting the bswap asm. For now, we don't support 486 or
21386 // lower so don't worry about this.
21388 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21389 matchAsm(AsmPieces[0], "bswapl", "$0") ||
21390 matchAsm(AsmPieces[0], "bswapq", "$0") ||
21391 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21392 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21393 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21394 // No need to check constraints, nothing other than the equivalent of
21395 // "=r,0" would be valid here.
21396 return IntrinsicLowering::LowerToByteSwap(CI);
21399 // rorw $$8, ${0:w} --> llvm.bswap.i16
21400 if (CI->getType()->isIntegerTy(16) &&
21401 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21402 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21403 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21405 const std::string &ConstraintsStr = IA->getConstraintString();
21406 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21407 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21408 if (clobbersFlagRegisters(AsmPieces))
21409 return IntrinsicLowering::LowerToByteSwap(CI);
21413 if (CI->getType()->isIntegerTy(32) &&
21414 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21415 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21416 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21417 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21419 const std::string &ConstraintsStr = IA->getConstraintString();
21420 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21421 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21422 if (clobbersFlagRegisters(AsmPieces))
21423 return IntrinsicLowering::LowerToByteSwap(CI);
21426 if (CI->getType()->isIntegerTy(64)) {
21427 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21428 if (Constraints.size() >= 2 &&
21429 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21430 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21431 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
21432 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21433 matchAsm(AsmPieces[1], "bswap", "%edx") &&
21434 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21435 return IntrinsicLowering::LowerToByteSwap(CI);
21443 /// getConstraintType - Given a constraint letter, return the type of
21444 /// constraint it is for this target.
21445 X86TargetLowering::ConstraintType
21446 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21447 if (Constraint.size() == 1) {
21448 switch (Constraint[0]) {
21459 return C_RegisterClass;
21483 return TargetLowering::getConstraintType(Constraint);
21486 /// Examine constraint type and operand type and determine a weight value.
21487 /// This object must already have been set up with the operand type
21488 /// and the current alternative constraint selected.
21489 TargetLowering::ConstraintWeight
21490 X86TargetLowering::getSingleConstraintMatchWeight(
21491 AsmOperandInfo &info, const char *constraint) const {
21492 ConstraintWeight weight = CW_Invalid;
21493 Value *CallOperandVal = info.CallOperandVal;
21494 // If we don't have a value, we can't do a match,
21495 // but allow it at the lowest weight.
21496 if (!CallOperandVal)
21498 Type *type = CallOperandVal->getType();
21499 // Look at the constraint type.
21500 switch (*constraint) {
21502 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21513 if (CallOperandVal->getType()->isIntegerTy())
21514 weight = CW_SpecificReg;
21519 if (type->isFloatingPointTy())
21520 weight = CW_SpecificReg;
21523 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21524 weight = CW_SpecificReg;
21528 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21529 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21530 weight = CW_Register;
21533 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21534 if (C->getZExtValue() <= 31)
21535 weight = CW_Constant;
21539 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21540 if (C->getZExtValue() <= 63)
21541 weight = CW_Constant;
21545 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21546 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21547 weight = CW_Constant;
21551 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21552 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21553 weight = CW_Constant;
21557 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21558 if (C->getZExtValue() <= 3)
21559 weight = CW_Constant;
21563 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21564 if (C->getZExtValue() <= 0xff)
21565 weight = CW_Constant;
21570 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21571 weight = CW_Constant;
21575 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21576 if ((C->getSExtValue() >= -0x80000000LL) &&
21577 (C->getSExtValue() <= 0x7fffffffLL))
21578 weight = CW_Constant;
21582 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21583 if (C->getZExtValue() <= 0xffffffff)
21584 weight = CW_Constant;
21591 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21592 /// with another that has more specific requirements based on the type of the
21593 /// corresponding operand.
21594 const char *X86TargetLowering::
21595 LowerXConstraint(EVT ConstraintVT) const {
21596 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21597 // 'f' like normal targets.
21598 if (ConstraintVT.isFloatingPoint()) {
21599 if (Subtarget->hasSSE2())
21601 if (Subtarget->hasSSE1())
21605 return TargetLowering::LowerXConstraint(ConstraintVT);
21608 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21609 /// vector. If it is invalid, don't add anything to Ops.
21610 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21611 std::string &Constraint,
21612 std::vector<SDValue>&Ops,
21613 SelectionDAG &DAG) const {
21616 // Only support length 1 constraints for now.
21617 if (Constraint.length() > 1) return;
21619 char ConstraintLetter = Constraint[0];
21620 switch (ConstraintLetter) {
21623 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21624 if (C->getZExtValue() <= 31) {
21625 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21631 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21632 if (C->getZExtValue() <= 63) {
21633 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21639 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21640 if (isInt<8>(C->getSExtValue())) {
21641 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21647 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21648 if (C->getZExtValue() <= 255) {
21649 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21655 // 32-bit signed value
21656 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21657 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21658 C->getSExtValue())) {
21659 // Widen to 64 bits here to get it sign extended.
21660 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21663 // FIXME gcc accepts some relocatable values here too, but only in certain
21664 // memory models; it's complicated.
21669 // 32-bit unsigned value
21670 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21671 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21672 C->getZExtValue())) {
21673 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21677 // FIXME gcc accepts some relocatable values here too, but only in certain
21678 // memory models; it's complicated.
21682 // Literal immediates are always ok.
21683 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21684 // Widen to 64 bits here to get it sign extended.
21685 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21689 // In any sort of PIC mode addresses need to be computed at runtime by
21690 // adding in a register or some sort of table lookup. These can't
21691 // be used as immediates.
21692 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21695 // If we are in non-pic codegen mode, we allow the address of a global (with
21696 // an optional displacement) to be used with 'i'.
21697 GlobalAddressSDNode *GA = nullptr;
21698 int64_t Offset = 0;
21700 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21702 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21703 Offset += GA->getOffset();
21705 } else if (Op.getOpcode() == ISD::ADD) {
21706 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21707 Offset += C->getZExtValue();
21708 Op = Op.getOperand(0);
21711 } else if (Op.getOpcode() == ISD::SUB) {
21712 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21713 Offset += -C->getZExtValue();
21714 Op = Op.getOperand(0);
21719 // Otherwise, this isn't something we can handle, reject it.
21723 const GlobalValue *GV = GA->getGlobal();
21724 // If we require an extra load to get this address, as in PIC mode, we
21725 // can't accept it.
21726 if (isGlobalStubReference(
21727 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21730 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21731 GA->getValueType(0), Offset);
21736 if (Result.getNode()) {
21737 Ops.push_back(Result);
21740 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21743 std::pair<unsigned, const TargetRegisterClass*>
21744 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21746 // First, see if this is a constraint that directly corresponds to an LLVM
21748 if (Constraint.size() == 1) {
21749 // GCC Constraint Letters
21750 switch (Constraint[0]) {
21752 // TODO: Slight differences here in allocation order and leaving
21753 // RIP in the class. Do they matter any more here than they do
21754 // in the normal allocation?
21755 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21756 if (Subtarget->is64Bit()) {
21757 if (VT == MVT::i32 || VT == MVT::f32)
21758 return std::make_pair(0U, &X86::GR32RegClass);
21759 if (VT == MVT::i16)
21760 return std::make_pair(0U, &X86::GR16RegClass);
21761 if (VT == MVT::i8 || VT == MVT::i1)
21762 return std::make_pair(0U, &X86::GR8RegClass);
21763 if (VT == MVT::i64 || VT == MVT::f64)
21764 return std::make_pair(0U, &X86::GR64RegClass);
21767 // 32-bit fallthrough
21768 case 'Q': // Q_REGS
21769 if (VT == MVT::i32 || VT == MVT::f32)
21770 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21771 if (VT == MVT::i16)
21772 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21773 if (VT == MVT::i8 || VT == MVT::i1)
21774 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21775 if (VT == MVT::i64)
21776 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21778 case 'r': // GENERAL_REGS
21779 case 'l': // INDEX_REGS
21780 if (VT == MVT::i8 || VT == MVT::i1)
21781 return std::make_pair(0U, &X86::GR8RegClass);
21782 if (VT == MVT::i16)
21783 return std::make_pair(0U, &X86::GR16RegClass);
21784 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21785 return std::make_pair(0U, &X86::GR32RegClass);
21786 return std::make_pair(0U, &X86::GR64RegClass);
21787 case 'R': // LEGACY_REGS
21788 if (VT == MVT::i8 || VT == MVT::i1)
21789 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21790 if (VT == MVT::i16)
21791 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21792 if (VT == MVT::i32 || !Subtarget->is64Bit())
21793 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21794 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21795 case 'f': // FP Stack registers.
21796 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21797 // value to the correct fpstack register class.
21798 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21799 return std::make_pair(0U, &X86::RFP32RegClass);
21800 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21801 return std::make_pair(0U, &X86::RFP64RegClass);
21802 return std::make_pair(0U, &X86::RFP80RegClass);
21803 case 'y': // MMX_REGS if MMX allowed.
21804 if (!Subtarget->hasMMX()) break;
21805 return std::make_pair(0U, &X86::VR64RegClass);
21806 case 'Y': // SSE_REGS if SSE2 allowed
21807 if (!Subtarget->hasSSE2()) break;
21809 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21810 if (!Subtarget->hasSSE1()) break;
21812 switch (VT.SimpleTy) {
21814 // Scalar SSE types.
21817 return std::make_pair(0U, &X86::FR32RegClass);
21820 return std::make_pair(0U, &X86::FR64RegClass);
21828 return std::make_pair(0U, &X86::VR128RegClass);
21836 return std::make_pair(0U, &X86::VR256RegClass);
21841 return std::make_pair(0U, &X86::VR512RegClass);
21847 // Use the default implementation in TargetLowering to convert the register
21848 // constraint into a member of a register class.
21849 std::pair<unsigned, const TargetRegisterClass*> Res;
21850 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21852 // Not found as a standard register?
21854 // Map st(0) -> st(7) -> ST0
21855 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21856 tolower(Constraint[1]) == 's' &&
21857 tolower(Constraint[2]) == 't' &&
21858 Constraint[3] == '(' &&
21859 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21860 Constraint[5] == ')' &&
21861 Constraint[6] == '}') {
21863 Res.first = X86::ST0+Constraint[4]-'0';
21864 Res.second = &X86::RFP80RegClass;
21868 // GCC allows "st(0)" to be called just plain "st".
21869 if (StringRef("{st}").equals_lower(Constraint)) {
21870 Res.first = X86::ST0;
21871 Res.second = &X86::RFP80RegClass;
21876 if (StringRef("{flags}").equals_lower(Constraint)) {
21877 Res.first = X86::EFLAGS;
21878 Res.second = &X86::CCRRegClass;
21882 // 'A' means EAX + EDX.
21883 if (Constraint == "A") {
21884 Res.first = X86::EAX;
21885 Res.second = &X86::GR32_ADRegClass;
21891 // Otherwise, check to see if this is a register class of the wrong value
21892 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21893 // turn into {ax},{dx}.
21894 if (Res.second->hasType(VT))
21895 return Res; // Correct type already, nothing to do.
21897 // All of the single-register GCC register classes map their values onto
21898 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21899 // really want an 8-bit or 32-bit register, map to the appropriate register
21900 // class and return the appropriate register.
21901 if (Res.second == &X86::GR16RegClass) {
21902 if (VT == MVT::i8 || VT == MVT::i1) {
21903 unsigned DestReg = 0;
21904 switch (Res.first) {
21906 case X86::AX: DestReg = X86::AL; break;
21907 case X86::DX: DestReg = X86::DL; break;
21908 case X86::CX: DestReg = X86::CL; break;
21909 case X86::BX: DestReg = X86::BL; break;
21912 Res.first = DestReg;
21913 Res.second = &X86::GR8RegClass;
21915 } else if (VT == MVT::i32 || VT == MVT::f32) {
21916 unsigned DestReg = 0;
21917 switch (Res.first) {
21919 case X86::AX: DestReg = X86::EAX; break;
21920 case X86::DX: DestReg = X86::EDX; break;
21921 case X86::CX: DestReg = X86::ECX; break;
21922 case X86::BX: DestReg = X86::EBX; break;
21923 case X86::SI: DestReg = X86::ESI; break;
21924 case X86::DI: DestReg = X86::EDI; break;
21925 case X86::BP: DestReg = X86::EBP; break;
21926 case X86::SP: DestReg = X86::ESP; break;
21929 Res.first = DestReg;
21930 Res.second = &X86::GR32RegClass;
21932 } else if (VT == MVT::i64 || VT == MVT::f64) {
21933 unsigned DestReg = 0;
21934 switch (Res.first) {
21936 case X86::AX: DestReg = X86::RAX; break;
21937 case X86::DX: DestReg = X86::RDX; break;
21938 case X86::CX: DestReg = X86::RCX; break;
21939 case X86::BX: DestReg = X86::RBX; break;
21940 case X86::SI: DestReg = X86::RSI; break;
21941 case X86::DI: DestReg = X86::RDI; break;
21942 case X86::BP: DestReg = X86::RBP; break;
21943 case X86::SP: DestReg = X86::RSP; break;
21946 Res.first = DestReg;
21947 Res.second = &X86::GR64RegClass;
21950 } else if (Res.second == &X86::FR32RegClass ||
21951 Res.second == &X86::FR64RegClass ||
21952 Res.second == &X86::VR128RegClass ||
21953 Res.second == &X86::VR256RegClass ||
21954 Res.second == &X86::FR32XRegClass ||
21955 Res.second == &X86::FR64XRegClass ||
21956 Res.second == &X86::VR128XRegClass ||
21957 Res.second == &X86::VR256XRegClass ||
21958 Res.second == &X86::VR512RegClass) {
21959 // Handle references to XMM physical registers that got mapped into the
21960 // wrong class. This can happen with constraints like {xmm0} where the
21961 // target independent register mapper will just pick the first match it can
21962 // find, ignoring the required type.
21964 if (VT == MVT::f32 || VT == MVT::i32)
21965 Res.second = &X86::FR32RegClass;
21966 else if (VT == MVT::f64 || VT == MVT::i64)
21967 Res.second = &X86::FR64RegClass;
21968 else if (X86::VR128RegClass.hasType(VT))
21969 Res.second = &X86::VR128RegClass;
21970 else if (X86::VR256RegClass.hasType(VT))
21971 Res.second = &X86::VR256RegClass;
21972 else if (X86::VR512RegClass.hasType(VT))
21973 Res.second = &X86::VR512RegClass;
21979 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21981 // Scaling factors are not free at all.
21982 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21983 // will take 2 allocations in the out of order engine instead of 1
21984 // for plain addressing mode, i.e. inst (reg1).
21986 // vaddps (%rsi,%drx), %ymm0, %ymm1
21987 // Requires two allocations (one for the load, one for the computation)
21989 // vaddps (%rsi), %ymm0, %ymm1
21990 // Requires just 1 allocation, i.e., freeing allocations for other operations
21991 // and having less micro operations to execute.
21993 // For some X86 architectures, this is even worse because for instance for
21994 // stores, the complex addressing mode forces the instruction to use the
21995 // "load" ports instead of the dedicated "store" port.
21996 // E.g., on Haswell:
21997 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21998 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21999 if (isLegalAddressingMode(AM, Ty))
22000 // Scale represents reg2 * scale, thus account for 1
22001 // as soon as we use a second register.
22002 return AM.Scale != 0;
22006 bool X86TargetLowering::isTargetFTOL() const {
22007 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();