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, 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, 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 // Custom lower several nodes.
1443 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1444 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1445 MVT VT = (MVT::SimpleValueType)i;
1447 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1448 // Extract subvector is special because the value type
1449 // (result) is 256/128-bit but the source is 512-bit wide.
1450 if (VT.is128BitVector() || VT.is256BitVector())
1451 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1453 if (VT.getVectorElementType() == MVT::i1)
1454 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1456 // Do not attempt to custom lower other non-512-bit vectors
1457 if (!VT.is512BitVector())
1460 if ( EltSize >= 32) {
1461 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1462 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1463 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1464 setOperationAction(ISD::VSELECT, VT, Legal);
1465 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1466 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1467 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1470 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1471 MVT VT = (MVT::SimpleValueType)i;
1473 // Do not attempt to promote non-256-bit vectors
1474 if (!VT.is512BitVector())
1477 setOperationAction(ISD::SELECT, VT, Promote);
1478 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1482 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1483 // of this type with custom code.
1484 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1485 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1486 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1490 // We want to custom lower some of our intrinsics.
1491 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1492 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1493 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1494 if (!Subtarget->is64Bit())
1495 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1497 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1498 // handle type legalization for these operations here.
1500 // FIXME: We really should do custom legalization for addition and
1501 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1502 // than generic legalization for 64-bit multiplication-with-overflow, though.
1503 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1504 // Add/Sub/Mul with overflow operations are custom lowered.
1506 setOperationAction(ISD::SADDO, VT, Custom);
1507 setOperationAction(ISD::UADDO, VT, Custom);
1508 setOperationAction(ISD::SSUBO, VT, Custom);
1509 setOperationAction(ISD::USUBO, VT, Custom);
1510 setOperationAction(ISD::SMULO, VT, Custom);
1511 setOperationAction(ISD::UMULO, VT, Custom);
1514 // There are no 8-bit 3-address imul/mul instructions
1515 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1516 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1518 if (!Subtarget->is64Bit()) {
1519 // These libcalls are not available in 32-bit.
1520 setLibcallName(RTLIB::SHL_I128, nullptr);
1521 setLibcallName(RTLIB::SRL_I128, nullptr);
1522 setLibcallName(RTLIB::SRA_I128, nullptr);
1525 // Combine sin / cos into one node or libcall if possible.
1526 if (Subtarget->hasSinCos()) {
1527 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1528 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1529 if (Subtarget->isTargetDarwin()) {
1530 // For MacOSX, we don't want to the normal expansion of a libcall to
1531 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1533 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1534 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1538 if (Subtarget->isTargetWin64()) {
1539 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1540 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1541 setOperationAction(ISD::SREM, MVT::i128, Custom);
1542 setOperationAction(ISD::UREM, MVT::i128, Custom);
1543 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1544 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1547 // We have target-specific dag combine patterns for the following nodes:
1548 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1549 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1550 setTargetDAGCombine(ISD::VSELECT);
1551 setTargetDAGCombine(ISD::SELECT);
1552 setTargetDAGCombine(ISD::SHL);
1553 setTargetDAGCombine(ISD::SRA);
1554 setTargetDAGCombine(ISD::SRL);
1555 setTargetDAGCombine(ISD::OR);
1556 setTargetDAGCombine(ISD::AND);
1557 setTargetDAGCombine(ISD::ADD);
1558 setTargetDAGCombine(ISD::FADD);
1559 setTargetDAGCombine(ISD::FSUB);
1560 setTargetDAGCombine(ISD::FMA);
1561 setTargetDAGCombine(ISD::SUB);
1562 setTargetDAGCombine(ISD::LOAD);
1563 setTargetDAGCombine(ISD::STORE);
1564 setTargetDAGCombine(ISD::ZERO_EXTEND);
1565 setTargetDAGCombine(ISD::ANY_EXTEND);
1566 setTargetDAGCombine(ISD::SIGN_EXTEND);
1567 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1568 setTargetDAGCombine(ISD::TRUNCATE);
1569 setTargetDAGCombine(ISD::SINT_TO_FP);
1570 setTargetDAGCombine(ISD::SETCC);
1571 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1572 setTargetDAGCombine(ISD::BUILD_VECTOR);
1573 if (Subtarget->is64Bit())
1574 setTargetDAGCombine(ISD::MUL);
1575 setTargetDAGCombine(ISD::XOR);
1577 computeRegisterProperties();
1579 // On Darwin, -Os means optimize for size without hurting performance,
1580 // do not reduce the limit.
1581 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1582 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1583 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1584 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1585 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1586 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1587 setPrefLoopAlignment(4); // 2^4 bytes.
1589 // Predictable cmov don't hurt on atom because it's in-order.
1590 PredictableSelectIsExpensive = !Subtarget->isAtom();
1592 setPrefFunctionAlignment(4); // 2^4 bytes.
1595 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1597 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1599 if (Subtarget->hasAVX512())
1600 switch(VT.getVectorNumElements()) {
1601 case 8: return MVT::v8i1;
1602 case 16: return MVT::v16i1;
1605 return VT.changeVectorElementTypeToInteger();
1608 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1609 /// the desired ByVal argument alignment.
1610 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1613 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1614 if (VTy->getBitWidth() == 128)
1616 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1617 unsigned EltAlign = 0;
1618 getMaxByValAlign(ATy->getElementType(), EltAlign);
1619 if (EltAlign > MaxAlign)
1620 MaxAlign = EltAlign;
1621 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1622 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1623 unsigned EltAlign = 0;
1624 getMaxByValAlign(STy->getElementType(i), EltAlign);
1625 if (EltAlign > MaxAlign)
1626 MaxAlign = EltAlign;
1633 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1634 /// function arguments in the caller parameter area. For X86, aggregates
1635 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1636 /// are at 4-byte boundaries.
1637 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1638 if (Subtarget->is64Bit()) {
1639 // Max of 8 and alignment of type.
1640 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1647 if (Subtarget->hasSSE1())
1648 getMaxByValAlign(Ty, Align);
1652 /// getOptimalMemOpType - Returns the target specific optimal type for load
1653 /// and store operations as a result of memset, memcpy, and memmove
1654 /// lowering. If DstAlign is zero that means it's safe to destination
1655 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1656 /// means there isn't a need to check it against alignment requirement,
1657 /// probably because the source does not need to be loaded. If 'IsMemset' is
1658 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1659 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1660 /// source is constant so it does not need to be loaded.
1661 /// It returns EVT::Other if the type should be determined using generic
1662 /// target-independent logic.
1664 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1665 unsigned DstAlign, unsigned SrcAlign,
1666 bool IsMemset, bool ZeroMemset,
1668 MachineFunction &MF) const {
1669 const Function *F = MF.getFunction();
1670 if ((!IsMemset || ZeroMemset) &&
1671 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1672 Attribute::NoImplicitFloat)) {
1674 (Subtarget->isUnalignedMemAccessFast() ||
1675 ((DstAlign == 0 || DstAlign >= 16) &&
1676 (SrcAlign == 0 || SrcAlign >= 16)))) {
1678 if (Subtarget->hasInt256())
1680 if (Subtarget->hasFp256())
1683 if (Subtarget->hasSSE2())
1685 if (Subtarget->hasSSE1())
1687 } else if (!MemcpyStrSrc && Size >= 8 &&
1688 !Subtarget->is64Bit() &&
1689 Subtarget->hasSSE2()) {
1690 // Do not use f64 to lower memcpy if source is string constant. It's
1691 // better to use i32 to avoid the loads.
1695 if (Subtarget->is64Bit() && Size >= 8)
1700 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1702 return X86ScalarSSEf32;
1703 else if (VT == MVT::f64)
1704 return X86ScalarSSEf64;
1709 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1713 *Fast = Subtarget->isUnalignedMemAccessFast();
1717 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1718 /// current function. The returned value is a member of the
1719 /// MachineJumpTableInfo::JTEntryKind enum.
1720 unsigned X86TargetLowering::getJumpTableEncoding() const {
1721 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1723 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1724 Subtarget->isPICStyleGOT())
1725 return MachineJumpTableInfo::EK_Custom32;
1727 // Otherwise, use the normal jump table encoding heuristics.
1728 return TargetLowering::getJumpTableEncoding();
1732 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1733 const MachineBasicBlock *MBB,
1734 unsigned uid,MCContext &Ctx) const{
1735 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1736 Subtarget->isPICStyleGOT());
1737 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1739 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1740 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1743 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1745 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1746 SelectionDAG &DAG) const {
1747 if (!Subtarget->is64Bit())
1748 // This doesn't have SDLoc associated with it, but is not really the
1749 // same as a Register.
1750 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1754 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1755 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1757 const MCExpr *X86TargetLowering::
1758 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1759 MCContext &Ctx) const {
1760 // X86-64 uses RIP relative addressing based on the jump table label.
1761 if (Subtarget->isPICStyleRIPRel())
1762 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1764 // Otherwise, the reference is relative to the PIC base.
1765 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1768 // FIXME: Why this routine is here? Move to RegInfo!
1769 std::pair<const TargetRegisterClass*, uint8_t>
1770 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1771 const TargetRegisterClass *RRC = nullptr;
1773 switch (VT.SimpleTy) {
1775 return TargetLowering::findRepresentativeClass(VT);
1776 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1777 RRC = Subtarget->is64Bit() ?
1778 (const TargetRegisterClass*)&X86::GR64RegClass :
1779 (const TargetRegisterClass*)&X86::GR32RegClass;
1782 RRC = &X86::VR64RegClass;
1784 case MVT::f32: case MVT::f64:
1785 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1786 case MVT::v4f32: case MVT::v2f64:
1787 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1789 RRC = &X86::VR128RegClass;
1792 return std::make_pair(RRC, Cost);
1795 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1796 unsigned &Offset) const {
1797 if (!Subtarget->isTargetLinux())
1800 if (Subtarget->is64Bit()) {
1801 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1803 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1815 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1816 unsigned DestAS) const {
1817 assert(SrcAS != DestAS && "Expected different address spaces!");
1819 return SrcAS < 256 && DestAS < 256;
1822 //===----------------------------------------------------------------------===//
1823 // Return Value Calling Convention Implementation
1824 //===----------------------------------------------------------------------===//
1826 #include "X86GenCallingConv.inc"
1829 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1830 MachineFunction &MF, bool isVarArg,
1831 const SmallVectorImpl<ISD::OutputArg> &Outs,
1832 LLVMContext &Context) const {
1833 SmallVector<CCValAssign, 16> RVLocs;
1834 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1836 return CCInfo.CheckReturn(Outs, RetCC_X86);
1839 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1840 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1845 X86TargetLowering::LowerReturn(SDValue Chain,
1846 CallingConv::ID CallConv, bool isVarArg,
1847 const SmallVectorImpl<ISD::OutputArg> &Outs,
1848 const SmallVectorImpl<SDValue> &OutVals,
1849 SDLoc dl, SelectionDAG &DAG) const {
1850 MachineFunction &MF = DAG.getMachineFunction();
1851 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1853 SmallVector<CCValAssign, 16> RVLocs;
1854 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1855 RVLocs, *DAG.getContext());
1856 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1859 SmallVector<SDValue, 6> RetOps;
1860 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1861 // Operand #1 = Bytes To Pop
1862 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1865 // Copy the result values into the output registers.
1866 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1867 CCValAssign &VA = RVLocs[i];
1868 assert(VA.isRegLoc() && "Can only return in registers!");
1869 SDValue ValToCopy = OutVals[i];
1870 EVT ValVT = ValToCopy.getValueType();
1872 // Promote values to the appropriate types
1873 if (VA.getLocInfo() == CCValAssign::SExt)
1874 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1875 else if (VA.getLocInfo() == CCValAssign::ZExt)
1876 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1877 else if (VA.getLocInfo() == CCValAssign::AExt)
1878 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1879 else if (VA.getLocInfo() == CCValAssign::BCvt)
1880 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1882 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1883 "Unexpected FP-extend for return value.");
1885 // If this is x86-64, and we disabled SSE, we can't return FP values,
1886 // or SSE or MMX vectors.
1887 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1888 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1889 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1890 report_fatal_error("SSE register return with SSE disabled");
1892 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1893 // llvm-gcc has never done it right and no one has noticed, so this
1894 // should be OK for now.
1895 if (ValVT == MVT::f64 &&
1896 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1897 report_fatal_error("SSE2 register return with SSE2 disabled");
1899 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1900 // the RET instruction and handled by the FP Stackifier.
1901 if (VA.getLocReg() == X86::ST0 ||
1902 VA.getLocReg() == X86::ST1) {
1903 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1904 // change the value to the FP stack register class.
1905 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1906 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1907 RetOps.push_back(ValToCopy);
1908 // Don't emit a copytoreg.
1912 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1913 // which is returned in RAX / RDX.
1914 if (Subtarget->is64Bit()) {
1915 if (ValVT == MVT::x86mmx) {
1916 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1917 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1918 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1920 // If we don't have SSE2 available, convert to v4f32 so the generated
1921 // register is legal.
1922 if (!Subtarget->hasSSE2())
1923 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1928 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1929 Flag = Chain.getValue(1);
1930 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1933 // The x86-64 ABIs require that for returning structs by value we copy
1934 // the sret argument into %rax/%eax (depending on ABI) for the return.
1935 // Win32 requires us to put the sret argument to %eax as well.
1936 // We saved the argument into a virtual register in the entry block,
1937 // so now we copy the value out and into %rax/%eax.
1938 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1939 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1940 MachineFunction &MF = DAG.getMachineFunction();
1941 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1942 unsigned Reg = FuncInfo->getSRetReturnReg();
1944 "SRetReturnReg should have been set in LowerFormalArguments().");
1945 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1948 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1949 X86::RAX : X86::EAX;
1950 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1951 Flag = Chain.getValue(1);
1953 // RAX/EAX now acts like a return value.
1954 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1957 RetOps[0] = Chain; // Update chain.
1959 // Add the flag if we have it.
1961 RetOps.push_back(Flag);
1963 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1966 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1967 if (N->getNumValues() != 1)
1969 if (!N->hasNUsesOfValue(1, 0))
1972 SDValue TCChain = Chain;
1973 SDNode *Copy = *N->use_begin();
1974 if (Copy->getOpcode() == ISD::CopyToReg) {
1975 // If the copy has a glue operand, we conservatively assume it isn't safe to
1976 // perform a tail call.
1977 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1979 TCChain = Copy->getOperand(0);
1980 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1983 bool HasRet = false;
1984 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1986 if (UI->getOpcode() != X86ISD::RET_FLAG)
1999 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2000 ISD::NodeType ExtendKind) const {
2002 // TODO: Is this also valid on 32-bit?
2003 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2004 ReturnMVT = MVT::i8;
2006 ReturnMVT = MVT::i32;
2008 MVT MinVT = getRegisterType(ReturnMVT);
2009 return VT.bitsLT(MinVT) ? MinVT : VT;
2012 /// LowerCallResult - Lower the result values of a call into the
2013 /// appropriate copies out of appropriate physical registers.
2016 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2017 CallingConv::ID CallConv, bool isVarArg,
2018 const SmallVectorImpl<ISD::InputArg> &Ins,
2019 SDLoc dl, SelectionDAG &DAG,
2020 SmallVectorImpl<SDValue> &InVals) const {
2022 // Assign locations to each value returned by this call.
2023 SmallVector<CCValAssign, 16> RVLocs;
2024 bool Is64Bit = Subtarget->is64Bit();
2025 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2026 DAG.getTarget(), RVLocs, *DAG.getContext());
2027 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2029 // Copy all of the result registers out of their specified physreg.
2030 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2031 CCValAssign &VA = RVLocs[i];
2032 EVT CopyVT = VA.getValVT();
2034 // If this is x86-64, and we disabled SSE, we can't return FP values
2035 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2036 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2037 report_fatal_error("SSE register return with SSE disabled");
2042 // If this is a call to a function that returns an fp value on the floating
2043 // point stack, we must guarantee the value is popped from the stack, so
2044 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2045 // if the return value is not used. We use the FpPOP_RETVAL instruction
2047 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2048 // If we prefer to use the value in xmm registers, copy it out as f80 and
2049 // use a truncate to move it from fp stack reg to xmm reg.
2050 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2051 SDValue Ops[] = { Chain, InFlag };
2052 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2053 MVT::Other, MVT::Glue, Ops), 1);
2054 Val = Chain.getValue(0);
2056 // Round the f80 to the right size, which also moves it to the appropriate
2058 if (CopyVT != VA.getValVT())
2059 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2060 // This truncation won't change the value.
2061 DAG.getIntPtrConstant(1));
2063 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2064 CopyVT, InFlag).getValue(1);
2065 Val = Chain.getValue(0);
2067 InFlag = Chain.getValue(2);
2068 InVals.push_back(Val);
2074 //===----------------------------------------------------------------------===//
2075 // C & StdCall & Fast Calling Convention implementation
2076 //===----------------------------------------------------------------------===//
2077 // StdCall calling convention seems to be standard for many Windows' API
2078 // routines and around. It differs from C calling convention just a little:
2079 // callee should clean up the stack, not caller. Symbols should be also
2080 // decorated in some fancy way :) It doesn't support any vector arguments.
2081 // For info on fast calling convention see Fast Calling Convention (tail call)
2082 // implementation LowerX86_32FastCCCallTo.
2084 /// CallIsStructReturn - Determines whether a call uses struct return
2086 enum StructReturnType {
2091 static StructReturnType
2092 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2094 return NotStructReturn;
2096 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2097 if (!Flags.isSRet())
2098 return NotStructReturn;
2099 if (Flags.isInReg())
2100 return RegStructReturn;
2101 return StackStructReturn;
2104 /// ArgsAreStructReturn - Determines whether a function uses struct
2105 /// return semantics.
2106 static StructReturnType
2107 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2109 return NotStructReturn;
2111 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2112 if (!Flags.isSRet())
2113 return NotStructReturn;
2114 if (Flags.isInReg())
2115 return RegStructReturn;
2116 return StackStructReturn;
2119 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2120 /// by "Src" to address "Dst" with size and alignment information specified by
2121 /// the specific parameter attribute. The copy will be passed as a byval
2122 /// function parameter.
2124 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2125 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2127 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2129 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2130 /*isVolatile*/false, /*AlwaysInline=*/true,
2131 MachinePointerInfo(), MachinePointerInfo());
2134 /// IsTailCallConvention - Return true if the calling convention is one that
2135 /// supports tail call optimization.
2136 static bool IsTailCallConvention(CallingConv::ID CC) {
2137 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2138 CC == CallingConv::HiPE);
2141 /// \brief Return true if the calling convention is a C calling convention.
2142 static bool IsCCallConvention(CallingConv::ID CC) {
2143 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2144 CC == CallingConv::X86_64_SysV);
2147 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2148 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2152 CallingConv::ID CalleeCC = CS.getCallingConv();
2153 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2159 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2160 /// a tailcall target by changing its ABI.
2161 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2162 bool GuaranteedTailCallOpt) {
2163 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2167 X86TargetLowering::LowerMemArgument(SDValue Chain,
2168 CallingConv::ID CallConv,
2169 const SmallVectorImpl<ISD::InputArg> &Ins,
2170 SDLoc dl, SelectionDAG &DAG,
2171 const CCValAssign &VA,
2172 MachineFrameInfo *MFI,
2174 // Create the nodes corresponding to a load from this parameter slot.
2175 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2176 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2177 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2178 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2181 // If value is passed by pointer we have address passed instead of the value
2183 if (VA.getLocInfo() == CCValAssign::Indirect)
2184 ValVT = VA.getLocVT();
2186 ValVT = VA.getValVT();
2188 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2189 // changed with more analysis.
2190 // In case of tail call optimization mark all arguments mutable. Since they
2191 // could be overwritten by lowering of arguments in case of a tail call.
2192 if (Flags.isByVal()) {
2193 unsigned Bytes = Flags.getByValSize();
2194 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2195 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2196 return DAG.getFrameIndex(FI, getPointerTy());
2198 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2199 VA.getLocMemOffset(), isImmutable);
2200 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2201 return DAG.getLoad(ValVT, dl, Chain, FIN,
2202 MachinePointerInfo::getFixedStack(FI),
2203 false, false, false, 0);
2208 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2209 CallingConv::ID CallConv,
2211 const SmallVectorImpl<ISD::InputArg> &Ins,
2214 SmallVectorImpl<SDValue> &InVals)
2216 MachineFunction &MF = DAG.getMachineFunction();
2217 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2219 const Function* Fn = MF.getFunction();
2220 if (Fn->hasExternalLinkage() &&
2221 Subtarget->isTargetCygMing() &&
2222 Fn->getName() == "main")
2223 FuncInfo->setForceFramePointer(true);
2225 MachineFrameInfo *MFI = MF.getFrameInfo();
2226 bool Is64Bit = Subtarget->is64Bit();
2227 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2229 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2230 "Var args not supported with calling convention fastcc, ghc or hipe");
2232 // Assign locations to all of the incoming arguments.
2233 SmallVector<CCValAssign, 16> ArgLocs;
2234 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2235 ArgLocs, *DAG.getContext());
2237 // Allocate shadow area for Win64
2239 CCInfo.AllocateStack(32, 8);
2241 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2243 unsigned LastVal = ~0U;
2245 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2246 CCValAssign &VA = ArgLocs[i];
2247 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2249 assert(VA.getValNo() != LastVal &&
2250 "Don't support value assigned to multiple locs yet");
2252 LastVal = VA.getValNo();
2254 if (VA.isRegLoc()) {
2255 EVT RegVT = VA.getLocVT();
2256 const TargetRegisterClass *RC;
2257 if (RegVT == MVT::i32)
2258 RC = &X86::GR32RegClass;
2259 else if (Is64Bit && RegVT == MVT::i64)
2260 RC = &X86::GR64RegClass;
2261 else if (RegVT == MVT::f32)
2262 RC = &X86::FR32RegClass;
2263 else if (RegVT == MVT::f64)
2264 RC = &X86::FR64RegClass;
2265 else if (RegVT.is512BitVector())
2266 RC = &X86::VR512RegClass;
2267 else if (RegVT.is256BitVector())
2268 RC = &X86::VR256RegClass;
2269 else if (RegVT.is128BitVector())
2270 RC = &X86::VR128RegClass;
2271 else if (RegVT == MVT::x86mmx)
2272 RC = &X86::VR64RegClass;
2273 else if (RegVT == MVT::i1)
2274 RC = &X86::VK1RegClass;
2275 else if (RegVT == MVT::v8i1)
2276 RC = &X86::VK8RegClass;
2277 else if (RegVT == MVT::v16i1)
2278 RC = &X86::VK16RegClass;
2280 llvm_unreachable("Unknown argument type!");
2282 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2283 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2285 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2286 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2288 if (VA.getLocInfo() == CCValAssign::SExt)
2289 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2290 DAG.getValueType(VA.getValVT()));
2291 else if (VA.getLocInfo() == CCValAssign::ZExt)
2292 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2293 DAG.getValueType(VA.getValVT()));
2294 else if (VA.getLocInfo() == CCValAssign::BCvt)
2295 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2297 if (VA.isExtInLoc()) {
2298 // Handle MMX values passed in XMM regs.
2299 if (RegVT.isVector())
2300 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2302 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2305 assert(VA.isMemLoc());
2306 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2309 // If value is passed via pointer - do a load.
2310 if (VA.getLocInfo() == CCValAssign::Indirect)
2311 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2312 MachinePointerInfo(), false, false, false, 0);
2314 InVals.push_back(ArgValue);
2317 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2318 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2319 // The x86-64 ABIs require that for returning structs by value we copy
2320 // the sret argument into %rax/%eax (depending on ABI) for the return.
2321 // Win32 requires us to put the sret argument to %eax as well.
2322 // Save the argument into a virtual register so that we can access it
2323 // from the return points.
2324 if (Ins[i].Flags.isSRet()) {
2325 unsigned Reg = FuncInfo->getSRetReturnReg();
2327 MVT PtrTy = getPointerTy();
2328 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2329 FuncInfo->setSRetReturnReg(Reg);
2331 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2332 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2338 unsigned StackSize = CCInfo.getNextStackOffset();
2339 // Align stack specially for tail calls.
2340 if (FuncIsMadeTailCallSafe(CallConv,
2341 MF.getTarget().Options.GuaranteedTailCallOpt))
2342 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2344 // If the function takes variable number of arguments, make a frame index for
2345 // the start of the first vararg value... for expansion of llvm.va_start.
2347 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2348 CallConv != CallingConv::X86_ThisCall)) {
2349 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2352 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2354 // FIXME: We should really autogenerate these arrays
2355 static const MCPhysReg GPR64ArgRegsWin64[] = {
2356 X86::RCX, X86::RDX, X86::R8, X86::R9
2358 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2359 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2361 static const MCPhysReg XMMArgRegs64Bit[] = {
2362 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2363 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2365 const MCPhysReg *GPR64ArgRegs;
2366 unsigned NumXMMRegs = 0;
2369 // The XMM registers which might contain var arg parameters are shadowed
2370 // in their paired GPR. So we only need to save the GPR to their home
2372 TotalNumIntRegs = 4;
2373 GPR64ArgRegs = GPR64ArgRegsWin64;
2375 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2376 GPR64ArgRegs = GPR64ArgRegs64Bit;
2378 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2381 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2384 bool NoImplicitFloatOps = Fn->getAttributes().
2385 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2386 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2387 "SSE register cannot be used when SSE is disabled!");
2388 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2389 NoImplicitFloatOps) &&
2390 "SSE register cannot be used when SSE is disabled!");
2391 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2392 !Subtarget->hasSSE1())
2393 // Kernel mode asks for SSE to be disabled, so don't push them
2395 TotalNumXMMRegs = 0;
2398 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2399 // Get to the caller-allocated home save location. Add 8 to account
2400 // for the return address.
2401 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2402 FuncInfo->setRegSaveFrameIndex(
2403 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2404 // Fixup to set vararg frame on shadow area (4 x i64).
2406 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2408 // For X86-64, if there are vararg parameters that are passed via
2409 // registers, then we must store them to their spots on the stack so
2410 // they may be loaded by deferencing the result of va_next.
2411 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2412 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2413 FuncInfo->setRegSaveFrameIndex(
2414 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2418 // Store the integer parameter registers.
2419 SmallVector<SDValue, 8> MemOps;
2420 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2422 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2423 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2424 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2425 DAG.getIntPtrConstant(Offset));
2426 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2427 &X86::GR64RegClass);
2428 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2430 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2431 MachinePointerInfo::getFixedStack(
2432 FuncInfo->getRegSaveFrameIndex(), Offset),
2434 MemOps.push_back(Store);
2438 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2439 // Now store the XMM (fp + vector) parameter registers.
2440 SmallVector<SDValue, 11> SaveXMMOps;
2441 SaveXMMOps.push_back(Chain);
2443 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2444 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2445 SaveXMMOps.push_back(ALVal);
2447 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2448 FuncInfo->getRegSaveFrameIndex()));
2449 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2450 FuncInfo->getVarArgsFPOffset()));
2452 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2453 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2454 &X86::VR128RegClass);
2455 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2456 SaveXMMOps.push_back(Val);
2458 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2459 MVT::Other, SaveXMMOps));
2462 if (!MemOps.empty())
2463 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2467 // Some CCs need callee pop.
2468 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2469 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2470 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2472 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2473 // If this is an sret function, the return should pop the hidden pointer.
2474 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2475 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2476 argsAreStructReturn(Ins) == StackStructReturn)
2477 FuncInfo->setBytesToPopOnReturn(4);
2481 // RegSaveFrameIndex is X86-64 only.
2482 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2483 if (CallConv == CallingConv::X86_FastCall ||
2484 CallConv == CallingConv::X86_ThisCall)
2485 // fastcc functions can't have varargs.
2486 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2489 FuncInfo->setArgumentStackSize(StackSize);
2495 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2496 SDValue StackPtr, SDValue Arg,
2497 SDLoc dl, SelectionDAG &DAG,
2498 const CCValAssign &VA,
2499 ISD::ArgFlagsTy Flags) const {
2500 unsigned LocMemOffset = VA.getLocMemOffset();
2501 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2502 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2503 if (Flags.isByVal())
2504 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2506 return DAG.getStore(Chain, dl, Arg, PtrOff,
2507 MachinePointerInfo::getStack(LocMemOffset),
2511 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2512 /// optimization is performed and it is required.
2514 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2515 SDValue &OutRetAddr, SDValue Chain,
2516 bool IsTailCall, bool Is64Bit,
2517 int FPDiff, SDLoc dl) const {
2518 // Adjust the Return address stack slot.
2519 EVT VT = getPointerTy();
2520 OutRetAddr = getReturnAddressFrameIndex(DAG);
2522 // Load the "old" Return address.
2523 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2524 false, false, false, 0);
2525 return SDValue(OutRetAddr.getNode(), 1);
2528 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2529 /// optimization is performed and it is required (FPDiff!=0).
2530 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2531 SDValue Chain, SDValue RetAddrFrIdx,
2532 EVT PtrVT, unsigned SlotSize,
2533 int FPDiff, SDLoc dl) {
2534 // Store the return address to the appropriate stack slot.
2535 if (!FPDiff) return Chain;
2536 // Calculate the new stack slot for the return address.
2537 int NewReturnAddrFI =
2538 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2540 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2541 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2542 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2548 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2549 SmallVectorImpl<SDValue> &InVals) const {
2550 SelectionDAG &DAG = CLI.DAG;
2552 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2553 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2554 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2555 SDValue Chain = CLI.Chain;
2556 SDValue Callee = CLI.Callee;
2557 CallingConv::ID CallConv = CLI.CallConv;
2558 bool &isTailCall = CLI.IsTailCall;
2559 bool isVarArg = CLI.IsVarArg;
2561 MachineFunction &MF = DAG.getMachineFunction();
2562 bool Is64Bit = Subtarget->is64Bit();
2563 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2564 StructReturnType SR = callIsStructReturn(Outs);
2565 bool IsSibcall = false;
2567 if (MF.getTarget().Options.DisableTailCalls)
2570 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2572 // Force this to be a tail call. The verifier rules are enough to ensure
2573 // that we can lower this successfully without moving the return address
2576 } else if (isTailCall) {
2577 // Check if it's really possible to do a tail call.
2578 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2579 isVarArg, SR != NotStructReturn,
2580 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2581 Outs, OutVals, Ins, DAG);
2583 // Sibcalls are automatically detected tailcalls which do not require
2585 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2592 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2593 "Var args not supported with calling convention fastcc, ghc or hipe");
2595 // Analyze operands of the call, assigning locations to each operand.
2596 SmallVector<CCValAssign, 16> ArgLocs;
2597 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2598 ArgLocs, *DAG.getContext());
2600 // Allocate shadow area for Win64
2602 CCInfo.AllocateStack(32, 8);
2604 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2606 // Get a count of how many bytes are to be pushed on the stack.
2607 unsigned NumBytes = CCInfo.getNextStackOffset();
2609 // This is a sibcall. The memory operands are available in caller's
2610 // own caller's stack.
2612 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2613 IsTailCallConvention(CallConv))
2614 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2617 if (isTailCall && !IsSibcall && !IsMustTail) {
2618 // Lower arguments at fp - stackoffset + fpdiff.
2619 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2620 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2622 FPDiff = NumBytesCallerPushed - NumBytes;
2624 // Set the delta of movement of the returnaddr stackslot.
2625 // But only set if delta is greater than previous delta.
2626 if (FPDiff < X86Info->getTCReturnAddrDelta())
2627 X86Info->setTCReturnAddrDelta(FPDiff);
2630 unsigned NumBytesToPush = NumBytes;
2631 unsigned NumBytesToPop = NumBytes;
2633 // If we have an inalloca argument, all stack space has already been allocated
2634 // for us and be right at the top of the stack. We don't support multiple
2635 // arguments passed in memory when using inalloca.
2636 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2638 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2639 "an inalloca argument must be the only memory argument");
2643 Chain = DAG.getCALLSEQ_START(
2644 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2646 SDValue RetAddrFrIdx;
2647 // Load return address for tail calls.
2648 if (isTailCall && FPDiff)
2649 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2650 Is64Bit, FPDiff, dl);
2652 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2653 SmallVector<SDValue, 8> MemOpChains;
2656 // Walk the register/memloc assignments, inserting copies/loads. In the case
2657 // of tail call optimization arguments are handle later.
2658 const X86RegisterInfo *RegInfo =
2659 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2660 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2661 // Skip inalloca arguments, they have already been written.
2662 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2663 if (Flags.isInAlloca())
2666 CCValAssign &VA = ArgLocs[i];
2667 EVT RegVT = VA.getLocVT();
2668 SDValue Arg = OutVals[i];
2669 bool isByVal = Flags.isByVal();
2671 // Promote the value if needed.
2672 switch (VA.getLocInfo()) {
2673 default: llvm_unreachable("Unknown loc info!");
2674 case CCValAssign::Full: break;
2675 case CCValAssign::SExt:
2676 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2678 case CCValAssign::ZExt:
2679 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2681 case CCValAssign::AExt:
2682 if (RegVT.is128BitVector()) {
2683 // Special case: passing MMX values in XMM registers.
2684 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2685 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2686 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2688 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2690 case CCValAssign::BCvt:
2691 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2693 case CCValAssign::Indirect: {
2694 // Store the argument.
2695 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2696 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2697 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2698 MachinePointerInfo::getFixedStack(FI),
2705 if (VA.isRegLoc()) {
2706 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2707 if (isVarArg && IsWin64) {
2708 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2709 // shadow reg if callee is a varargs function.
2710 unsigned ShadowReg = 0;
2711 switch (VA.getLocReg()) {
2712 case X86::XMM0: ShadowReg = X86::RCX; break;
2713 case X86::XMM1: ShadowReg = X86::RDX; break;
2714 case X86::XMM2: ShadowReg = X86::R8; break;
2715 case X86::XMM3: ShadowReg = X86::R9; break;
2718 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2720 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2721 assert(VA.isMemLoc());
2722 if (!StackPtr.getNode())
2723 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2725 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2726 dl, DAG, VA, Flags));
2730 if (!MemOpChains.empty())
2731 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2733 if (Subtarget->isPICStyleGOT()) {
2734 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2737 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2738 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2740 // If we are tail calling and generating PIC/GOT style code load the
2741 // address of the callee into ECX. The value in ecx is used as target of
2742 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2743 // for tail calls on PIC/GOT architectures. Normally we would just put the
2744 // address of GOT into ebx and then call target@PLT. But for tail calls
2745 // ebx would be restored (since ebx is callee saved) before jumping to the
2748 // Note: The actual moving to ECX is done further down.
2749 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2750 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2751 !G->getGlobal()->hasProtectedVisibility())
2752 Callee = LowerGlobalAddress(Callee, DAG);
2753 else if (isa<ExternalSymbolSDNode>(Callee))
2754 Callee = LowerExternalSymbol(Callee, DAG);
2758 if (Is64Bit && isVarArg && !IsWin64) {
2759 // From AMD64 ABI document:
2760 // For calls that may call functions that use varargs or stdargs
2761 // (prototype-less calls or calls to functions containing ellipsis (...) in
2762 // the declaration) %al is used as hidden argument to specify the number
2763 // of SSE registers used. The contents of %al do not need to match exactly
2764 // the number of registers, but must be an ubound on the number of SSE
2765 // registers used and is in the range 0 - 8 inclusive.
2767 // Count the number of XMM registers allocated.
2768 static const MCPhysReg XMMArgRegs[] = {
2769 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2770 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2772 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2773 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2774 && "SSE registers cannot be used when SSE is disabled");
2776 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2777 DAG.getConstant(NumXMMRegs, MVT::i8)));
2780 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2781 // don't need this because the eligibility check rejects calls that require
2782 // shuffling arguments passed in memory.
2783 if (!IsSibcall && isTailCall) {
2784 // Force all the incoming stack arguments to be loaded from the stack
2785 // before any new outgoing arguments are stored to the stack, because the
2786 // outgoing stack slots may alias the incoming argument stack slots, and
2787 // the alias isn't otherwise explicit. This is slightly more conservative
2788 // than necessary, because it means that each store effectively depends
2789 // on every argument instead of just those arguments it would clobber.
2790 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2792 SmallVector<SDValue, 8> MemOpChains2;
2795 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2796 CCValAssign &VA = ArgLocs[i];
2799 assert(VA.isMemLoc());
2800 SDValue Arg = OutVals[i];
2801 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2802 // Skip inalloca arguments. They don't require any work.
2803 if (Flags.isInAlloca())
2805 // Create frame index.
2806 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2807 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2808 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2809 FIN = DAG.getFrameIndex(FI, getPointerTy());
2811 if (Flags.isByVal()) {
2812 // Copy relative to framepointer.
2813 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2814 if (!StackPtr.getNode())
2815 StackPtr = DAG.getCopyFromReg(Chain, dl,
2816 RegInfo->getStackRegister(),
2818 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2820 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2824 // Store relative to framepointer.
2825 MemOpChains2.push_back(
2826 DAG.getStore(ArgChain, dl, Arg, FIN,
2827 MachinePointerInfo::getFixedStack(FI),
2832 if (!MemOpChains2.empty())
2833 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2835 // Store the return address to the appropriate stack slot.
2836 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2837 getPointerTy(), RegInfo->getSlotSize(),
2841 // Build a sequence of copy-to-reg nodes chained together with token chain
2842 // and flag operands which copy the outgoing args into registers.
2844 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2845 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2846 RegsToPass[i].second, InFlag);
2847 InFlag = Chain.getValue(1);
2850 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2851 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2852 // In the 64-bit large code model, we have to make all calls
2853 // through a register, since the call instruction's 32-bit
2854 // pc-relative offset may not be large enough to hold the whole
2856 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2857 // If the callee is a GlobalAddress node (quite common, every direct call
2858 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2861 // We should use extra load for direct calls to dllimported functions in
2863 const GlobalValue *GV = G->getGlobal();
2864 if (!GV->hasDLLImportStorageClass()) {
2865 unsigned char OpFlags = 0;
2866 bool ExtraLoad = false;
2867 unsigned WrapperKind = ISD::DELETED_NODE;
2869 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2870 // external symbols most go through the PLT in PIC mode. If the symbol
2871 // has hidden or protected visibility, or if it is static or local, then
2872 // we don't need to use the PLT - we can directly call it.
2873 if (Subtarget->isTargetELF() &&
2874 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2875 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2876 OpFlags = X86II::MO_PLT;
2877 } else if (Subtarget->isPICStyleStubAny() &&
2878 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2879 (!Subtarget->getTargetTriple().isMacOSX() ||
2880 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2881 // PC-relative references to external symbols should go through $stub,
2882 // unless we're building with the leopard linker or later, which
2883 // automatically synthesizes these stubs.
2884 OpFlags = X86II::MO_DARWIN_STUB;
2885 } else if (Subtarget->isPICStyleRIPRel() &&
2886 isa<Function>(GV) &&
2887 cast<Function>(GV)->getAttributes().
2888 hasAttribute(AttributeSet::FunctionIndex,
2889 Attribute::NonLazyBind)) {
2890 // If the function is marked as non-lazy, generate an indirect call
2891 // which loads from the GOT directly. This avoids runtime overhead
2892 // at the cost of eager binding (and one extra byte of encoding).
2893 OpFlags = X86II::MO_GOTPCREL;
2894 WrapperKind = X86ISD::WrapperRIP;
2898 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2899 G->getOffset(), OpFlags);
2901 // Add a wrapper if needed.
2902 if (WrapperKind != ISD::DELETED_NODE)
2903 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2904 // Add extra indirection if needed.
2906 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2907 MachinePointerInfo::getGOT(),
2908 false, false, false, 0);
2910 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2911 unsigned char OpFlags = 0;
2913 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2914 // external symbols should go through the PLT.
2915 if (Subtarget->isTargetELF() &&
2916 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2917 OpFlags = X86II::MO_PLT;
2918 } else if (Subtarget->isPICStyleStubAny() &&
2919 (!Subtarget->getTargetTriple().isMacOSX() ||
2920 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2921 // PC-relative references to external symbols should go through $stub,
2922 // unless we're building with the leopard linker or later, which
2923 // automatically synthesizes these stubs.
2924 OpFlags = X86II::MO_DARWIN_STUB;
2927 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2931 // Returns a chain & a flag for retval copy to use.
2932 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2933 SmallVector<SDValue, 8> Ops;
2935 if (!IsSibcall && isTailCall) {
2936 Chain = DAG.getCALLSEQ_END(Chain,
2937 DAG.getIntPtrConstant(NumBytesToPop, true),
2938 DAG.getIntPtrConstant(0, true), InFlag, dl);
2939 InFlag = Chain.getValue(1);
2942 Ops.push_back(Chain);
2943 Ops.push_back(Callee);
2946 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2948 // Add argument registers to the end of the list so that they are known live
2950 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2951 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2952 RegsToPass[i].second.getValueType()));
2954 // Add a register mask operand representing the call-preserved registers.
2955 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2956 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2957 assert(Mask && "Missing call preserved mask for calling convention");
2958 Ops.push_back(DAG.getRegisterMask(Mask));
2960 if (InFlag.getNode())
2961 Ops.push_back(InFlag);
2965 //// If this is the first return lowered for this function, add the regs
2966 //// to the liveout set for the function.
2967 // This isn't right, although it's probably harmless on x86; liveouts
2968 // should be computed from returns not tail calls. Consider a void
2969 // function making a tail call to a function returning int.
2970 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2973 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2974 InFlag = Chain.getValue(1);
2976 // Create the CALLSEQ_END node.
2977 unsigned NumBytesForCalleeToPop;
2978 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2979 DAG.getTarget().Options.GuaranteedTailCallOpt))
2980 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2981 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2982 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2983 SR == StackStructReturn)
2984 // If this is a call to a struct-return function, the callee
2985 // pops the hidden struct pointer, so we have to push it back.
2986 // This is common for Darwin/X86, Linux & Mingw32 targets.
2987 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2988 NumBytesForCalleeToPop = 4;
2990 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2992 // Returns a flag for retval copy to use.
2994 Chain = DAG.getCALLSEQ_END(Chain,
2995 DAG.getIntPtrConstant(NumBytesToPop, true),
2996 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2999 InFlag = Chain.getValue(1);
3002 // Handle result values, copying them out of physregs into vregs that we
3004 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3005 Ins, dl, DAG, InVals);
3008 //===----------------------------------------------------------------------===//
3009 // Fast Calling Convention (tail call) implementation
3010 //===----------------------------------------------------------------------===//
3012 // Like std call, callee cleans arguments, convention except that ECX is
3013 // reserved for storing the tail called function address. Only 2 registers are
3014 // free for argument passing (inreg). Tail call optimization is performed
3016 // * tailcallopt is enabled
3017 // * caller/callee are fastcc
3018 // On X86_64 architecture with GOT-style position independent code only local
3019 // (within module) calls are supported at the moment.
3020 // To keep the stack aligned according to platform abi the function
3021 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3022 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3023 // If a tail called function callee has more arguments than the caller the
3024 // caller needs to make sure that there is room to move the RETADDR to. This is
3025 // achieved by reserving an area the size of the argument delta right after the
3026 // original REtADDR, but before the saved framepointer or the spilled registers
3027 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3039 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3040 /// for a 16 byte align requirement.
3042 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3043 SelectionDAG& DAG) const {
3044 MachineFunction &MF = DAG.getMachineFunction();
3045 const TargetMachine &TM = MF.getTarget();
3046 const X86RegisterInfo *RegInfo =
3047 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3048 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3049 unsigned StackAlignment = TFI.getStackAlignment();
3050 uint64_t AlignMask = StackAlignment - 1;
3051 int64_t Offset = StackSize;
3052 unsigned SlotSize = RegInfo->getSlotSize();
3053 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3054 // Number smaller than 12 so just add the difference.
3055 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3057 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3058 Offset = ((~AlignMask) & Offset) + StackAlignment +
3059 (StackAlignment-SlotSize);
3064 /// MatchingStackOffset - Return true if the given stack call argument is
3065 /// already available in the same position (relatively) of the caller's
3066 /// incoming argument stack.
3068 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3069 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3070 const X86InstrInfo *TII) {
3071 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3073 if (Arg.getOpcode() == ISD::CopyFromReg) {
3074 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3075 if (!TargetRegisterInfo::isVirtualRegister(VR))
3077 MachineInstr *Def = MRI->getVRegDef(VR);
3080 if (!Flags.isByVal()) {
3081 if (!TII->isLoadFromStackSlot(Def, FI))
3084 unsigned Opcode = Def->getOpcode();
3085 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3086 Def->getOperand(1).isFI()) {
3087 FI = Def->getOperand(1).getIndex();
3088 Bytes = Flags.getByValSize();
3092 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3093 if (Flags.isByVal())
3094 // ByVal argument is passed in as a pointer but it's now being
3095 // dereferenced. e.g.
3096 // define @foo(%struct.X* %A) {
3097 // tail call @bar(%struct.X* byval %A)
3100 SDValue Ptr = Ld->getBasePtr();
3101 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3104 FI = FINode->getIndex();
3105 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3106 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3107 FI = FINode->getIndex();
3108 Bytes = Flags.getByValSize();
3112 assert(FI != INT_MAX);
3113 if (!MFI->isFixedObjectIndex(FI))
3115 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3118 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3119 /// for tail call optimization. Targets which want to do tail call
3120 /// optimization should implement this function.
3122 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3123 CallingConv::ID CalleeCC,
3125 bool isCalleeStructRet,
3126 bool isCallerStructRet,
3128 const SmallVectorImpl<ISD::OutputArg> &Outs,
3129 const SmallVectorImpl<SDValue> &OutVals,
3130 const SmallVectorImpl<ISD::InputArg> &Ins,
3131 SelectionDAG &DAG) const {
3132 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3135 // If -tailcallopt is specified, make fastcc functions tail-callable.
3136 const MachineFunction &MF = DAG.getMachineFunction();
3137 const Function *CallerF = MF.getFunction();
3139 // If the function return type is x86_fp80 and the callee return type is not,
3140 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3141 // perform a tailcall optimization here.
3142 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3145 CallingConv::ID CallerCC = CallerF->getCallingConv();
3146 bool CCMatch = CallerCC == CalleeCC;
3147 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3148 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3150 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3151 if (IsTailCallConvention(CalleeCC) && CCMatch)
3156 // Look for obvious safe cases to perform tail call optimization that do not
3157 // require ABI changes. This is what gcc calls sibcall.
3159 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3160 // emit a special epilogue.
3161 const X86RegisterInfo *RegInfo =
3162 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3163 if (RegInfo->needsStackRealignment(MF))
3166 // Also avoid sibcall optimization if either caller or callee uses struct
3167 // return semantics.
3168 if (isCalleeStructRet || isCallerStructRet)
3171 // An stdcall/thiscall caller is expected to clean up its arguments; the
3172 // callee isn't going to do that.
3173 // FIXME: this is more restrictive than needed. We could produce a tailcall
3174 // when the stack adjustment matches. For example, with a thiscall that takes
3175 // only one argument.
3176 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3177 CallerCC == CallingConv::X86_ThisCall))
3180 // Do not sibcall optimize vararg calls unless all arguments are passed via
3182 if (isVarArg && !Outs.empty()) {
3184 // Optimizing for varargs on Win64 is unlikely to be safe without
3185 // additional testing.
3186 if (IsCalleeWin64 || IsCallerWin64)
3189 SmallVector<CCValAssign, 16> ArgLocs;
3190 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3191 DAG.getTarget(), ArgLocs, *DAG.getContext());
3193 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3194 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3195 if (!ArgLocs[i].isRegLoc())
3199 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3200 // stack. Therefore, if it's not used by the call it is not safe to optimize
3201 // this into a sibcall.
3202 bool Unused = false;
3203 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3210 SmallVector<CCValAssign, 16> RVLocs;
3211 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3212 DAG.getTarget(), RVLocs, *DAG.getContext());
3213 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3214 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3215 CCValAssign &VA = RVLocs[i];
3216 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3221 // If the calling conventions do not match, then we'd better make sure the
3222 // results are returned in the same way as what the caller expects.
3224 SmallVector<CCValAssign, 16> RVLocs1;
3225 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3226 DAG.getTarget(), RVLocs1, *DAG.getContext());
3227 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3229 SmallVector<CCValAssign, 16> RVLocs2;
3230 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3231 DAG.getTarget(), RVLocs2, *DAG.getContext());
3232 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3234 if (RVLocs1.size() != RVLocs2.size())
3236 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3237 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3239 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3241 if (RVLocs1[i].isRegLoc()) {
3242 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3245 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3251 // If the callee takes no arguments then go on to check the results of the
3253 if (!Outs.empty()) {
3254 // Check if stack adjustment is needed. For now, do not do this if any
3255 // argument is passed on the stack.
3256 SmallVector<CCValAssign, 16> ArgLocs;
3257 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3258 DAG.getTarget(), ArgLocs, *DAG.getContext());
3260 // Allocate shadow area for Win64
3262 CCInfo.AllocateStack(32, 8);
3264 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3265 if (CCInfo.getNextStackOffset()) {
3266 MachineFunction &MF = DAG.getMachineFunction();
3267 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3270 // Check if the arguments are already laid out in the right way as
3271 // the caller's fixed stack objects.
3272 MachineFrameInfo *MFI = MF.getFrameInfo();
3273 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3274 const X86InstrInfo *TII =
3275 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3276 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3277 CCValAssign &VA = ArgLocs[i];
3278 SDValue Arg = OutVals[i];
3279 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3280 if (VA.getLocInfo() == CCValAssign::Indirect)
3282 if (!VA.isRegLoc()) {
3283 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3290 // If the tailcall address may be in a register, then make sure it's
3291 // possible to register allocate for it. In 32-bit, the call address can
3292 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3293 // callee-saved registers are restored. These happen to be the same
3294 // registers used to pass 'inreg' arguments so watch out for those.
3295 if (!Subtarget->is64Bit() &&
3296 ((!isa<GlobalAddressSDNode>(Callee) &&
3297 !isa<ExternalSymbolSDNode>(Callee)) ||
3298 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3299 unsigned NumInRegs = 0;
3300 // In PIC we need an extra register to formulate the address computation
3302 unsigned MaxInRegs =
3303 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3305 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3306 CCValAssign &VA = ArgLocs[i];
3309 unsigned Reg = VA.getLocReg();
3312 case X86::EAX: case X86::EDX: case X86::ECX:
3313 if (++NumInRegs == MaxInRegs)
3325 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3326 const TargetLibraryInfo *libInfo) const {
3327 return X86::createFastISel(funcInfo, libInfo);
3330 //===----------------------------------------------------------------------===//
3331 // Other Lowering Hooks
3332 //===----------------------------------------------------------------------===//
3334 static bool MayFoldLoad(SDValue Op) {
3335 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3338 static bool MayFoldIntoStore(SDValue Op) {
3339 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3342 static bool isTargetShuffle(unsigned Opcode) {
3344 default: return false;
3345 case X86ISD::PSHUFD:
3346 case X86ISD::PSHUFHW:
3347 case X86ISD::PSHUFLW:
3349 case X86ISD::PALIGNR:
3350 case X86ISD::MOVLHPS:
3351 case X86ISD::MOVLHPD:
3352 case X86ISD::MOVHLPS:
3353 case X86ISD::MOVLPS:
3354 case X86ISD::MOVLPD:
3355 case X86ISD::MOVSHDUP:
3356 case X86ISD::MOVSLDUP:
3357 case X86ISD::MOVDDUP:
3360 case X86ISD::UNPCKL:
3361 case X86ISD::UNPCKH:
3362 case X86ISD::VPERMILP:
3363 case X86ISD::VPERM2X128:
3364 case X86ISD::VPERMI:
3369 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3370 SDValue V1, SelectionDAG &DAG) {
3372 default: llvm_unreachable("Unknown x86 shuffle node");
3373 case X86ISD::MOVSHDUP:
3374 case X86ISD::MOVSLDUP:
3375 case X86ISD::MOVDDUP:
3376 return DAG.getNode(Opc, dl, VT, V1);
3380 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3381 SDValue V1, unsigned TargetMask,
3382 SelectionDAG &DAG) {
3384 default: llvm_unreachable("Unknown x86 shuffle node");
3385 case X86ISD::PSHUFD:
3386 case X86ISD::PSHUFHW:
3387 case X86ISD::PSHUFLW:
3388 case X86ISD::VPERMILP:
3389 case X86ISD::VPERMI:
3390 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3394 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3395 SDValue V1, SDValue V2, unsigned TargetMask,
3396 SelectionDAG &DAG) {
3398 default: llvm_unreachable("Unknown x86 shuffle node");
3399 case X86ISD::PALIGNR:
3401 case X86ISD::VPERM2X128:
3402 return DAG.getNode(Opc, dl, VT, V1, V2,
3403 DAG.getConstant(TargetMask, MVT::i8));
3407 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3408 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3410 default: llvm_unreachable("Unknown x86 shuffle node");
3411 case X86ISD::MOVLHPS:
3412 case X86ISD::MOVLHPD:
3413 case X86ISD::MOVHLPS:
3414 case X86ISD::MOVLPS:
3415 case X86ISD::MOVLPD:
3418 case X86ISD::UNPCKL:
3419 case X86ISD::UNPCKH:
3420 return DAG.getNode(Opc, dl, VT, V1, V2);
3424 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3425 MachineFunction &MF = DAG.getMachineFunction();
3426 const X86RegisterInfo *RegInfo =
3427 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3428 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3429 int ReturnAddrIndex = FuncInfo->getRAIndex();
3431 if (ReturnAddrIndex == 0) {
3432 // Set up a frame object for the return address.
3433 unsigned SlotSize = RegInfo->getSlotSize();
3434 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3437 FuncInfo->setRAIndex(ReturnAddrIndex);
3440 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3443 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3444 bool hasSymbolicDisplacement) {
3445 // Offset should fit into 32 bit immediate field.
3446 if (!isInt<32>(Offset))
3449 // If we don't have a symbolic displacement - we don't have any extra
3451 if (!hasSymbolicDisplacement)
3454 // FIXME: Some tweaks might be needed for medium code model.
3455 if (M != CodeModel::Small && M != CodeModel::Kernel)
3458 // For small code model we assume that latest object is 16MB before end of 31
3459 // bits boundary. We may also accept pretty large negative constants knowing
3460 // that all objects are in the positive half of address space.
3461 if (M == CodeModel::Small && Offset < 16*1024*1024)
3464 // For kernel code model we know that all object resist in the negative half
3465 // of 32bits address space. We may not accept negative offsets, since they may
3466 // be just off and we may accept pretty large positive ones.
3467 if (M == CodeModel::Kernel && Offset > 0)
3473 /// isCalleePop - Determines whether the callee is required to pop its
3474 /// own arguments. Callee pop is necessary to support tail calls.
3475 bool X86::isCalleePop(CallingConv::ID CallingConv,
3476 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3480 switch (CallingConv) {
3483 case CallingConv::X86_StdCall:
3485 case CallingConv::X86_FastCall:
3487 case CallingConv::X86_ThisCall:
3489 case CallingConv::Fast:
3491 case CallingConv::GHC:
3493 case CallingConv::HiPE:
3498 /// \brief Return true if the condition is an unsigned comparison operation.
3499 static bool isX86CCUnsigned(unsigned X86CC) {
3501 default: llvm_unreachable("Invalid integer condition!");
3502 case X86::COND_E: return true;
3503 case X86::COND_G: return false;
3504 case X86::COND_GE: return false;
3505 case X86::COND_L: return false;
3506 case X86::COND_LE: return false;
3507 case X86::COND_NE: return true;
3508 case X86::COND_B: return true;
3509 case X86::COND_A: return true;
3510 case X86::COND_BE: return true;
3511 case X86::COND_AE: return true;
3513 llvm_unreachable("covered switch fell through?!");
3516 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3517 /// specific condition code, returning the condition code and the LHS/RHS of the
3518 /// comparison to make.
3519 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3520 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3522 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3523 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3524 // X > -1 -> X == 0, jump !sign.
3525 RHS = DAG.getConstant(0, RHS.getValueType());
3526 return X86::COND_NS;
3528 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3529 // X < 0 -> X == 0, jump on sign.
3532 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3534 RHS = DAG.getConstant(0, RHS.getValueType());
3535 return X86::COND_LE;
3539 switch (SetCCOpcode) {
3540 default: llvm_unreachable("Invalid integer condition!");
3541 case ISD::SETEQ: return X86::COND_E;
3542 case ISD::SETGT: return X86::COND_G;
3543 case ISD::SETGE: return X86::COND_GE;
3544 case ISD::SETLT: return X86::COND_L;
3545 case ISD::SETLE: return X86::COND_LE;
3546 case ISD::SETNE: return X86::COND_NE;
3547 case ISD::SETULT: return X86::COND_B;
3548 case ISD::SETUGT: return X86::COND_A;
3549 case ISD::SETULE: return X86::COND_BE;
3550 case ISD::SETUGE: return X86::COND_AE;
3554 // First determine if it is required or is profitable to flip the operands.
3556 // If LHS is a foldable load, but RHS is not, flip the condition.
3557 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3558 !ISD::isNON_EXTLoad(RHS.getNode())) {
3559 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3560 std::swap(LHS, RHS);
3563 switch (SetCCOpcode) {
3569 std::swap(LHS, RHS);
3573 // On a floating point condition, the flags are set as follows:
3575 // 0 | 0 | 0 | X > Y
3576 // 0 | 0 | 1 | X < Y
3577 // 1 | 0 | 0 | X == Y
3578 // 1 | 1 | 1 | unordered
3579 switch (SetCCOpcode) {
3580 default: llvm_unreachable("Condcode should be pre-legalized away");
3582 case ISD::SETEQ: return X86::COND_E;
3583 case ISD::SETOLT: // flipped
3585 case ISD::SETGT: return X86::COND_A;
3586 case ISD::SETOLE: // flipped
3588 case ISD::SETGE: return X86::COND_AE;
3589 case ISD::SETUGT: // flipped
3591 case ISD::SETLT: return X86::COND_B;
3592 case ISD::SETUGE: // flipped
3594 case ISD::SETLE: return X86::COND_BE;
3596 case ISD::SETNE: return X86::COND_NE;
3597 case ISD::SETUO: return X86::COND_P;
3598 case ISD::SETO: return X86::COND_NP;
3600 case ISD::SETUNE: return X86::COND_INVALID;
3604 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3605 /// code. Current x86 isa includes the following FP cmov instructions:
3606 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3607 static bool hasFPCMov(unsigned X86CC) {
3623 /// isFPImmLegal - Returns true if the target can instruction select the
3624 /// specified FP immediate natively. If false, the legalizer will
3625 /// materialize the FP immediate as a load from a constant pool.
3626 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3627 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3628 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3634 /// \brief Returns true if it is beneficial to convert a load of a constant
3635 /// to just the constant itself.
3636 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3638 assert(Ty->isIntegerTy());
3640 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3641 if (BitSize == 0 || BitSize > 64)
3646 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3647 /// the specified range (L, H].
3648 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3649 return (Val < 0) || (Val >= Low && Val < Hi);
3652 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3653 /// specified value.
3654 static bool isUndefOrEqual(int Val, int CmpVal) {
3655 return (Val < 0 || Val == CmpVal);
3658 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3659 /// from position Pos and ending in Pos+Size, falls within the specified
3660 /// sequential range (L, L+Pos]. or is undef.
3661 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3662 unsigned Pos, unsigned Size, int Low) {
3663 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3664 if (!isUndefOrEqual(Mask[i], Low))
3669 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3670 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3671 /// the second operand.
3672 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3673 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3674 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3675 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3676 return (Mask[0] < 2 && Mask[1] < 2);
3680 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3681 /// is suitable for input to PSHUFHW.
3682 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3683 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3686 // Lower quadword copied in order or undef.
3687 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3690 // Upper quadword shuffled.
3691 for (unsigned i = 4; i != 8; ++i)
3692 if (!isUndefOrInRange(Mask[i], 4, 8))
3695 if (VT == MVT::v16i16) {
3696 // Lower quadword copied in order or undef.
3697 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3700 // Upper quadword shuffled.
3701 for (unsigned i = 12; i != 16; ++i)
3702 if (!isUndefOrInRange(Mask[i], 12, 16))
3709 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3710 /// is suitable for input to PSHUFLW.
3711 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3712 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3715 // Upper quadword copied in order.
3716 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3719 // Lower quadword shuffled.
3720 for (unsigned i = 0; i != 4; ++i)
3721 if (!isUndefOrInRange(Mask[i], 0, 4))
3724 if (VT == MVT::v16i16) {
3725 // Upper quadword copied in order.
3726 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3729 // Lower quadword shuffled.
3730 for (unsigned i = 8; i != 12; ++i)
3731 if (!isUndefOrInRange(Mask[i], 8, 12))
3738 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3739 /// is suitable for input to PALIGNR.
3740 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3741 const X86Subtarget *Subtarget) {
3742 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3743 (VT.is256BitVector() && !Subtarget->hasInt256()))
3746 unsigned NumElts = VT.getVectorNumElements();
3747 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3748 unsigned NumLaneElts = NumElts/NumLanes;
3750 // Do not handle 64-bit element shuffles with palignr.
3751 if (NumLaneElts == 2)
3754 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3756 for (i = 0; i != NumLaneElts; ++i) {
3761 // Lane is all undef, go to next lane
3762 if (i == NumLaneElts)
3765 int Start = Mask[i+l];
3767 // Make sure its in this lane in one of the sources
3768 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3769 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3772 // If not lane 0, then we must match lane 0
3773 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3776 // Correct second source to be contiguous with first source
3777 if (Start >= (int)NumElts)
3778 Start -= NumElts - NumLaneElts;
3780 // Make sure we're shifting in the right direction.
3781 if (Start <= (int)(i+l))
3786 // Check the rest of the elements to see if they are consecutive.
3787 for (++i; i != NumLaneElts; ++i) {
3788 int Idx = Mask[i+l];
3790 // Make sure its in this lane
3791 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3792 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3795 // If not lane 0, then we must match lane 0
3796 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3799 if (Idx >= (int)NumElts)
3800 Idx -= NumElts - NumLaneElts;
3802 if (!isUndefOrEqual(Idx, Start+i))
3811 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3812 /// the two vector operands have swapped position.
3813 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3814 unsigned NumElems) {
3815 for (unsigned i = 0; i != NumElems; ++i) {
3819 else if (idx < (int)NumElems)
3820 Mask[i] = idx + NumElems;
3822 Mask[i] = idx - NumElems;
3826 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3827 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3828 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3829 /// reverse of what x86 shuffles want.
3830 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3832 unsigned NumElems = VT.getVectorNumElements();
3833 unsigned NumLanes = VT.getSizeInBits()/128;
3834 unsigned NumLaneElems = NumElems/NumLanes;
3836 if (NumLaneElems != 2 && NumLaneElems != 4)
3839 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3840 bool symetricMaskRequired =
3841 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3843 // VSHUFPSY divides the resulting vector into 4 chunks.
3844 // The sources are also splitted into 4 chunks, and each destination
3845 // chunk must come from a different source chunk.
3847 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3848 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3850 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3851 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3853 // VSHUFPDY divides the resulting vector into 4 chunks.
3854 // The sources are also splitted into 4 chunks, and each destination
3855 // chunk must come from a different source chunk.
3857 // SRC1 => X3 X2 X1 X0
3858 // SRC2 => Y3 Y2 Y1 Y0
3860 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3862 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3863 unsigned HalfLaneElems = NumLaneElems/2;
3864 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3865 for (unsigned i = 0; i != NumLaneElems; ++i) {
3866 int Idx = Mask[i+l];
3867 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3868 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3870 // For VSHUFPSY, the mask of the second half must be the same as the
3871 // first but with the appropriate offsets. This works in the same way as
3872 // VPERMILPS works with masks.
3873 if (!symetricMaskRequired || Idx < 0)
3875 if (MaskVal[i] < 0) {
3876 MaskVal[i] = Idx - l;
3879 if ((signed)(Idx - l) != MaskVal[i])
3887 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3888 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3889 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3890 if (!VT.is128BitVector())
3893 unsigned NumElems = VT.getVectorNumElements();
3898 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3899 return isUndefOrEqual(Mask[0], 6) &&
3900 isUndefOrEqual(Mask[1], 7) &&
3901 isUndefOrEqual(Mask[2], 2) &&
3902 isUndefOrEqual(Mask[3], 3);
3905 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3906 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3908 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3909 if (!VT.is128BitVector())
3912 unsigned NumElems = VT.getVectorNumElements();
3917 return isUndefOrEqual(Mask[0], 2) &&
3918 isUndefOrEqual(Mask[1], 3) &&
3919 isUndefOrEqual(Mask[2], 2) &&
3920 isUndefOrEqual(Mask[3], 3);
3923 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3925 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3926 if (!VT.is128BitVector())
3929 unsigned NumElems = VT.getVectorNumElements();
3931 if (NumElems != 2 && NumElems != 4)
3934 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3935 if (!isUndefOrEqual(Mask[i], i + NumElems))
3938 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3939 if (!isUndefOrEqual(Mask[i], i))
3945 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3946 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3947 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3948 if (!VT.is128BitVector())
3951 unsigned NumElems = VT.getVectorNumElements();
3953 if (NumElems != 2 && NumElems != 4)
3956 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3957 if (!isUndefOrEqual(Mask[i], i))
3960 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3961 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3967 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3968 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3969 /// i. e: If all but one element come from the same vector.
3970 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3971 // TODO: Deal with AVX's VINSERTPS
3972 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3975 unsigned CorrectPosV1 = 0;
3976 unsigned CorrectPosV2 = 0;
3977 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3978 if (Mask[i] == -1) {
3986 else if (Mask[i] == i + 4)
3990 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3991 // We have 3 elements (undefs count as elements from any vector) from one
3992 // vector, and one from another.
3999 // Some special combinations that can be optimized.
4002 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4003 SelectionDAG &DAG) {
4004 MVT VT = SVOp->getSimpleValueType(0);
4007 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4010 ArrayRef<int> Mask = SVOp->getMask();
4012 // These are the special masks that may be optimized.
4013 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4014 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4015 bool MatchEvenMask = true;
4016 bool MatchOddMask = true;
4017 for (int i=0; i<8; ++i) {
4018 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4019 MatchEvenMask = false;
4020 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4021 MatchOddMask = false;
4024 if (!MatchEvenMask && !MatchOddMask)
4027 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4029 SDValue Op0 = SVOp->getOperand(0);
4030 SDValue Op1 = SVOp->getOperand(1);
4032 if (MatchEvenMask) {
4033 // Shift the second operand right to 32 bits.
4034 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4035 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4037 // Shift the first operand left to 32 bits.
4038 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4039 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4041 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4042 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4045 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4046 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4047 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4048 bool HasInt256, bool V2IsSplat = false) {
4050 assert(VT.getSizeInBits() >= 128 &&
4051 "Unsupported vector type for unpckl");
4053 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4055 unsigned NumOf256BitLanes;
4056 unsigned NumElts = VT.getVectorNumElements();
4057 if (VT.is256BitVector()) {
4058 if (NumElts != 4 && NumElts != 8 &&
4059 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4062 NumOf256BitLanes = 1;
4063 } else if (VT.is512BitVector()) {
4064 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4065 "Unsupported vector type for unpckh");
4067 NumOf256BitLanes = 2;
4070 NumOf256BitLanes = 1;
4073 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4074 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4076 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4077 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4078 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4079 int BitI = Mask[l256*NumEltsInStride+l+i];
4080 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4081 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4083 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4085 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4093 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4094 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4095 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4096 bool HasInt256, bool V2IsSplat = false) {
4097 assert(VT.getSizeInBits() >= 128 &&
4098 "Unsupported vector type for unpckh");
4100 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4102 unsigned NumOf256BitLanes;
4103 unsigned NumElts = VT.getVectorNumElements();
4104 if (VT.is256BitVector()) {
4105 if (NumElts != 4 && NumElts != 8 &&
4106 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4109 NumOf256BitLanes = 1;
4110 } else if (VT.is512BitVector()) {
4111 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4112 "Unsupported vector type for unpckh");
4114 NumOf256BitLanes = 2;
4117 NumOf256BitLanes = 1;
4120 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4121 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4123 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4124 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4125 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4126 int BitI = Mask[l256*NumEltsInStride+l+i];
4127 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4128 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4130 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4132 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4140 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4141 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4143 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4144 unsigned NumElts = VT.getVectorNumElements();
4145 bool Is256BitVec = VT.is256BitVector();
4147 if (VT.is512BitVector())
4149 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4150 "Unsupported vector type for unpckh");
4152 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4153 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4156 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4157 // FIXME: Need a better way to get rid of this, there's no latency difference
4158 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4159 // the former later. We should also remove the "_undef" special mask.
4160 if (NumElts == 4 && Is256BitVec)
4163 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4164 // independently on 128-bit lanes.
4165 unsigned NumLanes = VT.getSizeInBits()/128;
4166 unsigned NumLaneElts = NumElts/NumLanes;
4168 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4169 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4170 int BitI = Mask[l+i];
4171 int BitI1 = Mask[l+i+1];
4173 if (!isUndefOrEqual(BitI, j))
4175 if (!isUndefOrEqual(BitI1, j))
4183 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4184 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4186 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4187 unsigned NumElts = VT.getVectorNumElements();
4189 if (VT.is512BitVector())
4192 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4193 "Unsupported vector type for unpckh");
4195 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4196 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4199 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4200 // independently on 128-bit lanes.
4201 unsigned NumLanes = VT.getSizeInBits()/128;
4202 unsigned NumLaneElts = NumElts/NumLanes;
4204 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4205 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4206 int BitI = Mask[l+i];
4207 int BitI1 = Mask[l+i+1];
4208 if (!isUndefOrEqual(BitI, j))
4210 if (!isUndefOrEqual(BitI1, j))
4217 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4218 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4219 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4220 if (!VT.is512BitVector())
4223 unsigned NumElts = VT.getVectorNumElements();
4224 unsigned HalfSize = NumElts/2;
4225 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4226 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4231 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4232 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4240 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4241 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4242 /// MOVSD, and MOVD, i.e. setting the lowest element.
4243 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4244 if (VT.getVectorElementType().getSizeInBits() < 32)
4246 if (!VT.is128BitVector())
4249 unsigned NumElts = VT.getVectorNumElements();
4251 if (!isUndefOrEqual(Mask[0], NumElts))
4254 for (unsigned i = 1; i != NumElts; ++i)
4255 if (!isUndefOrEqual(Mask[i], i))
4261 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4262 /// as permutations between 128-bit chunks or halves. As an example: this
4264 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4265 /// The first half comes from the second half of V1 and the second half from the
4266 /// the second half of V2.
4267 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4268 if (!HasFp256 || !VT.is256BitVector())
4271 // The shuffle result is divided into half A and half B. In total the two
4272 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4273 // B must come from C, D, E or F.
4274 unsigned HalfSize = VT.getVectorNumElements()/2;
4275 bool MatchA = false, MatchB = false;
4277 // Check if A comes from one of C, D, E, F.
4278 for (unsigned Half = 0; Half != 4; ++Half) {
4279 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4285 // Check if B comes from one of C, D, E, F.
4286 for (unsigned Half = 0; Half != 4; ++Half) {
4287 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4293 return MatchA && MatchB;
4296 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4297 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4298 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4299 MVT VT = SVOp->getSimpleValueType(0);
4301 unsigned HalfSize = VT.getVectorNumElements()/2;
4303 unsigned FstHalf = 0, SndHalf = 0;
4304 for (unsigned i = 0; i < HalfSize; ++i) {
4305 if (SVOp->getMaskElt(i) > 0) {
4306 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4310 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4311 if (SVOp->getMaskElt(i) > 0) {
4312 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4317 return (FstHalf | (SndHalf << 4));
4320 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4321 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4322 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4326 unsigned NumElts = VT.getVectorNumElements();
4328 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4329 for (unsigned i = 0; i != NumElts; ++i) {
4332 Imm8 |= Mask[i] << (i*2);
4337 unsigned LaneSize = 4;
4338 SmallVector<int, 4> MaskVal(LaneSize, -1);
4340 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4341 for (unsigned i = 0; i != LaneSize; ++i) {
4342 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4346 if (MaskVal[i] < 0) {
4347 MaskVal[i] = Mask[i+l] - l;
4348 Imm8 |= MaskVal[i] << (i*2);
4351 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4358 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4359 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4360 /// Note that VPERMIL mask matching is different depending whether theunderlying
4361 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4362 /// to the same elements of the low, but to the higher half of the source.
4363 /// In VPERMILPD the two lanes could be shuffled independently of each other
4364 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4365 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4366 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4367 if (VT.getSizeInBits() < 256 || EltSize < 32)
4369 bool symetricMaskRequired = (EltSize == 32);
4370 unsigned NumElts = VT.getVectorNumElements();
4372 unsigned NumLanes = VT.getSizeInBits()/128;
4373 unsigned LaneSize = NumElts/NumLanes;
4374 // 2 or 4 elements in one lane
4376 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4377 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4378 for (unsigned i = 0; i != LaneSize; ++i) {
4379 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4381 if (symetricMaskRequired) {
4382 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4383 ExpectedMaskVal[i] = Mask[i+l] - l;
4386 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4394 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4395 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4396 /// element of vector 2 and the other elements to come from vector 1 in order.
4397 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4398 bool V2IsSplat = false, bool V2IsUndef = false) {
4399 if (!VT.is128BitVector())
4402 unsigned NumOps = VT.getVectorNumElements();
4403 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4406 if (!isUndefOrEqual(Mask[0], 0))
4409 for (unsigned i = 1; i != NumOps; ++i)
4410 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4411 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4412 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4418 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4419 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4420 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4421 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4422 const X86Subtarget *Subtarget) {
4423 if (!Subtarget->hasSSE3())
4426 unsigned NumElems = VT.getVectorNumElements();
4428 if ((VT.is128BitVector() && NumElems != 4) ||
4429 (VT.is256BitVector() && NumElems != 8) ||
4430 (VT.is512BitVector() && NumElems != 16))
4433 // "i+1" is the value the indexed mask element must have
4434 for (unsigned i = 0; i != NumElems; i += 2)
4435 if (!isUndefOrEqual(Mask[i], i+1) ||
4436 !isUndefOrEqual(Mask[i+1], i+1))
4442 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4443 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4444 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4445 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4446 const X86Subtarget *Subtarget) {
4447 if (!Subtarget->hasSSE3())
4450 unsigned NumElems = VT.getVectorNumElements();
4452 if ((VT.is128BitVector() && NumElems != 4) ||
4453 (VT.is256BitVector() && NumElems != 8) ||
4454 (VT.is512BitVector() && NumElems != 16))
4457 // "i" is the value the indexed mask element must have
4458 for (unsigned i = 0; i != NumElems; i += 2)
4459 if (!isUndefOrEqual(Mask[i], i) ||
4460 !isUndefOrEqual(Mask[i+1], i))
4466 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4467 /// specifies a shuffle of elements that is suitable for input to 256-bit
4468 /// version of MOVDDUP.
4469 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4470 if (!HasFp256 || !VT.is256BitVector())
4473 unsigned NumElts = VT.getVectorNumElements();
4477 for (unsigned i = 0; i != NumElts/2; ++i)
4478 if (!isUndefOrEqual(Mask[i], 0))
4480 for (unsigned i = NumElts/2; i != NumElts; ++i)
4481 if (!isUndefOrEqual(Mask[i], NumElts/2))
4486 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4487 /// specifies a shuffle of elements that is suitable for input to 128-bit
4488 /// version of MOVDDUP.
4489 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4490 if (!VT.is128BitVector())
4493 unsigned e = VT.getVectorNumElements() / 2;
4494 for (unsigned i = 0; i != e; ++i)
4495 if (!isUndefOrEqual(Mask[i], i))
4497 for (unsigned i = 0; i != e; ++i)
4498 if (!isUndefOrEqual(Mask[e+i], i))
4503 /// isVEXTRACTIndex - Return true if the specified
4504 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4505 /// suitable for instruction that extract 128 or 256 bit vectors
4506 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4507 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4508 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4511 // The index should be aligned on a vecWidth-bit boundary.
4513 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4515 MVT VT = N->getSimpleValueType(0);
4516 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4517 bool Result = (Index * ElSize) % vecWidth == 0;
4522 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4523 /// operand specifies a subvector insert that is suitable for input to
4524 /// insertion of 128 or 256-bit subvectors
4525 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4526 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4527 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4529 // The index should be aligned on a vecWidth-bit boundary.
4531 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4533 MVT VT = N->getSimpleValueType(0);
4534 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4535 bool Result = (Index * ElSize) % vecWidth == 0;
4540 bool X86::isVINSERT128Index(SDNode *N) {
4541 return isVINSERTIndex(N, 128);
4544 bool X86::isVINSERT256Index(SDNode *N) {
4545 return isVINSERTIndex(N, 256);
4548 bool X86::isVEXTRACT128Index(SDNode *N) {
4549 return isVEXTRACTIndex(N, 128);
4552 bool X86::isVEXTRACT256Index(SDNode *N) {
4553 return isVEXTRACTIndex(N, 256);
4556 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4557 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4558 /// Handles 128-bit and 256-bit.
4559 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4560 MVT VT = N->getSimpleValueType(0);
4562 assert((VT.getSizeInBits() >= 128) &&
4563 "Unsupported vector type for PSHUF/SHUFP");
4565 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4566 // independently on 128-bit lanes.
4567 unsigned NumElts = VT.getVectorNumElements();
4568 unsigned NumLanes = VT.getSizeInBits()/128;
4569 unsigned NumLaneElts = NumElts/NumLanes;
4571 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4572 "Only supports 2, 4 or 8 elements per lane");
4574 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4576 for (unsigned i = 0; i != NumElts; ++i) {
4577 int Elt = N->getMaskElt(i);
4578 if (Elt < 0) continue;
4579 Elt &= NumLaneElts - 1;
4580 unsigned ShAmt = (i << Shift) % 8;
4581 Mask |= Elt << ShAmt;
4587 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4588 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4589 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4590 MVT VT = N->getSimpleValueType(0);
4592 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4593 "Unsupported vector type for PSHUFHW");
4595 unsigned NumElts = VT.getVectorNumElements();
4598 for (unsigned l = 0; l != NumElts; l += 8) {
4599 // 8 nodes per lane, but we only care about the last 4.
4600 for (unsigned i = 0; i < 4; ++i) {
4601 int Elt = N->getMaskElt(l+i+4);
4602 if (Elt < 0) continue;
4603 Elt &= 0x3; // only 2-bits.
4604 Mask |= Elt << (i * 2);
4611 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4612 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4613 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4614 MVT VT = N->getSimpleValueType(0);
4616 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4617 "Unsupported vector type for PSHUFHW");
4619 unsigned NumElts = VT.getVectorNumElements();
4622 for (unsigned l = 0; l != NumElts; l += 8) {
4623 // 8 nodes per lane, but we only care about the first 4.
4624 for (unsigned i = 0; i < 4; ++i) {
4625 int Elt = N->getMaskElt(l+i);
4626 if (Elt < 0) continue;
4627 Elt &= 0x3; // only 2-bits
4628 Mask |= Elt << (i * 2);
4635 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4636 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4637 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4638 MVT VT = SVOp->getSimpleValueType(0);
4639 unsigned EltSize = VT.is512BitVector() ? 1 :
4640 VT.getVectorElementType().getSizeInBits() >> 3;
4642 unsigned NumElts = VT.getVectorNumElements();
4643 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4644 unsigned NumLaneElts = NumElts/NumLanes;
4648 for (i = 0; i != NumElts; ++i) {
4649 Val = SVOp->getMaskElt(i);
4653 if (Val >= (int)NumElts)
4654 Val -= NumElts - NumLaneElts;
4656 assert(Val - i > 0 && "PALIGNR imm should be positive");
4657 return (Val - i) * EltSize;
4660 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4661 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4662 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4663 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4666 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4668 MVT VecVT = N->getOperand(0).getSimpleValueType();
4669 MVT ElVT = VecVT.getVectorElementType();
4671 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4672 return Index / NumElemsPerChunk;
4675 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4676 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4677 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4678 llvm_unreachable("Illegal insert subvector for VINSERT");
4681 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4683 MVT VecVT = N->getSimpleValueType(0);
4684 MVT ElVT = VecVT.getVectorElementType();
4686 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4687 return Index / NumElemsPerChunk;
4690 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4691 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4692 /// and VINSERTI128 instructions.
4693 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4694 return getExtractVEXTRACTImmediate(N, 128);
4697 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4698 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4699 /// and VINSERTI64x4 instructions.
4700 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4701 return getExtractVEXTRACTImmediate(N, 256);
4704 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4705 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4706 /// and VINSERTI128 instructions.
4707 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4708 return getInsertVINSERTImmediate(N, 128);
4711 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4712 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4713 /// and VINSERTI64x4 instructions.
4714 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4715 return getInsertVINSERTImmediate(N, 256);
4718 /// isZero - Returns true if Elt is a constant integer zero
4719 static bool isZero(SDValue V) {
4720 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4721 return C && C->isNullValue();
4724 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4726 bool X86::isZeroNode(SDValue Elt) {
4729 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4730 return CFP->getValueAPF().isPosZero();
4734 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4735 /// their permute mask.
4736 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4737 SelectionDAG &DAG) {
4738 MVT VT = SVOp->getSimpleValueType(0);
4739 unsigned NumElems = VT.getVectorNumElements();
4740 SmallVector<int, 8> MaskVec;
4742 for (unsigned i = 0; i != NumElems; ++i) {
4743 int Idx = SVOp->getMaskElt(i);
4745 if (Idx < (int)NumElems)
4750 MaskVec.push_back(Idx);
4752 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4753 SVOp->getOperand(0), &MaskVec[0]);
4756 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4757 /// match movhlps. The lower half elements should come from upper half of
4758 /// V1 (and in order), and the upper half elements should come from the upper
4759 /// half of V2 (and in order).
4760 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4761 if (!VT.is128BitVector())
4763 if (VT.getVectorNumElements() != 4)
4765 for (unsigned i = 0, e = 2; i != e; ++i)
4766 if (!isUndefOrEqual(Mask[i], i+2))
4768 for (unsigned i = 2; i != 4; ++i)
4769 if (!isUndefOrEqual(Mask[i], i+4))
4774 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4775 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4777 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4778 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4780 N = N->getOperand(0).getNode();
4781 if (!ISD::isNON_EXTLoad(N))
4784 *LD = cast<LoadSDNode>(N);
4788 // Test whether the given value is a vector value which will be legalized
4790 static bool WillBeConstantPoolLoad(SDNode *N) {
4791 if (N->getOpcode() != ISD::BUILD_VECTOR)
4794 // Check for any non-constant elements.
4795 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4796 switch (N->getOperand(i).getNode()->getOpcode()) {
4798 case ISD::ConstantFP:
4805 // Vectors of all-zeros and all-ones are materialized with special
4806 // instructions rather than being loaded.
4807 return !ISD::isBuildVectorAllZeros(N) &&
4808 !ISD::isBuildVectorAllOnes(N);
4811 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4812 /// match movlp{s|d}. The lower half elements should come from lower half of
4813 /// V1 (and in order), and the upper half elements should come from the upper
4814 /// half of V2 (and in order). And since V1 will become the source of the
4815 /// MOVLP, it must be either a vector load or a scalar load to vector.
4816 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4817 ArrayRef<int> Mask, MVT VT) {
4818 if (!VT.is128BitVector())
4821 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4823 // Is V2 is a vector load, don't do this transformation. We will try to use
4824 // load folding shufps op.
4825 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4828 unsigned NumElems = VT.getVectorNumElements();
4830 if (NumElems != 2 && NumElems != 4)
4832 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4833 if (!isUndefOrEqual(Mask[i], i))
4835 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4836 if (!isUndefOrEqual(Mask[i], i+NumElems))
4841 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4843 static bool isSplatVector(SDNode *N) {
4844 if (N->getOpcode() != ISD::BUILD_VECTOR)
4847 SDValue SplatValue = N->getOperand(0);
4848 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4849 if (N->getOperand(i) != SplatValue)
4854 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4855 /// to an zero vector.
4856 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4857 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4858 SDValue V1 = N->getOperand(0);
4859 SDValue V2 = N->getOperand(1);
4860 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4861 for (unsigned i = 0; i != NumElems; ++i) {
4862 int Idx = N->getMaskElt(i);
4863 if (Idx >= (int)NumElems) {
4864 unsigned Opc = V2.getOpcode();
4865 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4867 if (Opc != ISD::BUILD_VECTOR ||
4868 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4870 } else if (Idx >= 0) {
4871 unsigned Opc = V1.getOpcode();
4872 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4874 if (Opc != ISD::BUILD_VECTOR ||
4875 !X86::isZeroNode(V1.getOperand(Idx)))
4882 /// getZeroVector - Returns a vector of specified type with all zero elements.
4884 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4885 SelectionDAG &DAG, SDLoc dl) {
4886 assert(VT.isVector() && "Expected a vector type");
4888 // Always build SSE zero vectors as <4 x i32> bitcasted
4889 // to their dest type. This ensures they get CSE'd.
4891 if (VT.is128BitVector()) { // SSE
4892 if (Subtarget->hasSSE2()) { // SSE2
4893 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4894 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4896 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4897 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4899 } else if (VT.is256BitVector()) { // AVX
4900 if (Subtarget->hasInt256()) { // AVX2
4901 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4902 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4903 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4905 // 256-bit logic and arithmetic instructions in AVX are all
4906 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4907 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4908 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4909 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4911 } else if (VT.is512BitVector()) { // AVX-512
4912 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4913 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4914 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4915 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4916 } else if (VT.getScalarType() == MVT::i1) {
4917 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4918 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4919 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4920 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4922 llvm_unreachable("Unexpected vector type");
4924 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4927 /// getOnesVector - Returns a vector of specified type with all bits set.
4928 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4929 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4930 /// Then bitcast to their original type, ensuring they get CSE'd.
4931 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4933 assert(VT.isVector() && "Expected a vector type");
4935 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4937 if (VT.is256BitVector()) {
4938 if (HasInt256) { // AVX2
4939 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4940 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4942 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4943 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4945 } else if (VT.is128BitVector()) {
4946 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4948 llvm_unreachable("Unexpected vector type");
4950 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4953 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4954 /// that point to V2 points to its first element.
4955 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4956 for (unsigned i = 0; i != NumElems; ++i) {
4957 if (Mask[i] > (int)NumElems) {
4963 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4964 /// operation of specified width.
4965 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4967 unsigned NumElems = VT.getVectorNumElements();
4968 SmallVector<int, 8> Mask;
4969 Mask.push_back(NumElems);
4970 for (unsigned i = 1; i != NumElems; ++i)
4972 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4975 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4976 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4978 unsigned NumElems = VT.getVectorNumElements();
4979 SmallVector<int, 8> Mask;
4980 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4982 Mask.push_back(i + NumElems);
4984 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4987 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4988 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4990 unsigned NumElems = VT.getVectorNumElements();
4991 SmallVector<int, 8> Mask;
4992 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4993 Mask.push_back(i + Half);
4994 Mask.push_back(i + NumElems + Half);
4996 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4999 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5000 // a generic shuffle instruction because the target has no such instructions.
5001 // Generate shuffles which repeat i16 and i8 several times until they can be
5002 // represented by v4f32 and then be manipulated by target suported shuffles.
5003 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5004 MVT VT = V.getSimpleValueType();
5005 int NumElems = VT.getVectorNumElements();
5008 while (NumElems > 4) {
5009 if (EltNo < NumElems/2) {
5010 V = getUnpackl(DAG, dl, VT, V, V);
5012 V = getUnpackh(DAG, dl, VT, V, V);
5013 EltNo -= NumElems/2;
5020 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5021 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5022 MVT VT = V.getSimpleValueType();
5025 if (VT.is128BitVector()) {
5026 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5027 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5028 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5030 } else if (VT.is256BitVector()) {
5031 // To use VPERMILPS to splat scalars, the second half of indicies must
5032 // refer to the higher part, which is a duplication of the lower one,
5033 // because VPERMILPS can only handle in-lane permutations.
5034 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5035 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5037 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5038 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5041 llvm_unreachable("Vector size not supported");
5043 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5046 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5047 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5048 MVT SrcVT = SV->getSimpleValueType(0);
5049 SDValue V1 = SV->getOperand(0);
5052 int EltNo = SV->getSplatIndex();
5053 int NumElems = SrcVT.getVectorNumElements();
5054 bool Is256BitVec = SrcVT.is256BitVector();
5056 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5057 "Unknown how to promote splat for type");
5059 // Extract the 128-bit part containing the splat element and update
5060 // the splat element index when it refers to the higher register.
5062 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5063 if (EltNo >= NumElems/2)
5064 EltNo -= NumElems/2;
5067 // All i16 and i8 vector types can't be used directly by a generic shuffle
5068 // instruction because the target has no such instruction. Generate shuffles
5069 // which repeat i16 and i8 several times until they fit in i32, and then can
5070 // be manipulated by target suported shuffles.
5071 MVT EltVT = SrcVT.getVectorElementType();
5072 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5073 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5075 // Recreate the 256-bit vector and place the same 128-bit vector
5076 // into the low and high part. This is necessary because we want
5077 // to use VPERM* to shuffle the vectors
5079 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5082 return getLegalSplat(DAG, V1, EltNo);
5085 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5086 /// vector of zero or undef vector. This produces a shuffle where the low
5087 /// element of V2 is swizzled into the zero/undef vector, landing at element
5088 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5089 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5091 const X86Subtarget *Subtarget,
5092 SelectionDAG &DAG) {
5093 MVT VT = V2.getSimpleValueType();
5095 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5096 unsigned NumElems = VT.getVectorNumElements();
5097 SmallVector<int, 16> MaskVec;
5098 for (unsigned i = 0; i != NumElems; ++i)
5099 // If this is the insertion idx, put the low elt of V2 here.
5100 MaskVec.push_back(i == Idx ? NumElems : i);
5101 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5104 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5105 /// target specific opcode. Returns true if the Mask could be calculated.
5106 /// Sets IsUnary to true if only uses one source.
5107 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5108 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5109 unsigned NumElems = VT.getVectorNumElements();
5113 switch(N->getOpcode()) {
5115 ImmN = N->getOperand(N->getNumOperands()-1);
5116 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5118 case X86ISD::UNPCKH:
5119 DecodeUNPCKHMask(VT, Mask);
5121 case X86ISD::UNPCKL:
5122 DecodeUNPCKLMask(VT, Mask);
5124 case X86ISD::MOVHLPS:
5125 DecodeMOVHLPSMask(NumElems, Mask);
5127 case X86ISD::MOVLHPS:
5128 DecodeMOVLHPSMask(NumElems, Mask);
5130 case X86ISD::PALIGNR:
5131 ImmN = N->getOperand(N->getNumOperands()-1);
5132 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5134 case X86ISD::PSHUFD:
5135 case X86ISD::VPERMILP:
5136 ImmN = N->getOperand(N->getNumOperands()-1);
5137 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5140 case X86ISD::PSHUFHW:
5141 ImmN = N->getOperand(N->getNumOperands()-1);
5142 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5145 case X86ISD::PSHUFLW:
5146 ImmN = N->getOperand(N->getNumOperands()-1);
5147 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5150 case X86ISD::VPERMI:
5151 ImmN = N->getOperand(N->getNumOperands()-1);
5152 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5156 case X86ISD::MOVSD: {
5157 // The index 0 always comes from the first element of the second source,
5158 // this is why MOVSS and MOVSD are used in the first place. The other
5159 // elements come from the other positions of the first source vector
5160 Mask.push_back(NumElems);
5161 for (unsigned i = 1; i != NumElems; ++i) {
5166 case X86ISD::VPERM2X128:
5167 ImmN = N->getOperand(N->getNumOperands()-1);
5168 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5169 if (Mask.empty()) return false;
5171 case X86ISD::MOVDDUP:
5172 case X86ISD::MOVLHPD:
5173 case X86ISD::MOVLPD:
5174 case X86ISD::MOVLPS:
5175 case X86ISD::MOVSHDUP:
5176 case X86ISD::MOVSLDUP:
5177 // Not yet implemented
5179 default: llvm_unreachable("unknown target shuffle node");
5185 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5186 /// element of the result of the vector shuffle.
5187 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5190 return SDValue(); // Limit search depth.
5192 SDValue V = SDValue(N, 0);
5193 EVT VT = V.getValueType();
5194 unsigned Opcode = V.getOpcode();
5196 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5197 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5198 int Elt = SV->getMaskElt(Index);
5201 return DAG.getUNDEF(VT.getVectorElementType());
5203 unsigned NumElems = VT.getVectorNumElements();
5204 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5205 : SV->getOperand(1);
5206 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5209 // Recurse into target specific vector shuffles to find scalars.
5210 if (isTargetShuffle(Opcode)) {
5211 MVT ShufVT = V.getSimpleValueType();
5212 unsigned NumElems = ShufVT.getVectorNumElements();
5213 SmallVector<int, 16> ShuffleMask;
5216 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5219 int Elt = ShuffleMask[Index];
5221 return DAG.getUNDEF(ShufVT.getVectorElementType());
5223 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5225 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5229 // Actual nodes that may contain scalar elements
5230 if (Opcode == ISD::BITCAST) {
5231 V = V.getOperand(0);
5232 EVT SrcVT = V.getValueType();
5233 unsigned NumElems = VT.getVectorNumElements();
5235 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5239 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5240 return (Index == 0) ? V.getOperand(0)
5241 : DAG.getUNDEF(VT.getVectorElementType());
5243 if (V.getOpcode() == ISD::BUILD_VECTOR)
5244 return V.getOperand(Index);
5249 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5250 /// shuffle operation which come from a consecutively from a zero. The
5251 /// search can start in two different directions, from left or right.
5252 /// We count undefs as zeros until PreferredNum is reached.
5253 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5254 unsigned NumElems, bool ZerosFromLeft,
5256 unsigned PreferredNum = -1U) {
5257 unsigned NumZeros = 0;
5258 for (unsigned i = 0; i != NumElems; ++i) {
5259 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5260 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5264 if (X86::isZeroNode(Elt))
5266 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5267 NumZeros = std::min(NumZeros + 1, PreferredNum);
5275 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5276 /// correspond consecutively to elements from one of the vector operands,
5277 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5279 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5280 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5281 unsigned NumElems, unsigned &OpNum) {
5282 bool SeenV1 = false;
5283 bool SeenV2 = false;
5285 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5286 int Idx = SVOp->getMaskElt(i);
5287 // Ignore undef indicies
5291 if (Idx < (int)NumElems)
5296 // Only accept consecutive elements from the same vector
5297 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5301 OpNum = SeenV1 ? 0 : 1;
5305 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5306 /// logical left shift of a vector.
5307 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5308 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5310 SVOp->getSimpleValueType(0).getVectorNumElements();
5311 unsigned NumZeros = getNumOfConsecutiveZeros(
5312 SVOp, NumElems, false /* check zeros from right */, DAG,
5313 SVOp->getMaskElt(0));
5319 // Considering the elements in the mask that are not consecutive zeros,
5320 // check if they consecutively come from only one of the source vectors.
5322 // V1 = {X, A, B, C} 0
5324 // vector_shuffle V1, V2 <1, 2, 3, X>
5326 if (!isShuffleMaskConsecutive(SVOp,
5327 0, // Mask Start Index
5328 NumElems-NumZeros, // Mask End Index(exclusive)
5329 NumZeros, // Where to start looking in the src vector
5330 NumElems, // Number of elements in vector
5331 OpSrc)) // Which source operand ?
5336 ShVal = SVOp->getOperand(OpSrc);
5340 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5341 /// logical left shift of a vector.
5342 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5343 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5345 SVOp->getSimpleValueType(0).getVectorNumElements();
5346 unsigned NumZeros = getNumOfConsecutiveZeros(
5347 SVOp, NumElems, true /* check zeros from left */, DAG,
5348 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5354 // Considering the elements in the mask that are not consecutive zeros,
5355 // check if they consecutively come from only one of the source vectors.
5357 // 0 { A, B, X, X } = V2
5359 // vector_shuffle V1, V2 <X, X, 4, 5>
5361 if (!isShuffleMaskConsecutive(SVOp,
5362 NumZeros, // Mask Start Index
5363 NumElems, // Mask End Index(exclusive)
5364 0, // Where to start looking in the src vector
5365 NumElems, // Number of elements in vector
5366 OpSrc)) // Which source operand ?
5371 ShVal = SVOp->getOperand(OpSrc);
5375 /// isVectorShift - Returns true if the shuffle can be implemented as a
5376 /// logical left or right shift of a vector.
5377 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5378 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5379 // Although the logic below support any bitwidth size, there are no
5380 // shift instructions which handle more than 128-bit vectors.
5381 if (!SVOp->getSimpleValueType(0).is128BitVector())
5384 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5385 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5391 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5393 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5394 unsigned NumNonZero, unsigned NumZero,
5396 const X86Subtarget* Subtarget,
5397 const TargetLowering &TLI) {
5404 for (unsigned i = 0; i < 16; ++i) {
5405 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5406 if (ThisIsNonZero && First) {
5408 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5410 V = DAG.getUNDEF(MVT::v8i16);
5415 SDValue ThisElt, LastElt;
5416 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5417 if (LastIsNonZero) {
5418 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5419 MVT::i16, Op.getOperand(i-1));
5421 if (ThisIsNonZero) {
5422 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5423 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5424 ThisElt, DAG.getConstant(8, MVT::i8));
5426 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5430 if (ThisElt.getNode())
5431 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5432 DAG.getIntPtrConstant(i/2));
5436 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5439 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5441 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5442 unsigned NumNonZero, unsigned NumZero,
5444 const X86Subtarget* Subtarget,
5445 const TargetLowering &TLI) {
5452 for (unsigned i = 0; i < 8; ++i) {
5453 bool isNonZero = (NonZeros & (1 << i)) != 0;
5457 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5459 V = DAG.getUNDEF(MVT::v8i16);
5462 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5463 MVT::v8i16, V, Op.getOperand(i),
5464 DAG.getIntPtrConstant(i));
5471 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5472 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5473 unsigned NonZeros, unsigned NumNonZero,
5474 unsigned NumZero, SelectionDAG &DAG,
5475 const X86Subtarget *Subtarget,
5476 const TargetLowering &TLI) {
5477 // We know there's at least one non-zero element
5478 unsigned FirstNonZeroIdx = 0;
5479 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5480 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5481 X86::isZeroNode(FirstNonZero)) {
5483 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5486 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5487 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5490 SDValue V = FirstNonZero.getOperand(0);
5491 MVT VVT = V.getSimpleValueType();
5492 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5495 unsigned FirstNonZeroDst =
5496 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5497 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5498 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5499 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5501 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5502 SDValue Elem = Op.getOperand(Idx);
5503 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5506 // TODO: What else can be here? Deal with it.
5507 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5510 // TODO: Some optimizations are still possible here
5511 // ex: Getting one element from a vector, and the rest from another.
5512 if (Elem.getOperand(0) != V)
5515 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5518 else if (IncorrectIdx == -1U) {
5522 // There was already one element with an incorrect index.
5523 // We can't optimize this case to an insertps.
5527 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5529 EVT VT = Op.getSimpleValueType();
5530 unsigned ElementMoveMask = 0;
5531 if (IncorrectIdx == -1U)
5532 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5534 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5536 SDValue InsertpsMask =
5537 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5538 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5544 /// getVShift - Return a vector logical shift node.
5546 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5547 unsigned NumBits, SelectionDAG &DAG,
5548 const TargetLowering &TLI, SDLoc dl) {
5549 assert(VT.is128BitVector() && "Unknown type for VShift");
5550 EVT ShVT = MVT::v2i64;
5551 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5552 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5553 return DAG.getNode(ISD::BITCAST, dl, VT,
5554 DAG.getNode(Opc, dl, ShVT, SrcOp,
5555 DAG.getConstant(NumBits,
5556 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5560 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5562 // Check if the scalar load can be widened into a vector load. And if
5563 // the address is "base + cst" see if the cst can be "absorbed" into
5564 // the shuffle mask.
5565 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5566 SDValue Ptr = LD->getBasePtr();
5567 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5569 EVT PVT = LD->getValueType(0);
5570 if (PVT != MVT::i32 && PVT != MVT::f32)
5575 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5576 FI = FINode->getIndex();
5578 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5579 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5580 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5581 Offset = Ptr.getConstantOperandVal(1);
5582 Ptr = Ptr.getOperand(0);
5587 // FIXME: 256-bit vector instructions don't require a strict alignment,
5588 // improve this code to support it better.
5589 unsigned RequiredAlign = VT.getSizeInBits()/8;
5590 SDValue Chain = LD->getChain();
5591 // Make sure the stack object alignment is at least 16 or 32.
5592 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5593 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5594 if (MFI->isFixedObjectIndex(FI)) {
5595 // Can't change the alignment. FIXME: It's possible to compute
5596 // the exact stack offset and reference FI + adjust offset instead.
5597 // If someone *really* cares about this. That's the way to implement it.
5600 MFI->setObjectAlignment(FI, RequiredAlign);
5604 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5605 // Ptr + (Offset & ~15).
5608 if ((Offset % RequiredAlign) & 3)
5610 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5612 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5613 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5615 int EltNo = (Offset - StartOffset) >> 2;
5616 unsigned NumElems = VT.getVectorNumElements();
5618 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5619 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5620 LD->getPointerInfo().getWithOffset(StartOffset),
5621 false, false, false, 0);
5623 SmallVector<int, 8> Mask;
5624 for (unsigned i = 0; i != NumElems; ++i)
5625 Mask.push_back(EltNo);
5627 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5633 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5634 /// vector of type 'VT', see if the elements can be replaced by a single large
5635 /// load which has the same value as a build_vector whose operands are 'elts'.
5637 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5639 /// FIXME: we'd also like to handle the case where the last elements are zero
5640 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5641 /// There's even a handy isZeroNode for that purpose.
5642 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5643 SDLoc &DL, SelectionDAG &DAG,
5644 bool isAfterLegalize) {
5645 EVT EltVT = VT.getVectorElementType();
5646 unsigned NumElems = Elts.size();
5648 LoadSDNode *LDBase = nullptr;
5649 unsigned LastLoadedElt = -1U;
5651 // For each element in the initializer, see if we've found a load or an undef.
5652 // If we don't find an initial load element, or later load elements are
5653 // non-consecutive, bail out.
5654 for (unsigned i = 0; i < NumElems; ++i) {
5655 SDValue Elt = Elts[i];
5657 if (!Elt.getNode() ||
5658 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5661 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5663 LDBase = cast<LoadSDNode>(Elt.getNode());
5667 if (Elt.getOpcode() == ISD::UNDEF)
5670 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5671 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5676 // If we have found an entire vector of loads and undefs, then return a large
5677 // load of the entire vector width starting at the base pointer. If we found
5678 // consecutive loads for the low half, generate a vzext_load node.
5679 if (LastLoadedElt == NumElems - 1) {
5681 if (isAfterLegalize &&
5682 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5685 SDValue NewLd = SDValue();
5687 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5688 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5689 LDBase->getPointerInfo(),
5690 LDBase->isVolatile(), LDBase->isNonTemporal(),
5691 LDBase->isInvariant(), 0);
5692 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5693 LDBase->getPointerInfo(),
5694 LDBase->isVolatile(), LDBase->isNonTemporal(),
5695 LDBase->isInvariant(), LDBase->getAlignment());
5697 if (LDBase->hasAnyUseOfValue(1)) {
5698 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5700 SDValue(NewLd.getNode(), 1));
5701 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5702 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5703 SDValue(NewLd.getNode(), 1));
5708 if (NumElems == 4 && LastLoadedElt == 1 &&
5709 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5710 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5711 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5713 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5714 LDBase->getPointerInfo(),
5715 LDBase->getAlignment(),
5716 false/*isVolatile*/, true/*ReadMem*/,
5719 // Make sure the newly-created LOAD is in the same position as LDBase in
5720 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5721 // update uses of LDBase's output chain to use the TokenFactor.
5722 if (LDBase->hasAnyUseOfValue(1)) {
5723 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5724 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5725 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5726 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5727 SDValue(ResNode.getNode(), 1));
5730 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5735 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5736 /// to generate a splat value for the following cases:
5737 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5738 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5739 /// a scalar load, or a constant.
5740 /// The VBROADCAST node is returned when a pattern is found,
5741 /// or SDValue() otherwise.
5742 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5743 SelectionDAG &DAG) {
5744 if (!Subtarget->hasFp256())
5747 MVT VT = Op.getSimpleValueType();
5750 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5751 "Unsupported vector type for broadcast.");
5756 switch (Op.getOpcode()) {
5758 // Unknown pattern found.
5761 case ISD::BUILD_VECTOR: {
5762 // The BUILD_VECTOR node must be a splat.
5763 if (!isSplatVector(Op.getNode()))
5766 Ld = Op.getOperand(0);
5767 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5768 Ld.getOpcode() == ISD::ConstantFP);
5770 // The suspected load node has several users. Make sure that all
5771 // of its users are from the BUILD_VECTOR node.
5772 // Constants may have multiple users.
5773 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5778 case ISD::VECTOR_SHUFFLE: {
5779 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5781 // Shuffles must have a splat mask where the first element is
5783 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5786 SDValue Sc = Op.getOperand(0);
5787 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5788 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5790 if (!Subtarget->hasInt256())
5793 // Use the register form of the broadcast instruction available on AVX2.
5794 if (VT.getSizeInBits() >= 256)
5795 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5796 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5799 Ld = Sc.getOperand(0);
5800 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5801 Ld.getOpcode() == ISD::ConstantFP);
5803 // The scalar_to_vector node and the suspected
5804 // load node must have exactly one user.
5805 // Constants may have multiple users.
5807 // AVX-512 has register version of the broadcast
5808 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5809 Ld.getValueType().getSizeInBits() >= 32;
5810 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5817 bool IsGE256 = (VT.getSizeInBits() >= 256);
5819 // Handle the broadcasting a single constant scalar from the constant pool
5820 // into a vector. On Sandybridge it is still better to load a constant vector
5821 // from the constant pool and not to broadcast it from a scalar.
5822 if (ConstSplatVal && Subtarget->hasInt256()) {
5823 EVT CVT = Ld.getValueType();
5824 assert(!CVT.isVector() && "Must not broadcast a vector type");
5825 unsigned ScalarSize = CVT.getSizeInBits();
5827 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5828 const Constant *C = nullptr;
5829 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5830 C = CI->getConstantIntValue();
5831 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5832 C = CF->getConstantFPValue();
5834 assert(C && "Invalid constant type");
5836 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5837 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5838 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5839 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5840 MachinePointerInfo::getConstantPool(),
5841 false, false, false, Alignment);
5843 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5847 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5848 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5850 // Handle AVX2 in-register broadcasts.
5851 if (!IsLoad && Subtarget->hasInt256() &&
5852 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5853 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5855 // The scalar source must be a normal load.
5859 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5860 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5862 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5863 // double since there is no vbroadcastsd xmm
5864 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5865 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5866 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5869 // Unsupported broadcast.
5873 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5874 /// underlying vector and index.
5876 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5878 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5880 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5881 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5884 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5886 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5888 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5889 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5892 // In this case the vector is the extract_subvector expression and the index
5893 // is 2, as specified by the shuffle.
5894 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5895 SDValue ShuffleVec = SVOp->getOperand(0);
5896 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5897 assert(ShuffleVecVT.getVectorElementType() ==
5898 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5900 int ShuffleIdx = SVOp->getMaskElt(Idx);
5901 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5902 ExtractedFromVec = ShuffleVec;
5908 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5909 MVT VT = Op.getSimpleValueType();
5911 // Skip if insert_vec_elt is not supported.
5912 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5913 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5917 unsigned NumElems = Op.getNumOperands();
5921 SmallVector<unsigned, 4> InsertIndices;
5922 SmallVector<int, 8> Mask(NumElems, -1);
5924 for (unsigned i = 0; i != NumElems; ++i) {
5925 unsigned Opc = Op.getOperand(i).getOpcode();
5927 if (Opc == ISD::UNDEF)
5930 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5931 // Quit if more than 1 elements need inserting.
5932 if (InsertIndices.size() > 1)
5935 InsertIndices.push_back(i);
5939 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5940 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5941 // Quit if non-constant index.
5942 if (!isa<ConstantSDNode>(ExtIdx))
5944 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5946 // Quit if extracted from vector of different type.
5947 if (ExtractedFromVec.getValueType() != VT)
5950 if (!VecIn1.getNode())
5951 VecIn1 = ExtractedFromVec;
5952 else if (VecIn1 != ExtractedFromVec) {
5953 if (!VecIn2.getNode())
5954 VecIn2 = ExtractedFromVec;
5955 else if (VecIn2 != ExtractedFromVec)
5956 // Quit if more than 2 vectors to shuffle
5960 if (ExtractedFromVec == VecIn1)
5962 else if (ExtractedFromVec == VecIn2)
5963 Mask[i] = Idx + NumElems;
5966 if (!VecIn1.getNode())
5969 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5970 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5971 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5972 unsigned Idx = InsertIndices[i];
5973 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5974 DAG.getIntPtrConstant(Idx));
5980 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5982 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5984 MVT VT = Op.getSimpleValueType();
5985 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5986 "Unexpected type in LowerBUILD_VECTORvXi1!");
5989 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5990 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5991 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5992 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5995 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5996 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5997 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5998 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6001 bool AllContants = true;
6002 uint64_t Immediate = 0;
6003 int NonConstIdx = -1;
6004 bool IsSplat = true;
6005 unsigned NumNonConsts = 0;
6006 unsigned NumConsts = 0;
6007 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6008 SDValue In = Op.getOperand(idx);
6009 if (In.getOpcode() == ISD::UNDEF)
6011 if (!isa<ConstantSDNode>(In)) {
6012 AllContants = false;
6018 if (cast<ConstantSDNode>(In)->getZExtValue())
6019 Immediate |= (1ULL << idx);
6021 if (In != Op.getOperand(0))
6026 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6027 DAG.getConstant(Immediate, MVT::i16));
6028 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6029 DAG.getIntPtrConstant(0));
6032 if (NumNonConsts == 1 && NonConstIdx != 0) {
6035 SDValue VecAsImm = DAG.getConstant(Immediate,
6036 MVT::getIntegerVT(VT.getSizeInBits()));
6037 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6040 DstVec = DAG.getUNDEF(VT);
6041 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6042 Op.getOperand(NonConstIdx),
6043 DAG.getIntPtrConstant(NonConstIdx));
6045 if (!IsSplat && (NonConstIdx != 0))
6046 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6047 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6050 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6051 DAG.getConstant(-1, SelectVT),
6052 DAG.getConstant(0, SelectVT));
6054 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6055 DAG.getConstant((Immediate | 1), SelectVT),
6056 DAG.getConstant(Immediate, SelectVT));
6057 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6060 /// \brief Return true if \p N implements a horizontal binop and return the
6061 /// operands for the horizontal binop into V0 and V1.
6063 /// This is a helper function of PerformBUILD_VECTORCombine.
6064 /// This function checks that the build_vector \p N in input implements a
6065 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6066 /// operation to match.
6067 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6068 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6069 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6072 /// This function only analyzes elements of \p N whose indices are
6073 /// in range [BaseIdx, LastIdx).
6074 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6075 unsigned BaseIdx, unsigned LastIdx,
6076 SDValue &V0, SDValue &V1) {
6077 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6078 assert(N->getValueType(0).isVector() &&
6079 N->getValueType(0).getVectorNumElements() >= LastIdx &&
6080 "Invalid Vector in input!");
6082 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6083 bool CanFold = true;
6084 unsigned ExpectedVExtractIdx = BaseIdx;
6085 unsigned NumElts = LastIdx - BaseIdx;
6087 // Check if N implements a horizontal binop.
6088 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6089 SDValue Op = N->getOperand(i + BaseIdx);
6090 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6095 SDValue Op0 = Op.getOperand(0);
6096 SDValue Op1 = Op.getOperand(1);
6098 // Try to match the following pattern:
6099 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6100 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6101 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6102 Op0.getOperand(0) == Op1.getOperand(0) &&
6103 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6104 isa<ConstantSDNode>(Op1.getOperand(1)));
6108 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6109 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6112 V0 = Op0.getOperand(0);
6113 else if (i * 2 == NumElts) {
6114 V1 = Op0.getOperand(0);
6115 ExpectedVExtractIdx = BaseIdx;
6118 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6119 if (I0 == ExpectedVExtractIdx)
6120 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6121 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6122 // Try to match the following dag sequence:
6123 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6124 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6128 ExpectedVExtractIdx += 2;
6134 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6135 const X86Subtarget *Subtarget) {
6137 EVT VT = N->getValueType(0);
6138 unsigned NumElts = VT.getVectorNumElements();
6139 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6140 SDValue InVec0, InVec1;
6142 // Try to match horizontal ADD/SUB.
6143 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6144 // Try to match an SSE3 float HADD/HSUB.
6145 if (isHorizontalBinOp(BV, ISD::FADD, 0, NumElts, InVec0, InVec1))
6146 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6148 if (isHorizontalBinOp(BV, ISD::FSUB, 0, NumElts, InVec0, InVec1))
6149 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6150 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6151 // Try to match an SSSE3 integer HADD/HSUB.
6152 if (isHorizontalBinOp(BV, ISD::ADD, 0, NumElts, InVec0, InVec1))
6153 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6155 if (isHorizontalBinOp(BV, ISD::SUB, 0, NumElts, InVec0, InVec1))
6156 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6159 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6160 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6162 if (isHorizontalBinOp(BV, ISD::ADD, 0, NumElts, InVec0, InVec1))
6163 X86Opcode = X86ISD::HADD;
6164 else if (isHorizontalBinOp(BV, ISD::SUB, 0, NumElts, InVec0, InVec1))
6165 X86Opcode = X86ISD::HSUB;
6166 else if (isHorizontalBinOp(BV, ISD::FADD, 0, NumElts, InVec0, InVec1))
6167 X86Opcode = X86ISD::FHADD;
6168 else if (isHorizontalBinOp(BV, ISD::FSUB, 0, NumElts, InVec0, InVec1))
6169 X86Opcode = X86ISD::FHSUB;
6173 // Convert this build_vector into two horizontal add/sub followed by
6175 SDValue InVec0_LO = Extract128BitVector(InVec0, 0, DAG, DL);
6176 SDValue InVec0_HI = Extract128BitVector(InVec0, NumElts/2, DAG, DL);
6177 SDValue InVec1_LO = Extract128BitVector(InVec1, 0, DAG, DL);
6178 SDValue InVec1_HI = Extract128BitVector(InVec1, NumElts/2, DAG, DL);
6179 EVT NewVT = InVec0_LO.getValueType();
6181 SDValue LO = DAG.getNode(X86Opcode, DL, NewVT, InVec0_LO, InVec0_HI);
6182 SDValue HI = DAG.getNode(X86Opcode, DL, NewVT, InVec1_LO, InVec1_HI);
6183 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6190 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6193 MVT VT = Op.getSimpleValueType();
6194 MVT ExtVT = VT.getVectorElementType();
6195 unsigned NumElems = Op.getNumOperands();
6197 // Generate vectors for predicate vectors.
6198 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6199 return LowerBUILD_VECTORvXi1(Op, DAG);
6201 // Vectors containing all zeros can be matched by pxor and xorps later
6202 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6203 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6204 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6205 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6208 return getZeroVector(VT, Subtarget, DAG, dl);
6211 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6212 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6213 // vpcmpeqd on 256-bit vectors.
6214 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6215 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6218 if (!VT.is512BitVector())
6219 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6222 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6223 if (Broadcast.getNode())
6226 unsigned EVTBits = ExtVT.getSizeInBits();
6228 unsigned NumZero = 0;
6229 unsigned NumNonZero = 0;
6230 unsigned NonZeros = 0;
6231 bool IsAllConstants = true;
6232 SmallSet<SDValue, 8> Values;
6233 for (unsigned i = 0; i < NumElems; ++i) {
6234 SDValue Elt = Op.getOperand(i);
6235 if (Elt.getOpcode() == ISD::UNDEF)
6238 if (Elt.getOpcode() != ISD::Constant &&
6239 Elt.getOpcode() != ISD::ConstantFP)
6240 IsAllConstants = false;
6241 if (X86::isZeroNode(Elt))
6244 NonZeros |= (1 << i);
6249 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6250 if (NumNonZero == 0)
6251 return DAG.getUNDEF(VT);
6253 // Special case for single non-zero, non-undef, element.
6254 if (NumNonZero == 1) {
6255 unsigned Idx = countTrailingZeros(NonZeros);
6256 SDValue Item = Op.getOperand(Idx);
6258 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6259 // the value are obviously zero, truncate the value to i32 and do the
6260 // insertion that way. Only do this if the value is non-constant or if the
6261 // value is a constant being inserted into element 0. It is cheaper to do
6262 // a constant pool load than it is to do a movd + shuffle.
6263 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6264 (!IsAllConstants || Idx == 0)) {
6265 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6267 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6268 EVT VecVT = MVT::v4i32;
6269 unsigned VecElts = 4;
6271 // Truncate the value (which may itself be a constant) to i32, and
6272 // convert it to a vector with movd (S2V+shuffle to zero extend).
6273 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6274 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6275 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6277 // Now we have our 32-bit value zero extended in the low element of
6278 // a vector. If Idx != 0, swizzle it into place.
6280 SmallVector<int, 4> Mask;
6281 Mask.push_back(Idx);
6282 for (unsigned i = 1; i != VecElts; ++i)
6284 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6287 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6291 // If we have a constant or non-constant insertion into the low element of
6292 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6293 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6294 // depending on what the source datatype is.
6297 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6299 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6300 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6301 if (VT.is256BitVector() || VT.is512BitVector()) {
6302 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6303 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6304 Item, DAG.getIntPtrConstant(0));
6306 assert(VT.is128BitVector() && "Expected an SSE value type!");
6307 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6308 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6309 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6312 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6313 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6314 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6315 if (VT.is256BitVector()) {
6316 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6317 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6319 assert(VT.is128BitVector() && "Expected an SSE value type!");
6320 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6322 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6326 // Is it a vector logical left shift?
6327 if (NumElems == 2 && Idx == 1 &&
6328 X86::isZeroNode(Op.getOperand(0)) &&
6329 !X86::isZeroNode(Op.getOperand(1))) {
6330 unsigned NumBits = VT.getSizeInBits();
6331 return getVShift(true, VT,
6332 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6333 VT, Op.getOperand(1)),
6334 NumBits/2, DAG, *this, dl);
6337 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6340 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6341 // is a non-constant being inserted into an element other than the low one,
6342 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6343 // movd/movss) to move this into the low element, then shuffle it into
6345 if (EVTBits == 32) {
6346 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6348 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6349 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6350 SmallVector<int, 8> MaskVec;
6351 for (unsigned i = 0; i != NumElems; ++i)
6352 MaskVec.push_back(i == Idx ? 0 : 1);
6353 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6357 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6358 if (Values.size() == 1) {
6359 if (EVTBits == 32) {
6360 // Instead of a shuffle like this:
6361 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6362 // Check if it's possible to issue this instead.
6363 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6364 unsigned Idx = countTrailingZeros(NonZeros);
6365 SDValue Item = Op.getOperand(Idx);
6366 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6367 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6372 // A vector full of immediates; various special cases are already
6373 // handled, so this is best done with a single constant-pool load.
6377 // For AVX-length vectors, build the individual 128-bit pieces and use
6378 // shuffles to put them in place.
6379 if (VT.is256BitVector() || VT.is512BitVector()) {
6380 SmallVector<SDValue, 64> V;
6381 for (unsigned i = 0; i != NumElems; ++i)
6382 V.push_back(Op.getOperand(i));
6384 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6386 // Build both the lower and upper subvector.
6387 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6388 makeArrayRef(&V[0], NumElems/2));
6389 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6390 makeArrayRef(&V[NumElems / 2], NumElems/2));
6392 // Recreate the wider vector with the lower and upper part.
6393 if (VT.is256BitVector())
6394 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6395 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6398 // Let legalizer expand 2-wide build_vectors.
6399 if (EVTBits == 64) {
6400 if (NumNonZero == 1) {
6401 // One half is zero or undef.
6402 unsigned Idx = countTrailingZeros(NonZeros);
6403 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6404 Op.getOperand(Idx));
6405 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6410 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6411 if (EVTBits == 8 && NumElems == 16) {
6412 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6414 if (V.getNode()) return V;
6417 if (EVTBits == 16 && NumElems == 8) {
6418 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6420 if (V.getNode()) return V;
6423 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6424 if (EVTBits == 32 && NumElems == 4) {
6425 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6426 NumZero, DAG, Subtarget, *this);
6431 // If element VT is == 32 bits, turn it into a number of shuffles.
6432 SmallVector<SDValue, 8> V(NumElems);
6433 if (NumElems == 4 && NumZero > 0) {
6434 for (unsigned i = 0; i < 4; ++i) {
6435 bool isZero = !(NonZeros & (1 << i));
6437 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6439 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6442 for (unsigned i = 0; i < 2; ++i) {
6443 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6446 V[i] = V[i*2]; // Must be a zero vector.
6449 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6452 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6455 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6460 bool Reverse1 = (NonZeros & 0x3) == 2;
6461 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6465 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6466 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6468 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6471 if (Values.size() > 1 && VT.is128BitVector()) {
6472 // Check for a build vector of consecutive loads.
6473 for (unsigned i = 0; i < NumElems; ++i)
6474 V[i] = Op.getOperand(i);
6476 // Check for elements which are consecutive loads.
6477 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6481 // Check for a build vector from mostly shuffle plus few inserting.
6482 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6486 // For SSE 4.1, use insertps to put the high elements into the low element.
6487 if (getSubtarget()->hasSSE41()) {
6489 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6490 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6492 Result = DAG.getUNDEF(VT);
6494 for (unsigned i = 1; i < NumElems; ++i) {
6495 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6496 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6497 Op.getOperand(i), DAG.getIntPtrConstant(i));
6502 // Otherwise, expand into a number of unpckl*, start by extending each of
6503 // our (non-undef) elements to the full vector width with the element in the
6504 // bottom slot of the vector (which generates no code for SSE).
6505 for (unsigned i = 0; i < NumElems; ++i) {
6506 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6507 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6509 V[i] = DAG.getUNDEF(VT);
6512 // Next, we iteratively mix elements, e.g. for v4f32:
6513 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6514 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6515 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6516 unsigned EltStride = NumElems >> 1;
6517 while (EltStride != 0) {
6518 for (unsigned i = 0; i < EltStride; ++i) {
6519 // If V[i+EltStride] is undef and this is the first round of mixing,
6520 // then it is safe to just drop this shuffle: V[i] is already in the
6521 // right place, the one element (since it's the first round) being
6522 // inserted as undef can be dropped. This isn't safe for successive
6523 // rounds because they will permute elements within both vectors.
6524 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6525 EltStride == NumElems/2)
6528 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6537 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6538 // to create 256-bit vectors from two other 128-bit ones.
6539 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6541 MVT ResVT = Op.getSimpleValueType();
6543 assert((ResVT.is256BitVector() ||
6544 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6546 SDValue V1 = Op.getOperand(0);
6547 SDValue V2 = Op.getOperand(1);
6548 unsigned NumElems = ResVT.getVectorNumElements();
6549 if(ResVT.is256BitVector())
6550 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6552 if (Op.getNumOperands() == 4) {
6553 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6554 ResVT.getVectorNumElements()/2);
6555 SDValue V3 = Op.getOperand(2);
6556 SDValue V4 = Op.getOperand(3);
6557 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6558 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6560 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6563 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6564 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6565 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6566 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6567 Op.getNumOperands() == 4)));
6569 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6570 // from two other 128-bit ones.
6572 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6573 return LowerAVXCONCAT_VECTORS(Op, DAG);
6576 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6577 bool hasInt256, unsigned *MaskOut = nullptr) {
6578 MVT EltVT = VT.getVectorElementType();
6580 // There is no blend with immediate in AVX-512.
6581 if (VT.is512BitVector())
6584 if (!hasSSE41 || EltVT == MVT::i8)
6586 if (!hasInt256 && VT == MVT::v16i16)
6589 unsigned MaskValue = 0;
6590 unsigned NumElems = VT.getVectorNumElements();
6591 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6592 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6593 unsigned NumElemsInLane = NumElems / NumLanes;
6595 // Blend for v16i16 should be symetric for the both lanes.
6596 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6598 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6599 int EltIdx = MaskVals[i];
6601 if ((EltIdx < 0 || EltIdx == (int)i) &&
6602 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6605 if (((unsigned)EltIdx == (i + NumElems)) &&
6606 (SndLaneEltIdx < 0 ||
6607 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6608 MaskValue |= (1 << i);
6614 *MaskOut = MaskValue;
6618 // Try to lower a shuffle node into a simple blend instruction.
6619 // This function assumes isBlendMask returns true for this
6620 // SuffleVectorSDNode
6621 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6623 const X86Subtarget *Subtarget,
6624 SelectionDAG &DAG) {
6625 MVT VT = SVOp->getSimpleValueType(0);
6626 MVT EltVT = VT.getVectorElementType();
6627 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6628 Subtarget->hasInt256() && "Trying to lower a "
6629 "VECTOR_SHUFFLE to a Blend but "
6630 "with the wrong mask"));
6631 SDValue V1 = SVOp->getOperand(0);
6632 SDValue V2 = SVOp->getOperand(1);
6634 unsigned NumElems = VT.getVectorNumElements();
6636 // Convert i32 vectors to floating point if it is not AVX2.
6637 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6639 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6640 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6642 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6643 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6646 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6647 DAG.getConstant(MaskValue, MVT::i32));
6648 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6651 /// In vector type \p VT, return true if the element at index \p InputIdx
6652 /// falls on a different 128-bit lane than \p OutputIdx.
6653 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6654 unsigned OutputIdx) {
6655 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6656 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6659 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6660 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6661 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6662 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6664 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6665 SelectionDAG &DAG) {
6666 MVT VT = V1.getSimpleValueType();
6667 assert(VT.is128BitVector() || VT.is256BitVector());
6669 MVT EltVT = VT.getVectorElementType();
6670 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6671 unsigned NumElts = VT.getVectorNumElements();
6673 SmallVector<SDValue, 32> PshufbMask;
6674 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6675 int InputIdx = MaskVals[OutputIdx];
6676 unsigned InputByteIdx;
6678 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6679 InputByteIdx = 0x80;
6681 // Cross lane is not allowed.
6682 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6684 InputByteIdx = InputIdx * EltSizeInBytes;
6685 // Index is an byte offset within the 128-bit lane.
6686 InputByteIdx &= 0xf;
6689 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6690 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6691 if (InputByteIdx != 0x80)
6696 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6698 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6699 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6700 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6703 // v8i16 shuffles - Prefer shuffles in the following order:
6704 // 1. [all] pshuflw, pshufhw, optional move
6705 // 2. [ssse3] 1 x pshufb
6706 // 3. [ssse3] 2 x pshufb + 1 x por
6707 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6709 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6710 SelectionDAG &DAG) {
6711 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6712 SDValue V1 = SVOp->getOperand(0);
6713 SDValue V2 = SVOp->getOperand(1);
6715 SmallVector<int, 8> MaskVals;
6717 // Determine if more than 1 of the words in each of the low and high quadwords
6718 // of the result come from the same quadword of one of the two inputs. Undef
6719 // mask values count as coming from any quadword, for better codegen.
6721 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6722 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6723 unsigned LoQuad[] = { 0, 0, 0, 0 };
6724 unsigned HiQuad[] = { 0, 0, 0, 0 };
6725 // Indices of quads used.
6726 std::bitset<4> InputQuads;
6727 for (unsigned i = 0; i < 8; ++i) {
6728 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6729 int EltIdx = SVOp->getMaskElt(i);
6730 MaskVals.push_back(EltIdx);
6739 InputQuads.set(EltIdx / 4);
6742 int BestLoQuad = -1;
6743 unsigned MaxQuad = 1;
6744 for (unsigned i = 0; i < 4; ++i) {
6745 if (LoQuad[i] > MaxQuad) {
6747 MaxQuad = LoQuad[i];
6751 int BestHiQuad = -1;
6753 for (unsigned i = 0; i < 4; ++i) {
6754 if (HiQuad[i] > MaxQuad) {
6756 MaxQuad = HiQuad[i];
6760 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6761 // of the two input vectors, shuffle them into one input vector so only a
6762 // single pshufb instruction is necessary. If there are more than 2 input
6763 // quads, disable the next transformation since it does not help SSSE3.
6764 bool V1Used = InputQuads[0] || InputQuads[1];
6765 bool V2Used = InputQuads[2] || InputQuads[3];
6766 if (Subtarget->hasSSSE3()) {
6767 if (InputQuads.count() == 2 && V1Used && V2Used) {
6768 BestLoQuad = InputQuads[0] ? 0 : 1;
6769 BestHiQuad = InputQuads[2] ? 2 : 3;
6771 if (InputQuads.count() > 2) {
6777 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6778 // the shuffle mask. If a quad is scored as -1, that means that it contains
6779 // words from all 4 input quadwords.
6781 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6783 BestLoQuad < 0 ? 0 : BestLoQuad,
6784 BestHiQuad < 0 ? 1 : BestHiQuad
6786 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6787 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6788 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6789 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6791 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6792 // source words for the shuffle, to aid later transformations.
6793 bool AllWordsInNewV = true;
6794 bool InOrder[2] = { true, true };
6795 for (unsigned i = 0; i != 8; ++i) {
6796 int idx = MaskVals[i];
6798 InOrder[i/4] = false;
6799 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6801 AllWordsInNewV = false;
6805 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6806 if (AllWordsInNewV) {
6807 for (int i = 0; i != 8; ++i) {
6808 int idx = MaskVals[i];
6811 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6812 if ((idx != i) && idx < 4)
6814 if ((idx != i) && idx > 3)
6823 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6824 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6825 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6826 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6827 unsigned TargetMask = 0;
6828 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6829 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6830 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6831 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6832 getShufflePSHUFLWImmediate(SVOp);
6833 V1 = NewV.getOperand(0);
6834 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6838 // Promote splats to a larger type which usually leads to more efficient code.
6839 // FIXME: Is this true if pshufb is available?
6840 if (SVOp->isSplat())
6841 return PromoteSplat(SVOp, DAG);
6843 // If we have SSSE3, and all words of the result are from 1 input vector,
6844 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6845 // is present, fall back to case 4.
6846 if (Subtarget->hasSSSE3()) {
6847 SmallVector<SDValue,16> pshufbMask;
6849 // If we have elements from both input vectors, set the high bit of the
6850 // shuffle mask element to zero out elements that come from V2 in the V1
6851 // mask, and elements that come from V1 in the V2 mask, so that the two
6852 // results can be OR'd together.
6853 bool TwoInputs = V1Used && V2Used;
6854 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6856 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6858 // Calculate the shuffle mask for the second input, shuffle it, and
6859 // OR it with the first shuffled input.
6860 CommuteVectorShuffleMask(MaskVals, 8);
6861 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6862 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6863 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6866 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6867 // and update MaskVals with new element order.
6868 std::bitset<8> InOrder;
6869 if (BestLoQuad >= 0) {
6870 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6871 for (int i = 0; i != 4; ++i) {
6872 int idx = MaskVals[i];
6875 } else if ((idx / 4) == BestLoQuad) {
6880 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6883 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6884 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6885 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6887 getShufflePSHUFLWImmediate(SVOp), DAG);
6891 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6892 // and update MaskVals with the new element order.
6893 if (BestHiQuad >= 0) {
6894 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6895 for (unsigned i = 4; i != 8; ++i) {
6896 int idx = MaskVals[i];
6899 } else if ((idx / 4) == BestHiQuad) {
6900 MaskV[i] = (idx & 3) + 4;
6904 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6907 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6908 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6909 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6911 getShufflePSHUFHWImmediate(SVOp), DAG);
6915 // In case BestHi & BestLo were both -1, which means each quadword has a word
6916 // from each of the four input quadwords, calculate the InOrder bitvector now
6917 // before falling through to the insert/extract cleanup.
6918 if (BestLoQuad == -1 && BestHiQuad == -1) {
6920 for (int i = 0; i != 8; ++i)
6921 if (MaskVals[i] < 0 || MaskVals[i] == i)
6925 // The other elements are put in the right place using pextrw and pinsrw.
6926 for (unsigned i = 0; i != 8; ++i) {
6929 int EltIdx = MaskVals[i];
6932 SDValue ExtOp = (EltIdx < 8) ?
6933 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6934 DAG.getIntPtrConstant(EltIdx)) :
6935 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6936 DAG.getIntPtrConstant(EltIdx - 8));
6937 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6938 DAG.getIntPtrConstant(i));
6943 /// \brief v16i16 shuffles
6945 /// FIXME: We only support generation of a single pshufb currently. We can
6946 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6947 /// well (e.g 2 x pshufb + 1 x por).
6949 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6950 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6951 SDValue V1 = SVOp->getOperand(0);
6952 SDValue V2 = SVOp->getOperand(1);
6955 if (V2.getOpcode() != ISD::UNDEF)
6958 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6959 return getPSHUFB(MaskVals, V1, dl, DAG);
6962 // v16i8 shuffles - Prefer shuffles in the following order:
6963 // 1. [ssse3] 1 x pshufb
6964 // 2. [ssse3] 2 x pshufb + 1 x por
6965 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6966 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6967 const X86Subtarget* Subtarget,
6968 SelectionDAG &DAG) {
6969 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6970 SDValue V1 = SVOp->getOperand(0);
6971 SDValue V2 = SVOp->getOperand(1);
6973 ArrayRef<int> MaskVals = SVOp->getMask();
6975 // Promote splats to a larger type which usually leads to more efficient code.
6976 // FIXME: Is this true if pshufb is available?
6977 if (SVOp->isSplat())
6978 return PromoteSplat(SVOp, DAG);
6980 // If we have SSSE3, case 1 is generated when all result bytes come from
6981 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6982 // present, fall back to case 3.
6984 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6985 if (Subtarget->hasSSSE3()) {
6986 SmallVector<SDValue,16> pshufbMask;
6988 // If all result elements are from one input vector, then only translate
6989 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6991 // Otherwise, we have elements from both input vectors, and must zero out
6992 // elements that come from V2 in the first mask, and V1 in the second mask
6993 // so that we can OR them together.
6994 for (unsigned i = 0; i != 16; ++i) {
6995 int EltIdx = MaskVals[i];
6996 if (EltIdx < 0 || EltIdx >= 16)
6998 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7000 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
7001 DAG.getNode(ISD::BUILD_VECTOR, dl,
7002 MVT::v16i8, pshufbMask));
7004 // As PSHUFB will zero elements with negative indices, it's safe to ignore
7005 // the 2nd operand if it's undefined or zero.
7006 if (V2.getOpcode() == ISD::UNDEF ||
7007 ISD::isBuildVectorAllZeros(V2.getNode()))
7010 // Calculate the shuffle mask for the second input, shuffle it, and
7011 // OR it with the first shuffled input.
7013 for (unsigned i = 0; i != 16; ++i) {
7014 int EltIdx = MaskVals[i];
7015 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
7016 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7018 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
7019 DAG.getNode(ISD::BUILD_VECTOR, dl,
7020 MVT::v16i8, pshufbMask));
7021 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7024 // No SSSE3 - Calculate in place words and then fix all out of place words
7025 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
7026 // the 16 different words that comprise the two doublequadword input vectors.
7027 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7028 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7030 for (int i = 0; i != 8; ++i) {
7031 int Elt0 = MaskVals[i*2];
7032 int Elt1 = MaskVals[i*2+1];
7034 // This word of the result is all undef, skip it.
7035 if (Elt0 < 0 && Elt1 < 0)
7038 // This word of the result is already in the correct place, skip it.
7039 if ((Elt0 == i*2) && (Elt1 == i*2+1))
7042 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7043 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7046 // If Elt0 and Elt1 are defined, are consecutive, and can be load
7047 // using a single extract together, load it and store it.
7048 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7049 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7050 DAG.getIntPtrConstant(Elt1 / 2));
7051 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7052 DAG.getIntPtrConstant(i));
7056 // If Elt1 is defined, extract it from the appropriate source. If the
7057 // source byte is not also odd, shift the extracted word left 8 bits
7058 // otherwise clear the bottom 8 bits if we need to do an or.
7060 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7061 DAG.getIntPtrConstant(Elt1 / 2));
7062 if ((Elt1 & 1) == 0)
7063 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7065 TLI.getShiftAmountTy(InsElt.getValueType())));
7067 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7068 DAG.getConstant(0xFF00, MVT::i16));
7070 // If Elt0 is defined, extract it from the appropriate source. If the
7071 // source byte is not also even, shift the extracted word right 8 bits. If
7072 // Elt1 was also defined, OR the extracted values together before
7073 // inserting them in the result.
7075 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7076 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7077 if ((Elt0 & 1) != 0)
7078 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7080 TLI.getShiftAmountTy(InsElt0.getValueType())));
7082 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7083 DAG.getConstant(0x00FF, MVT::i16));
7084 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7087 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7088 DAG.getIntPtrConstant(i));
7090 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7093 // v32i8 shuffles - Translate to VPSHUFB if possible.
7095 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7096 const X86Subtarget *Subtarget,
7097 SelectionDAG &DAG) {
7098 MVT VT = SVOp->getSimpleValueType(0);
7099 SDValue V1 = SVOp->getOperand(0);
7100 SDValue V2 = SVOp->getOperand(1);
7102 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7104 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7105 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7106 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7108 // VPSHUFB may be generated if
7109 // (1) one of input vector is undefined or zeroinitializer.
7110 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7111 // And (2) the mask indexes don't cross the 128-bit lane.
7112 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7113 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7116 if (V1IsAllZero && !V2IsAllZero) {
7117 CommuteVectorShuffleMask(MaskVals, 32);
7120 return getPSHUFB(MaskVals, V1, dl, DAG);
7123 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7124 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7125 /// done when every pair / quad of shuffle mask elements point to elements in
7126 /// the right sequence. e.g.
7127 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7129 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7130 SelectionDAG &DAG) {
7131 MVT VT = SVOp->getSimpleValueType(0);
7133 unsigned NumElems = VT.getVectorNumElements();
7136 switch (VT.SimpleTy) {
7137 default: llvm_unreachable("Unexpected!");
7140 return SDValue(SVOp, 0);
7141 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7142 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7143 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7144 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7145 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7146 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7149 SmallVector<int, 8> MaskVec;
7150 for (unsigned i = 0; i != NumElems; i += Scale) {
7152 for (unsigned j = 0; j != Scale; ++j) {
7153 int EltIdx = SVOp->getMaskElt(i+j);
7157 StartIdx = (EltIdx / Scale);
7158 if (EltIdx != (int)(StartIdx*Scale + j))
7161 MaskVec.push_back(StartIdx);
7164 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7165 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7166 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7169 /// getVZextMovL - Return a zero-extending vector move low node.
7171 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7172 SDValue SrcOp, SelectionDAG &DAG,
7173 const X86Subtarget *Subtarget, SDLoc dl) {
7174 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7175 LoadSDNode *LD = nullptr;
7176 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7177 LD = dyn_cast<LoadSDNode>(SrcOp);
7179 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7181 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7182 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7183 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7184 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7185 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7187 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7188 return DAG.getNode(ISD::BITCAST, dl, VT,
7189 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7190 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7198 return DAG.getNode(ISD::BITCAST, dl, VT,
7199 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7200 DAG.getNode(ISD::BITCAST, dl,
7204 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7205 /// which could not be matched by any known target speficic shuffle
7207 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7209 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7210 if (NewOp.getNode())
7213 MVT VT = SVOp->getSimpleValueType(0);
7215 unsigned NumElems = VT.getVectorNumElements();
7216 unsigned NumLaneElems = NumElems / 2;
7219 MVT EltVT = VT.getVectorElementType();
7220 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7223 SmallVector<int, 16> Mask;
7224 for (unsigned l = 0; l < 2; ++l) {
7225 // Build a shuffle mask for the output, discovering on the fly which
7226 // input vectors to use as shuffle operands (recorded in InputUsed).
7227 // If building a suitable shuffle vector proves too hard, then bail
7228 // out with UseBuildVector set.
7229 bool UseBuildVector = false;
7230 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7231 unsigned LaneStart = l * NumLaneElems;
7232 for (unsigned i = 0; i != NumLaneElems; ++i) {
7233 // The mask element. This indexes into the input.
7234 int Idx = SVOp->getMaskElt(i+LaneStart);
7236 // the mask element does not index into any input vector.
7241 // The input vector this mask element indexes into.
7242 int Input = Idx / NumLaneElems;
7244 // Turn the index into an offset from the start of the input vector.
7245 Idx -= Input * NumLaneElems;
7247 // Find or create a shuffle vector operand to hold this input.
7249 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7250 if (InputUsed[OpNo] == Input)
7251 // This input vector is already an operand.
7253 if (InputUsed[OpNo] < 0) {
7254 // Create a new operand for this input vector.
7255 InputUsed[OpNo] = Input;
7260 if (OpNo >= array_lengthof(InputUsed)) {
7261 // More than two input vectors used! Give up on trying to create a
7262 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7263 UseBuildVector = true;
7267 // Add the mask index for the new shuffle vector.
7268 Mask.push_back(Idx + OpNo * NumLaneElems);
7271 if (UseBuildVector) {
7272 SmallVector<SDValue, 16> SVOps;
7273 for (unsigned i = 0; i != NumLaneElems; ++i) {
7274 // The mask element. This indexes into the input.
7275 int Idx = SVOp->getMaskElt(i+LaneStart);
7277 SVOps.push_back(DAG.getUNDEF(EltVT));
7281 // The input vector this mask element indexes into.
7282 int Input = Idx / NumElems;
7284 // Turn the index into an offset from the start of the input vector.
7285 Idx -= Input * NumElems;
7287 // Extract the vector element by hand.
7288 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7289 SVOp->getOperand(Input),
7290 DAG.getIntPtrConstant(Idx)));
7293 // Construct the output using a BUILD_VECTOR.
7294 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7295 } else if (InputUsed[0] < 0) {
7296 // No input vectors were used! The result is undefined.
7297 Output[l] = DAG.getUNDEF(NVT);
7299 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7300 (InputUsed[0] % 2) * NumLaneElems,
7302 // If only one input was used, use an undefined vector for the other.
7303 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7304 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7305 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7306 // At least one input vector was used. Create a new shuffle vector.
7307 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7313 // Concatenate the result back
7314 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7317 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7318 /// 4 elements, and match them with several different shuffle types.
7320 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7321 SDValue V1 = SVOp->getOperand(0);
7322 SDValue V2 = SVOp->getOperand(1);
7324 MVT VT = SVOp->getSimpleValueType(0);
7326 assert(VT.is128BitVector() && "Unsupported vector size");
7328 std::pair<int, int> Locs[4];
7329 int Mask1[] = { -1, -1, -1, -1 };
7330 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7334 for (unsigned i = 0; i != 4; ++i) {
7335 int Idx = PermMask[i];
7337 Locs[i] = std::make_pair(-1, -1);
7339 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7341 Locs[i] = std::make_pair(0, NumLo);
7345 Locs[i] = std::make_pair(1, NumHi);
7347 Mask1[2+NumHi] = Idx;
7353 if (NumLo <= 2 && NumHi <= 2) {
7354 // If no more than two elements come from either vector. This can be
7355 // implemented with two shuffles. First shuffle gather the elements.
7356 // The second shuffle, which takes the first shuffle as both of its
7357 // vector operands, put the elements into the right order.
7358 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7360 int Mask2[] = { -1, -1, -1, -1 };
7362 for (unsigned i = 0; i != 4; ++i)
7363 if (Locs[i].first != -1) {
7364 unsigned Idx = (i < 2) ? 0 : 4;
7365 Idx += Locs[i].first * 2 + Locs[i].second;
7369 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7372 if (NumLo == 3 || NumHi == 3) {
7373 // Otherwise, we must have three elements from one vector, call it X, and
7374 // one element from the other, call it Y. First, use a shufps to build an
7375 // intermediate vector with the one element from Y and the element from X
7376 // that will be in the same half in the final destination (the indexes don't
7377 // matter). Then, use a shufps to build the final vector, taking the half
7378 // containing the element from Y from the intermediate, and the other half
7381 // Normalize it so the 3 elements come from V1.
7382 CommuteVectorShuffleMask(PermMask, 4);
7386 // Find the element from V2.
7388 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7389 int Val = PermMask[HiIndex];
7396 Mask1[0] = PermMask[HiIndex];
7398 Mask1[2] = PermMask[HiIndex^1];
7400 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7403 Mask1[0] = PermMask[0];
7404 Mask1[1] = PermMask[1];
7405 Mask1[2] = HiIndex & 1 ? 6 : 4;
7406 Mask1[3] = HiIndex & 1 ? 4 : 6;
7407 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7410 Mask1[0] = HiIndex & 1 ? 2 : 0;
7411 Mask1[1] = HiIndex & 1 ? 0 : 2;
7412 Mask1[2] = PermMask[2];
7413 Mask1[3] = PermMask[3];
7418 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7421 // Break it into (shuffle shuffle_hi, shuffle_lo).
7422 int LoMask[] = { -1, -1, -1, -1 };
7423 int HiMask[] = { -1, -1, -1, -1 };
7425 int *MaskPtr = LoMask;
7426 unsigned MaskIdx = 0;
7429 for (unsigned i = 0; i != 4; ++i) {
7436 int Idx = PermMask[i];
7438 Locs[i] = std::make_pair(-1, -1);
7439 } else if (Idx < 4) {
7440 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7441 MaskPtr[LoIdx] = Idx;
7444 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7445 MaskPtr[HiIdx] = Idx;
7450 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7451 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7452 int MaskOps[] = { -1, -1, -1, -1 };
7453 for (unsigned i = 0; i != 4; ++i)
7454 if (Locs[i].first != -1)
7455 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7456 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7459 static bool MayFoldVectorLoad(SDValue V) {
7460 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7461 V = V.getOperand(0);
7463 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7464 V = V.getOperand(0);
7465 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7466 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7467 // BUILD_VECTOR (load), undef
7468 V = V.getOperand(0);
7470 return MayFoldLoad(V);
7474 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7475 MVT VT = Op.getSimpleValueType();
7477 // Canonizalize to v2f64.
7478 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7479 return DAG.getNode(ISD::BITCAST, dl, VT,
7480 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7485 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7487 SDValue V1 = Op.getOperand(0);
7488 SDValue V2 = Op.getOperand(1);
7489 MVT VT = Op.getSimpleValueType();
7491 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7493 if (HasSSE2 && VT == MVT::v2f64)
7494 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7496 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7497 return DAG.getNode(ISD::BITCAST, dl, VT,
7498 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7499 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7500 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7504 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7505 SDValue V1 = Op.getOperand(0);
7506 SDValue V2 = Op.getOperand(1);
7507 MVT VT = Op.getSimpleValueType();
7509 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7510 "unsupported shuffle type");
7512 if (V2.getOpcode() == ISD::UNDEF)
7516 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7520 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7521 SDValue V1 = Op.getOperand(0);
7522 SDValue V2 = Op.getOperand(1);
7523 MVT VT = Op.getSimpleValueType();
7524 unsigned NumElems = VT.getVectorNumElements();
7526 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7527 // operand of these instructions is only memory, so check if there's a
7528 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7530 bool CanFoldLoad = false;
7532 // Trivial case, when V2 comes from a load.
7533 if (MayFoldVectorLoad(V2))
7536 // When V1 is a load, it can be folded later into a store in isel, example:
7537 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7539 // (MOVLPSmr addr:$src1, VR128:$src2)
7540 // So, recognize this potential and also use MOVLPS or MOVLPD
7541 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7544 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7546 if (HasSSE2 && NumElems == 2)
7547 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7550 // If we don't care about the second element, proceed to use movss.
7551 if (SVOp->getMaskElt(1) != -1)
7552 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7555 // movl and movlp will both match v2i64, but v2i64 is never matched by
7556 // movl earlier because we make it strict to avoid messing with the movlp load
7557 // folding logic (see the code above getMOVLP call). Match it here then,
7558 // this is horrible, but will stay like this until we move all shuffle
7559 // matching to x86 specific nodes. Note that for the 1st condition all
7560 // types are matched with movsd.
7562 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7563 // as to remove this logic from here, as much as possible
7564 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7565 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7566 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7569 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7571 // Invert the operand order and use SHUFPS to match it.
7572 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7573 getShuffleSHUFImmediate(SVOp), DAG);
7576 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7577 SelectionDAG &DAG) {
7579 MVT VT = Load->getSimpleValueType(0);
7580 MVT EVT = VT.getVectorElementType();
7581 SDValue Addr = Load->getOperand(1);
7582 SDValue NewAddr = DAG.getNode(
7583 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7584 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7587 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7588 DAG.getMachineFunction().getMachineMemOperand(
7589 Load->getMemOperand(), 0, EVT.getStoreSize()));
7593 // It is only safe to call this function if isINSERTPSMask is true for
7594 // this shufflevector mask.
7595 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7596 SelectionDAG &DAG) {
7597 // Generate an insertps instruction when inserting an f32 from memory onto a
7598 // v4f32 or when copying a member from one v4f32 to another.
7599 // We also use it for transferring i32 from one register to another,
7600 // since it simply copies the same bits.
7601 // If we're transferring an i32 from memory to a specific element in a
7602 // register, we output a generic DAG that will match the PINSRD
7604 MVT VT = SVOp->getSimpleValueType(0);
7605 MVT EVT = VT.getVectorElementType();
7606 SDValue V1 = SVOp->getOperand(0);
7607 SDValue V2 = SVOp->getOperand(1);
7608 auto Mask = SVOp->getMask();
7609 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7610 "unsupported vector type for insertps/pinsrd");
7612 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7613 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7614 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7622 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7625 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7626 "More than one element from V1 and from V2, or no elements from one "
7627 "of the vectors. This case should not have returned true from "
7632 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7635 if (MayFoldLoad(From)) {
7636 // Trivial case, when From comes from a load and is only used by the
7637 // shuffle. Make it use insertps from the vector that we need from that
7640 NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7641 if (!NewLoad.getNode())
7644 if (EVT == MVT::f32) {
7645 // Create this as a scalar to vector to match the instruction pattern.
7646 SDValue LoadScalarToVector =
7647 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7648 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7649 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7651 } else { // EVT == MVT::i32
7652 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7653 // instruction, to match the PINSRD instruction, which loads an i32 to a
7654 // certain vector element.
7655 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7656 DAG.getConstant(DestIndex, MVT::i32));
7660 // Vector-element-to-vector
7661 unsigned SrcIndex = Mask[DestIndex] % 4;
7662 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7663 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7666 // Reduce a vector shuffle to zext.
7667 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7668 SelectionDAG &DAG) {
7669 // PMOVZX is only available from SSE41.
7670 if (!Subtarget->hasSSE41())
7673 MVT VT = Op.getSimpleValueType();
7675 // Only AVX2 support 256-bit vector integer extending.
7676 if (!Subtarget->hasInt256() && VT.is256BitVector())
7679 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7681 SDValue V1 = Op.getOperand(0);
7682 SDValue V2 = Op.getOperand(1);
7683 unsigned NumElems = VT.getVectorNumElements();
7685 // Extending is an unary operation and the element type of the source vector
7686 // won't be equal to or larger than i64.
7687 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7688 VT.getVectorElementType() == MVT::i64)
7691 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7692 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7693 while ((1U << Shift) < NumElems) {
7694 if (SVOp->getMaskElt(1U << Shift) == 1)
7697 // The maximal ratio is 8, i.e. from i8 to i64.
7702 // Check the shuffle mask.
7703 unsigned Mask = (1U << Shift) - 1;
7704 for (unsigned i = 0; i != NumElems; ++i) {
7705 int EltIdx = SVOp->getMaskElt(i);
7706 if ((i & Mask) != 0 && EltIdx != -1)
7708 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7712 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7713 MVT NeVT = MVT::getIntegerVT(NBits);
7714 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7716 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7719 // Simplify the operand as it's prepared to be fed into shuffle.
7720 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7721 if (V1.getOpcode() == ISD::BITCAST &&
7722 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7723 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7724 V1.getOperand(0).getOperand(0)
7725 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7726 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7727 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7728 ConstantSDNode *CIdx =
7729 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7730 // If it's foldable, i.e. normal load with single use, we will let code
7731 // selection to fold it. Otherwise, we will short the conversion sequence.
7732 if (CIdx && CIdx->getZExtValue() == 0 &&
7733 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7734 MVT FullVT = V.getSimpleValueType();
7735 MVT V1VT = V1.getSimpleValueType();
7736 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7737 // The "ext_vec_elt" node is wider than the result node.
7738 // In this case we should extract subvector from V.
7739 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7740 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7741 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7742 FullVT.getVectorNumElements()/Ratio);
7743 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7744 DAG.getIntPtrConstant(0));
7746 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7750 return DAG.getNode(ISD::BITCAST, DL, VT,
7751 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7754 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7755 SelectionDAG &DAG) {
7756 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7757 MVT VT = Op.getSimpleValueType();
7759 SDValue V1 = Op.getOperand(0);
7760 SDValue V2 = Op.getOperand(1);
7762 if (isZeroShuffle(SVOp))
7763 return getZeroVector(VT, Subtarget, DAG, dl);
7765 // Handle splat operations
7766 if (SVOp->isSplat()) {
7767 // Use vbroadcast whenever the splat comes from a foldable load
7768 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7769 if (Broadcast.getNode())
7773 // Check integer expanding shuffles.
7774 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7775 if (NewOp.getNode())
7778 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7780 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7782 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7783 if (NewOp.getNode())
7784 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7785 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7786 // FIXME: Figure out a cleaner way to do this.
7787 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7788 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7789 if (NewOp.getNode()) {
7790 MVT NewVT = NewOp.getSimpleValueType();
7791 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7792 NewVT, true, false))
7793 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7796 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7797 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7798 if (NewOp.getNode()) {
7799 MVT NewVT = NewOp.getSimpleValueType();
7800 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7801 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7810 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7811 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7812 SDValue V1 = Op.getOperand(0);
7813 SDValue V2 = Op.getOperand(1);
7814 MVT VT = Op.getSimpleValueType();
7816 unsigned NumElems = VT.getVectorNumElements();
7817 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7818 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7819 bool V1IsSplat = false;
7820 bool V2IsSplat = false;
7821 bool HasSSE2 = Subtarget->hasSSE2();
7822 bool HasFp256 = Subtarget->hasFp256();
7823 bool HasInt256 = Subtarget->hasInt256();
7824 MachineFunction &MF = DAG.getMachineFunction();
7825 bool OptForSize = MF.getFunction()->getAttributes().
7826 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7828 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7830 if (V1IsUndef && V2IsUndef)
7831 return DAG.getUNDEF(VT);
7833 // When we create a shuffle node we put the UNDEF node to second operand,
7834 // but in some cases the first operand may be transformed to UNDEF.
7835 // In this case we should just commute the node.
7837 return CommuteVectorShuffle(SVOp, DAG);
7839 // Vector shuffle lowering takes 3 steps:
7841 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7842 // narrowing and commutation of operands should be handled.
7843 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7845 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7846 // so the shuffle can be broken into other shuffles and the legalizer can
7847 // try the lowering again.
7849 // The general idea is that no vector_shuffle operation should be left to
7850 // be matched during isel, all of them must be converted to a target specific
7853 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7854 // narrowing and commutation of operands should be handled. The actual code
7855 // doesn't include all of those, work in progress...
7856 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7857 if (NewOp.getNode())
7860 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7862 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7863 // unpckh_undef). Only use pshufd if speed is more important than size.
7864 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7865 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7866 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7867 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7869 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7870 V2IsUndef && MayFoldVectorLoad(V1))
7871 return getMOVDDup(Op, dl, V1, DAG);
7873 if (isMOVHLPS_v_undef_Mask(M, VT))
7874 return getMOVHighToLow(Op, dl, DAG);
7876 // Use to match splats
7877 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7878 (VT == MVT::v2f64 || VT == MVT::v2i64))
7879 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7881 if (isPSHUFDMask(M, VT)) {
7882 // The actual implementation will match the mask in the if above and then
7883 // during isel it can match several different instructions, not only pshufd
7884 // as its name says, sad but true, emulate the behavior for now...
7885 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7886 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7888 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7890 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7891 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7893 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7894 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7897 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7901 if (isPALIGNRMask(M, VT, Subtarget))
7902 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7903 getShufflePALIGNRImmediate(SVOp),
7906 // Check if this can be converted into a logical shift.
7907 bool isLeft = false;
7910 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7911 if (isShift && ShVal.hasOneUse()) {
7912 // If the shifted value has multiple uses, it may be cheaper to use
7913 // v_set0 + movlhps or movhlps, etc.
7914 MVT EltVT = VT.getVectorElementType();
7915 ShAmt *= EltVT.getSizeInBits();
7916 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7919 if (isMOVLMask(M, VT)) {
7920 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7921 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7922 if (!isMOVLPMask(M, VT)) {
7923 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7924 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7926 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7927 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7931 // FIXME: fold these into legal mask.
7932 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7933 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7935 if (isMOVHLPSMask(M, VT))
7936 return getMOVHighToLow(Op, dl, DAG);
7938 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7939 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7941 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7942 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7944 if (isMOVLPMask(M, VT))
7945 return getMOVLP(Op, dl, DAG, HasSSE2);
7947 if (ShouldXformToMOVHLPS(M, VT) ||
7948 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7949 return CommuteVectorShuffle(SVOp, DAG);
7952 // No better options. Use a vshldq / vsrldq.
7953 MVT EltVT = VT.getVectorElementType();
7954 ShAmt *= EltVT.getSizeInBits();
7955 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7958 bool Commuted = false;
7959 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7960 // 1,1,1,1 -> v8i16 though.
7961 V1IsSplat = isSplatVector(V1.getNode());
7962 V2IsSplat = isSplatVector(V2.getNode());
7964 // Canonicalize the splat or undef, if present, to be on the RHS.
7965 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7966 CommuteVectorShuffleMask(M, NumElems);
7968 std::swap(V1IsSplat, V2IsSplat);
7972 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7973 // Shuffling low element of v1 into undef, just return v1.
7976 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7977 // the instruction selector will not match, so get a canonical MOVL with
7978 // swapped operands to undo the commute.
7979 return getMOVL(DAG, dl, VT, V2, V1);
7982 if (isUNPCKLMask(M, VT, HasInt256))
7983 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7985 if (isUNPCKHMask(M, VT, HasInt256))
7986 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7989 // Normalize mask so all entries that point to V2 points to its first
7990 // element then try to match unpck{h|l} again. If match, return a
7991 // new vector_shuffle with the corrected mask.p
7992 SmallVector<int, 8> NewMask(M.begin(), M.end());
7993 NormalizeMask(NewMask, NumElems);
7994 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7995 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7996 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7997 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8001 // Commute is back and try unpck* again.
8002 // FIXME: this seems wrong.
8003 CommuteVectorShuffleMask(M, NumElems);
8005 std::swap(V1IsSplat, V2IsSplat);
8007 if (isUNPCKLMask(M, VT, HasInt256))
8008 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8010 if (isUNPCKHMask(M, VT, HasInt256))
8011 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8014 // Normalize the node to match x86 shuffle ops if needed
8015 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
8016 return CommuteVectorShuffle(SVOp, DAG);
8018 // The checks below are all present in isShuffleMaskLegal, but they are
8019 // inlined here right now to enable us to directly emit target specific
8020 // nodes, and remove one by one until they don't return Op anymore.
8022 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
8023 SVOp->getSplatIndex() == 0 && V2IsUndef) {
8024 if (VT == MVT::v2f64 || VT == MVT::v2i64)
8025 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8028 if (isPSHUFHWMask(M, VT, HasInt256))
8029 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8030 getShufflePSHUFHWImmediate(SVOp),
8033 if (isPSHUFLWMask(M, VT, HasInt256))
8034 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8035 getShufflePSHUFLWImmediate(SVOp),
8038 if (isSHUFPMask(M, VT))
8039 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8040 getShuffleSHUFImmediate(SVOp), DAG);
8042 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8043 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8044 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8045 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8047 //===--------------------------------------------------------------------===//
8048 // Generate target specific nodes for 128 or 256-bit shuffles only
8049 // supported in the AVX instruction set.
8052 // Handle VMOVDDUPY permutations
8053 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8054 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8056 // Handle VPERMILPS/D* permutations
8057 if (isVPERMILPMask(M, VT)) {
8058 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8059 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8060 getShuffleSHUFImmediate(SVOp), DAG);
8061 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8062 getShuffleSHUFImmediate(SVOp), DAG);
8066 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8067 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8068 Idx*(NumElems/2), DAG, dl);
8070 // Handle VPERM2F128/VPERM2I128 permutations
8071 if (isVPERM2X128Mask(M, VT, HasFp256))
8072 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8073 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8076 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8078 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8080 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8081 return getINSERTPS(SVOp, dl, DAG);
8084 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8085 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8087 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8088 VT.is512BitVector()) {
8089 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8090 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8091 SmallVector<SDValue, 16> permclMask;
8092 for (unsigned i = 0; i != NumElems; ++i) {
8093 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8096 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8098 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8099 return DAG.getNode(X86ISD::VPERMV, dl, VT,
8100 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8101 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8102 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8105 //===--------------------------------------------------------------------===//
8106 // Since no target specific shuffle was selected for this generic one,
8107 // lower it into other known shuffles. FIXME: this isn't true yet, but
8108 // this is the plan.
8111 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8112 if (VT == MVT::v8i16) {
8113 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8114 if (NewOp.getNode())
8118 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8119 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8120 if (NewOp.getNode())
8124 if (VT == MVT::v16i8) {
8125 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8126 if (NewOp.getNode())
8130 if (VT == MVT::v32i8) {
8131 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8132 if (NewOp.getNode())
8136 // Handle all 128-bit wide vectors with 4 elements, and match them with
8137 // several different shuffle types.
8138 if (NumElems == 4 && VT.is128BitVector())
8139 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8141 // Handle general 256-bit shuffles
8142 if (VT.is256BitVector())
8143 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8148 // This function assumes its argument is a BUILD_VECTOR of constants or
8149 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8151 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8152 unsigned &MaskValue) {
8154 unsigned NumElems = BuildVector->getNumOperands();
8155 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8156 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8157 unsigned NumElemsInLane = NumElems / NumLanes;
8159 // Blend for v16i16 should be symetric for the both lanes.
8160 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8161 SDValue EltCond = BuildVector->getOperand(i);
8162 SDValue SndLaneEltCond =
8163 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8165 int Lane1Cond = -1, Lane2Cond = -1;
8166 if (isa<ConstantSDNode>(EltCond))
8167 Lane1Cond = !isZero(EltCond);
8168 if (isa<ConstantSDNode>(SndLaneEltCond))
8169 Lane2Cond = !isZero(SndLaneEltCond);
8171 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8172 // Lane1Cond != 0, means we want the first argument.
8173 // Lane1Cond == 0, means we want the second argument.
8174 // The encoding of this argument is 0 for the first argument, 1
8175 // for the second. Therefore, invert the condition.
8176 MaskValue |= !Lane1Cond << i;
8177 else if (Lane1Cond < 0)
8178 MaskValue |= !Lane2Cond << i;
8185 // Try to lower a vselect node into a simple blend instruction.
8186 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8187 SelectionDAG &DAG) {
8188 SDValue Cond = Op.getOperand(0);
8189 SDValue LHS = Op.getOperand(1);
8190 SDValue RHS = Op.getOperand(2);
8192 MVT VT = Op.getSimpleValueType();
8193 MVT EltVT = VT.getVectorElementType();
8194 unsigned NumElems = VT.getVectorNumElements();
8196 // There is no blend with immediate in AVX-512.
8197 if (VT.is512BitVector())
8200 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8202 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8205 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8208 // Check the mask for BLEND and build the value.
8209 unsigned MaskValue = 0;
8210 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8213 // Convert i32 vectors to floating point if it is not AVX2.
8214 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8216 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8217 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8219 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8220 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8223 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8224 DAG.getConstant(MaskValue, MVT::i32));
8225 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8228 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8229 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8230 if (BlendOp.getNode())
8233 // Some types for vselect were previously set to Expand, not Legal or
8234 // Custom. Return an empty SDValue so we fall-through to Expand, after
8235 // the Custom lowering phase.
8236 MVT VT = Op.getSimpleValueType();
8237 switch (VT.SimpleTy) {
8245 // We couldn't create a "Blend with immediate" node.
8246 // This node should still be legal, but we'll have to emit a blendv*
8251 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8252 MVT VT = Op.getSimpleValueType();
8255 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8258 if (VT.getSizeInBits() == 8) {
8259 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8260 Op.getOperand(0), Op.getOperand(1));
8261 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8262 DAG.getValueType(VT));
8263 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8266 if (VT.getSizeInBits() == 16) {
8267 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8268 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8270 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8271 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8272 DAG.getNode(ISD::BITCAST, dl,
8276 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8277 Op.getOperand(0), Op.getOperand(1));
8278 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8279 DAG.getValueType(VT));
8280 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8283 if (VT == MVT::f32) {
8284 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8285 // the result back to FR32 register. It's only worth matching if the
8286 // result has a single use which is a store or a bitcast to i32. And in
8287 // the case of a store, it's not worth it if the index is a constant 0,
8288 // because a MOVSSmr can be used instead, which is smaller and faster.
8289 if (!Op.hasOneUse())
8291 SDNode *User = *Op.getNode()->use_begin();
8292 if ((User->getOpcode() != ISD::STORE ||
8293 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8294 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8295 (User->getOpcode() != ISD::BITCAST ||
8296 User->getValueType(0) != MVT::i32))
8298 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8299 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8302 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8305 if (VT == MVT::i32 || VT == MVT::i64) {
8306 // ExtractPS/pextrq works with constant index.
8307 if (isa<ConstantSDNode>(Op.getOperand(1)))
8313 /// Extract one bit from mask vector, like v16i1 or v8i1.
8314 /// AVX-512 feature.
8316 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8317 SDValue Vec = Op.getOperand(0);
8319 MVT VecVT = Vec.getSimpleValueType();
8320 SDValue Idx = Op.getOperand(1);
8321 MVT EltVT = Op.getSimpleValueType();
8323 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8325 // variable index can't be handled in mask registers,
8326 // extend vector to VR512
8327 if (!isa<ConstantSDNode>(Idx)) {
8328 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8329 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8330 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8331 ExtVT.getVectorElementType(), Ext, Idx);
8332 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8335 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8336 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8337 unsigned MaxSift = rc->getSize()*8 - 1;
8338 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8339 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8340 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8341 DAG.getConstant(MaxSift, MVT::i8));
8342 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8343 DAG.getIntPtrConstant(0));
8347 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8348 SelectionDAG &DAG) const {
8350 SDValue Vec = Op.getOperand(0);
8351 MVT VecVT = Vec.getSimpleValueType();
8352 SDValue Idx = Op.getOperand(1);
8354 if (Op.getSimpleValueType() == MVT::i1)
8355 return ExtractBitFromMaskVector(Op, DAG);
8357 if (!isa<ConstantSDNode>(Idx)) {
8358 if (VecVT.is512BitVector() ||
8359 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8360 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8363 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8364 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8365 MaskEltVT.getSizeInBits());
8367 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8368 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8369 getZeroVector(MaskVT, Subtarget, DAG, dl),
8370 Idx, DAG.getConstant(0, getPointerTy()));
8371 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8372 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8373 Perm, DAG.getConstant(0, getPointerTy()));
8378 // If this is a 256-bit vector result, first extract the 128-bit vector and
8379 // then extract the element from the 128-bit vector.
8380 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8382 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8383 // Get the 128-bit vector.
8384 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8385 MVT EltVT = VecVT.getVectorElementType();
8387 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8389 //if (IdxVal >= NumElems/2)
8390 // IdxVal -= NumElems/2;
8391 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8392 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8393 DAG.getConstant(IdxVal, MVT::i32));
8396 assert(VecVT.is128BitVector() && "Unexpected vector length");
8398 if (Subtarget->hasSSE41()) {
8399 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8404 MVT VT = Op.getSimpleValueType();
8405 // TODO: handle v16i8.
8406 if (VT.getSizeInBits() == 16) {
8407 SDValue Vec = Op.getOperand(0);
8408 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8410 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8411 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8412 DAG.getNode(ISD::BITCAST, dl,
8415 // Transform it so it match pextrw which produces a 32-bit result.
8416 MVT EltVT = MVT::i32;
8417 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8418 Op.getOperand(0), Op.getOperand(1));
8419 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8420 DAG.getValueType(VT));
8421 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8424 if (VT.getSizeInBits() == 32) {
8425 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8429 // SHUFPS the element to the lowest double word, then movss.
8430 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8431 MVT VVT = Op.getOperand(0).getSimpleValueType();
8432 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8433 DAG.getUNDEF(VVT), Mask);
8434 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8435 DAG.getIntPtrConstant(0));
8438 if (VT.getSizeInBits() == 64) {
8439 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8440 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8441 // to match extract_elt for f64.
8442 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8446 // UNPCKHPD the element to the lowest double word, then movsd.
8447 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8448 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8449 int Mask[2] = { 1, -1 };
8450 MVT VVT = Op.getOperand(0).getSimpleValueType();
8451 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8452 DAG.getUNDEF(VVT), Mask);
8453 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8454 DAG.getIntPtrConstant(0));
8460 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8461 MVT VT = Op.getSimpleValueType();
8462 MVT EltVT = VT.getVectorElementType();
8465 SDValue N0 = Op.getOperand(0);
8466 SDValue N1 = Op.getOperand(1);
8467 SDValue N2 = Op.getOperand(2);
8469 if (!VT.is128BitVector())
8472 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8473 isa<ConstantSDNode>(N2)) {
8475 if (VT == MVT::v8i16)
8476 Opc = X86ISD::PINSRW;
8477 else if (VT == MVT::v16i8)
8478 Opc = X86ISD::PINSRB;
8480 Opc = X86ISD::PINSRB;
8482 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8484 if (N1.getValueType() != MVT::i32)
8485 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8486 if (N2.getValueType() != MVT::i32)
8487 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8488 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8491 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8492 // Bits [7:6] of the constant are the source select. This will always be
8493 // zero here. The DAG Combiner may combine an extract_elt index into these
8494 // bits. For example (insert (extract, 3), 2) could be matched by putting
8495 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8496 // Bits [5:4] of the constant are the destination select. This is the
8497 // value of the incoming immediate.
8498 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8499 // combine either bitwise AND or insert of float 0.0 to set these bits.
8500 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8501 // Create this as a scalar to vector..
8502 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8503 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8506 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8507 // PINSR* works with constant index.
8513 /// Insert one bit to mask vector, like v16i1 or v8i1.
8514 /// AVX-512 feature.
8516 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8518 SDValue Vec = Op.getOperand(0);
8519 SDValue Elt = Op.getOperand(1);
8520 SDValue Idx = Op.getOperand(2);
8521 MVT VecVT = Vec.getSimpleValueType();
8523 if (!isa<ConstantSDNode>(Idx)) {
8524 // Non constant index. Extend source and destination,
8525 // insert element and then truncate the result.
8526 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8527 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8528 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8529 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8530 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8531 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8534 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8535 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8536 if (Vec.getOpcode() == ISD::UNDEF)
8537 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8538 DAG.getConstant(IdxVal, MVT::i8));
8539 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8540 unsigned MaxSift = rc->getSize()*8 - 1;
8541 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8542 DAG.getConstant(MaxSift, MVT::i8));
8543 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8544 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8545 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8548 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8549 MVT VT = Op.getSimpleValueType();
8550 MVT EltVT = VT.getVectorElementType();
8552 if (EltVT == MVT::i1)
8553 return InsertBitToMaskVector(Op, DAG);
8556 SDValue N0 = Op.getOperand(0);
8557 SDValue N1 = Op.getOperand(1);
8558 SDValue N2 = Op.getOperand(2);
8560 // If this is a 256-bit vector result, first extract the 128-bit vector,
8561 // insert the element into the extracted half and then place it back.
8562 if (VT.is256BitVector() || VT.is512BitVector()) {
8563 if (!isa<ConstantSDNode>(N2))
8566 // Get the desired 128-bit vector half.
8567 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8568 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8570 // Insert the element into the desired half.
8571 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8572 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8574 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8575 DAG.getConstant(IdxIn128, MVT::i32));
8577 // Insert the changed part back to the 256-bit vector
8578 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8581 if (Subtarget->hasSSE41())
8582 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8584 if (EltVT == MVT::i8)
8587 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8588 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8589 // as its second argument.
8590 if (N1.getValueType() != MVT::i32)
8591 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8592 if (N2.getValueType() != MVT::i32)
8593 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8594 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8599 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8601 MVT OpVT = Op.getSimpleValueType();
8603 // If this is a 256-bit vector result, first insert into a 128-bit
8604 // vector and then insert into the 256-bit vector.
8605 if (!OpVT.is128BitVector()) {
8606 // Insert into a 128-bit vector.
8607 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8608 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8609 OpVT.getVectorNumElements() / SizeFactor);
8611 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8613 // Insert the 128-bit vector.
8614 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8617 if (OpVT == MVT::v1i64 &&
8618 Op.getOperand(0).getValueType() == MVT::i64)
8619 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8621 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8622 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8623 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8624 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8627 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8628 // a simple subregister reference or explicit instructions to grab
8629 // upper bits of a vector.
8630 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8631 SelectionDAG &DAG) {
8633 SDValue In = Op.getOperand(0);
8634 SDValue Idx = Op.getOperand(1);
8635 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8636 MVT ResVT = Op.getSimpleValueType();
8637 MVT InVT = In.getSimpleValueType();
8639 if (Subtarget->hasFp256()) {
8640 if (ResVT.is128BitVector() &&
8641 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8642 isa<ConstantSDNode>(Idx)) {
8643 return Extract128BitVector(In, IdxVal, DAG, dl);
8645 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8646 isa<ConstantSDNode>(Idx)) {
8647 return Extract256BitVector(In, IdxVal, DAG, dl);
8653 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8654 // simple superregister reference or explicit instructions to insert
8655 // the upper bits of a vector.
8656 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8657 SelectionDAG &DAG) {
8658 if (Subtarget->hasFp256()) {
8659 SDLoc dl(Op.getNode());
8660 SDValue Vec = Op.getNode()->getOperand(0);
8661 SDValue SubVec = Op.getNode()->getOperand(1);
8662 SDValue Idx = Op.getNode()->getOperand(2);
8664 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8665 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8666 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8667 isa<ConstantSDNode>(Idx)) {
8668 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8669 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8672 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8673 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8674 isa<ConstantSDNode>(Idx)) {
8675 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8676 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8682 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8683 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8684 // one of the above mentioned nodes. It has to be wrapped because otherwise
8685 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8686 // be used to form addressing mode. These wrapped nodes will be selected
8689 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8690 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8692 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8694 unsigned char OpFlag = 0;
8695 unsigned WrapperKind = X86ISD::Wrapper;
8696 CodeModel::Model M = DAG.getTarget().getCodeModel();
8698 if (Subtarget->isPICStyleRIPRel() &&
8699 (M == CodeModel::Small || M == CodeModel::Kernel))
8700 WrapperKind = X86ISD::WrapperRIP;
8701 else if (Subtarget->isPICStyleGOT())
8702 OpFlag = X86II::MO_GOTOFF;
8703 else if (Subtarget->isPICStyleStubPIC())
8704 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8706 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8708 CP->getOffset(), OpFlag);
8710 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8711 // With PIC, the address is actually $g + Offset.
8713 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8714 DAG.getNode(X86ISD::GlobalBaseReg,
8715 SDLoc(), getPointerTy()),
8722 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8723 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8725 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8727 unsigned char OpFlag = 0;
8728 unsigned WrapperKind = X86ISD::Wrapper;
8729 CodeModel::Model M = DAG.getTarget().getCodeModel();
8731 if (Subtarget->isPICStyleRIPRel() &&
8732 (M == CodeModel::Small || M == CodeModel::Kernel))
8733 WrapperKind = X86ISD::WrapperRIP;
8734 else if (Subtarget->isPICStyleGOT())
8735 OpFlag = X86II::MO_GOTOFF;
8736 else if (Subtarget->isPICStyleStubPIC())
8737 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8739 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8742 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8744 // With PIC, the address is actually $g + Offset.
8746 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8747 DAG.getNode(X86ISD::GlobalBaseReg,
8748 SDLoc(), getPointerTy()),
8755 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8756 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8758 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8760 unsigned char OpFlag = 0;
8761 unsigned WrapperKind = X86ISD::Wrapper;
8762 CodeModel::Model M = DAG.getTarget().getCodeModel();
8764 if (Subtarget->isPICStyleRIPRel() &&
8765 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8766 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8767 OpFlag = X86II::MO_GOTPCREL;
8768 WrapperKind = X86ISD::WrapperRIP;
8769 } else if (Subtarget->isPICStyleGOT()) {
8770 OpFlag = X86II::MO_GOT;
8771 } else if (Subtarget->isPICStyleStubPIC()) {
8772 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8773 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8774 OpFlag = X86II::MO_DARWIN_NONLAZY;
8777 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8780 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8782 // With PIC, the address is actually $g + Offset.
8783 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
8784 !Subtarget->is64Bit()) {
8785 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8786 DAG.getNode(X86ISD::GlobalBaseReg,
8787 SDLoc(), getPointerTy()),
8791 // For symbols that require a load from a stub to get the address, emit the
8793 if (isGlobalStubReference(OpFlag))
8794 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8795 MachinePointerInfo::getGOT(), false, false, false, 0);
8801 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8802 // Create the TargetBlockAddressAddress node.
8803 unsigned char OpFlags =
8804 Subtarget->ClassifyBlockAddressReference();
8805 CodeModel::Model M = DAG.getTarget().getCodeModel();
8806 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8807 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8809 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8812 if (Subtarget->isPICStyleRIPRel() &&
8813 (M == CodeModel::Small || M == CodeModel::Kernel))
8814 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8816 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8818 // With PIC, the address is actually $g + Offset.
8819 if (isGlobalRelativeToPICBase(OpFlags)) {
8820 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8821 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8829 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8830 int64_t Offset, SelectionDAG &DAG) const {
8831 // Create the TargetGlobalAddress node, folding in the constant
8832 // offset if it is legal.
8833 unsigned char OpFlags =
8834 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
8835 CodeModel::Model M = DAG.getTarget().getCodeModel();
8837 if (OpFlags == X86II::MO_NO_FLAG &&
8838 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8839 // A direct static reference to a global.
8840 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8843 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8846 if (Subtarget->isPICStyleRIPRel() &&
8847 (M == CodeModel::Small || M == CodeModel::Kernel))
8848 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8850 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8852 // With PIC, the address is actually $g + Offset.
8853 if (isGlobalRelativeToPICBase(OpFlags)) {
8854 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8855 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8859 // For globals that require a load from a stub to get the address, emit the
8861 if (isGlobalStubReference(OpFlags))
8862 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8863 MachinePointerInfo::getGOT(), false, false, false, 0);
8865 // If there was a non-zero offset that we didn't fold, create an explicit
8868 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8869 DAG.getConstant(Offset, getPointerTy()));
8875 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8876 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8877 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8878 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8882 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8883 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8884 unsigned char OperandFlags, bool LocalDynamic = false) {
8885 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8886 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8888 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8889 GA->getValueType(0),
8893 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8897 SDValue Ops[] = { Chain, TGA, *InFlag };
8898 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8900 SDValue Ops[] = { Chain, TGA };
8901 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8904 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8905 MFI->setAdjustsStack(true);
8907 SDValue Flag = Chain.getValue(1);
8908 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8911 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8913 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8916 SDLoc dl(GA); // ? function entry point might be better
8917 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8918 DAG.getNode(X86ISD::GlobalBaseReg,
8919 SDLoc(), PtrVT), InFlag);
8920 InFlag = Chain.getValue(1);
8922 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8925 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8927 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8929 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8930 X86::RAX, X86II::MO_TLSGD);
8933 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8939 // Get the start address of the TLS block for this module.
8940 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8941 .getInfo<X86MachineFunctionInfo>();
8942 MFI->incNumLocalDynamicTLSAccesses();
8946 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8947 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8950 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8951 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8952 InFlag = Chain.getValue(1);
8953 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8954 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8957 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8961 unsigned char OperandFlags = X86II::MO_DTPOFF;
8962 unsigned WrapperKind = X86ISD::Wrapper;
8963 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8964 GA->getValueType(0),
8965 GA->getOffset(), OperandFlags);
8966 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8968 // Add x@dtpoff with the base.
8969 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8972 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8973 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8974 const EVT PtrVT, TLSModel::Model model,
8975 bool is64Bit, bool isPIC) {
8978 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8979 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8980 is64Bit ? 257 : 256));
8982 SDValue ThreadPointer =
8983 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8984 MachinePointerInfo(Ptr), false, false, false, 0);
8986 unsigned char OperandFlags = 0;
8987 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8989 unsigned WrapperKind = X86ISD::Wrapper;
8990 if (model == TLSModel::LocalExec) {
8991 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8992 } else if (model == TLSModel::InitialExec) {
8994 OperandFlags = X86II::MO_GOTTPOFF;
8995 WrapperKind = X86ISD::WrapperRIP;
8997 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
9000 llvm_unreachable("Unexpected model");
9003 // emit "addl x@ntpoff,%eax" (local exec)
9004 // or "addl x@indntpoff,%eax" (initial exec)
9005 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
9007 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
9008 GA->getOffset(), OperandFlags);
9009 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9011 if (model == TLSModel::InitialExec) {
9012 if (isPIC && !is64Bit) {
9013 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
9014 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
9018 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
9019 MachinePointerInfo::getGOT(), false, false, false, 0);
9022 // The address of the thread local variable is the add of the thread
9023 // pointer with the offset of the variable.
9024 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9028 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9030 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9031 const GlobalValue *GV = GA->getGlobal();
9033 if (Subtarget->isTargetELF()) {
9034 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9037 case TLSModel::GeneralDynamic:
9038 if (Subtarget->is64Bit())
9039 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9040 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9041 case TLSModel::LocalDynamic:
9042 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9043 Subtarget->is64Bit());
9044 case TLSModel::InitialExec:
9045 case TLSModel::LocalExec:
9046 return LowerToTLSExecModel(
9047 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9048 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9050 llvm_unreachable("Unknown TLS model.");
9053 if (Subtarget->isTargetDarwin()) {
9054 // Darwin only has one model of TLS. Lower to that.
9055 unsigned char OpFlag = 0;
9056 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9057 X86ISD::WrapperRIP : X86ISD::Wrapper;
9059 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9061 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9062 !Subtarget->is64Bit();
9064 OpFlag = X86II::MO_TLVP_PIC_BASE;
9066 OpFlag = X86II::MO_TLVP;
9068 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9069 GA->getValueType(0),
9070 GA->getOffset(), OpFlag);
9071 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9073 // With PIC32, the address is actually $g + Offset.
9075 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9076 DAG.getNode(X86ISD::GlobalBaseReg,
9077 SDLoc(), getPointerTy()),
9080 // Lowering the machine isd will make sure everything is in the right
9082 SDValue Chain = DAG.getEntryNode();
9083 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9084 SDValue Args[] = { Chain, Offset };
9085 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9087 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9088 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9089 MFI->setAdjustsStack(true);
9091 // And our return value (tls address) is in the standard call return value
9093 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9094 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9098 if (Subtarget->isTargetKnownWindowsMSVC() ||
9099 Subtarget->isTargetWindowsGNU()) {
9100 // Just use the implicit TLS architecture
9101 // Need to generate someting similar to:
9102 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9104 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
9105 // mov rcx, qword [rdx+rcx*8]
9106 // mov eax, .tls$:tlsvar
9107 // [rax+rcx] contains the address
9108 // Windows 64bit: gs:0x58
9109 // Windows 32bit: fs:__tls_array
9112 SDValue Chain = DAG.getEntryNode();
9114 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9115 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9116 // use its literal value of 0x2C.
9117 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9118 ? Type::getInt8PtrTy(*DAG.getContext(),
9120 : Type::getInt32PtrTy(*DAG.getContext(),
9124 Subtarget->is64Bit()
9125 ? DAG.getIntPtrConstant(0x58)
9126 : (Subtarget->isTargetWindowsGNU()
9127 ? DAG.getIntPtrConstant(0x2C)
9128 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9130 SDValue ThreadPointer =
9131 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9132 MachinePointerInfo(Ptr), false, false, false, 0);
9134 // Load the _tls_index variable
9135 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9136 if (Subtarget->is64Bit())
9137 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9138 IDX, MachinePointerInfo(), MVT::i32,
9141 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9142 false, false, false, 0);
9144 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9146 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9148 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9149 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9150 false, false, false, 0);
9152 // Get the offset of start of .tls section
9153 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9154 GA->getValueType(0),
9155 GA->getOffset(), X86II::MO_SECREL);
9156 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9158 // The address of the thread local variable is the add of the thread
9159 // pointer with the offset of the variable.
9160 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9163 llvm_unreachable("TLS not implemented for this target.");
9166 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9167 /// and take a 2 x i32 value to shift plus a shift amount.
9168 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9169 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9170 MVT VT = Op.getSimpleValueType();
9171 unsigned VTBits = VT.getSizeInBits();
9173 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9174 SDValue ShOpLo = Op.getOperand(0);
9175 SDValue ShOpHi = Op.getOperand(1);
9176 SDValue ShAmt = Op.getOperand(2);
9177 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9178 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9180 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9181 DAG.getConstant(VTBits - 1, MVT::i8));
9182 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9183 DAG.getConstant(VTBits - 1, MVT::i8))
9184 : DAG.getConstant(0, VT);
9187 if (Op.getOpcode() == ISD::SHL_PARTS) {
9188 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9189 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9191 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9192 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9195 // If the shift amount is larger or equal than the width of a part we can't
9196 // rely on the results of shld/shrd. Insert a test and select the appropriate
9197 // values for large shift amounts.
9198 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9199 DAG.getConstant(VTBits, MVT::i8));
9200 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9201 AndNode, DAG.getConstant(0, MVT::i8));
9204 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9205 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9206 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9208 if (Op.getOpcode() == ISD::SHL_PARTS) {
9209 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9210 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9212 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9213 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9216 SDValue Ops[2] = { Lo, Hi };
9217 return DAG.getMergeValues(Ops, dl);
9220 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9221 SelectionDAG &DAG) const {
9222 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9224 if (SrcVT.isVector())
9227 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9228 "Unknown SINT_TO_FP to lower!");
9230 // These are really Legal; return the operand so the caller accepts it as
9232 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9234 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9235 Subtarget->is64Bit()) {
9240 unsigned Size = SrcVT.getSizeInBits()/8;
9241 MachineFunction &MF = DAG.getMachineFunction();
9242 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9243 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9244 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9246 MachinePointerInfo::getFixedStack(SSFI),
9248 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9251 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9253 SelectionDAG &DAG) const {
9257 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9259 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9261 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9263 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9265 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9266 MachineMemOperand *MMO;
9268 int SSFI = FI->getIndex();
9270 DAG.getMachineFunction()
9271 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9272 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9274 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9275 StackSlot = StackSlot.getOperand(1);
9277 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9278 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9280 Tys, Ops, SrcVT, MMO);
9283 Chain = Result.getValue(1);
9284 SDValue InFlag = Result.getValue(2);
9286 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9287 // shouldn't be necessary except that RFP cannot be live across
9288 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9289 MachineFunction &MF = DAG.getMachineFunction();
9290 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9291 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9292 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9293 Tys = DAG.getVTList(MVT::Other);
9295 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9297 MachineMemOperand *MMO =
9298 DAG.getMachineFunction()
9299 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9300 MachineMemOperand::MOStore, SSFISize, SSFISize);
9302 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9303 Ops, Op.getValueType(), MMO);
9304 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9305 MachinePointerInfo::getFixedStack(SSFI),
9306 false, false, false, 0);
9312 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9313 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9314 SelectionDAG &DAG) const {
9315 // This algorithm is not obvious. Here it is what we're trying to output:
9318 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9319 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9323 pshufd $0x4e, %xmm0, %xmm1
9329 LLVMContext *Context = DAG.getContext();
9331 // Build some magic constants.
9332 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9333 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9334 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9336 SmallVector<Constant*,2> CV1;
9338 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9339 APInt(64, 0x4330000000000000ULL))));
9341 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9342 APInt(64, 0x4530000000000000ULL))));
9343 Constant *C1 = ConstantVector::get(CV1);
9344 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9346 // Load the 64-bit value into an XMM register.
9347 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9349 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9350 MachinePointerInfo::getConstantPool(),
9351 false, false, false, 16);
9352 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9353 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9356 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9357 MachinePointerInfo::getConstantPool(),
9358 false, false, false, 16);
9359 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9360 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9363 if (Subtarget->hasSSE3()) {
9364 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9365 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9367 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9368 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9370 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9371 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9375 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9376 DAG.getIntPtrConstant(0));
9379 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9380 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9381 SelectionDAG &DAG) const {
9383 // FP constant to bias correct the final result.
9384 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9387 // Load the 32-bit value into an XMM register.
9388 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9391 // Zero out the upper parts of the register.
9392 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9394 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9395 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9396 DAG.getIntPtrConstant(0));
9398 // Or the load with the bias.
9399 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9400 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9401 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9403 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9404 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9405 MVT::v2f64, Bias)));
9406 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9407 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9408 DAG.getIntPtrConstant(0));
9410 // Subtract the bias.
9411 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9413 // Handle final rounding.
9414 EVT DestVT = Op.getValueType();
9416 if (DestVT.bitsLT(MVT::f64))
9417 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9418 DAG.getIntPtrConstant(0));
9419 if (DestVT.bitsGT(MVT::f64))
9420 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9422 // Handle final rounding.
9426 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9427 SelectionDAG &DAG) const {
9428 SDValue N0 = Op.getOperand(0);
9429 MVT SVT = N0.getSimpleValueType();
9432 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9433 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9434 "Custom UINT_TO_FP is not supported!");
9436 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9437 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9438 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9441 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9442 SelectionDAG &DAG) const {
9443 SDValue N0 = Op.getOperand(0);
9446 if (Op.getValueType().isVector())
9447 return lowerUINT_TO_FP_vec(Op, DAG);
9449 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9450 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9451 // the optimization here.
9452 if (DAG.SignBitIsZero(N0))
9453 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9455 MVT SrcVT = N0.getSimpleValueType();
9456 MVT DstVT = Op.getSimpleValueType();
9457 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9458 return LowerUINT_TO_FP_i64(Op, DAG);
9459 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9460 return LowerUINT_TO_FP_i32(Op, DAG);
9461 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9464 // Make a 64-bit buffer, and use it to build an FILD.
9465 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9466 if (SrcVT == MVT::i32) {
9467 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9468 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9469 getPointerTy(), StackSlot, WordOff);
9470 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9471 StackSlot, MachinePointerInfo(),
9473 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9474 OffsetSlot, MachinePointerInfo(),
9476 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9480 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9481 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9482 StackSlot, MachinePointerInfo(),
9484 // For i64 source, we need to add the appropriate power of 2 if the input
9485 // was negative. This is the same as the optimization in
9486 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9487 // we must be careful to do the computation in x87 extended precision, not
9488 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9489 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9490 MachineMemOperand *MMO =
9491 DAG.getMachineFunction()
9492 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9493 MachineMemOperand::MOLoad, 8, 8);
9495 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9496 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9497 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9500 APInt FF(32, 0x5F800000ULL);
9502 // Check whether the sign bit is set.
9503 SDValue SignSet = DAG.getSetCC(dl,
9504 getSetCCResultType(*DAG.getContext(), MVT::i64),
9505 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9508 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9509 SDValue FudgePtr = DAG.getConstantPool(
9510 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9513 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9514 SDValue Zero = DAG.getIntPtrConstant(0);
9515 SDValue Four = DAG.getIntPtrConstant(4);
9516 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9518 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9520 // Load the value out, extending it from f32 to f80.
9521 // FIXME: Avoid the extend by constructing the right constant pool?
9522 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9523 FudgePtr, MachinePointerInfo::getConstantPool(),
9524 MVT::f32, false, false, 4);
9525 // Extend everything to 80 bits to force it to be done on x87.
9526 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9527 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9530 std::pair<SDValue,SDValue>
9531 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9532 bool IsSigned, bool IsReplace) const {
9535 EVT DstTy = Op.getValueType();
9537 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9538 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9542 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9543 DstTy.getSimpleVT() >= MVT::i16 &&
9544 "Unknown FP_TO_INT to lower!");
9546 // These are really Legal.
9547 if (DstTy == MVT::i32 &&
9548 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9549 return std::make_pair(SDValue(), SDValue());
9550 if (Subtarget->is64Bit() &&
9551 DstTy == MVT::i64 &&
9552 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9553 return std::make_pair(SDValue(), SDValue());
9555 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9556 // stack slot, or into the FTOL runtime function.
9557 MachineFunction &MF = DAG.getMachineFunction();
9558 unsigned MemSize = DstTy.getSizeInBits()/8;
9559 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9560 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9563 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9564 Opc = X86ISD::WIN_FTOL;
9566 switch (DstTy.getSimpleVT().SimpleTy) {
9567 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9568 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9569 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9570 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9573 SDValue Chain = DAG.getEntryNode();
9574 SDValue Value = Op.getOperand(0);
9575 EVT TheVT = Op.getOperand(0).getValueType();
9576 // FIXME This causes a redundant load/store if the SSE-class value is already
9577 // in memory, such as if it is on the callstack.
9578 if (isScalarFPTypeInSSEReg(TheVT)) {
9579 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9580 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9581 MachinePointerInfo::getFixedStack(SSFI),
9583 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9585 Chain, StackSlot, DAG.getValueType(TheVT)
9588 MachineMemOperand *MMO =
9589 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9590 MachineMemOperand::MOLoad, MemSize, MemSize);
9591 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9592 Chain = Value.getValue(1);
9593 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9594 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9597 MachineMemOperand *MMO =
9598 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9599 MachineMemOperand::MOStore, MemSize, MemSize);
9601 if (Opc != X86ISD::WIN_FTOL) {
9602 // Build the FP_TO_INT*_IN_MEM
9603 SDValue Ops[] = { Chain, Value, StackSlot };
9604 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9606 return std::make_pair(FIST, StackSlot);
9608 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9609 DAG.getVTList(MVT::Other, MVT::Glue),
9611 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9612 MVT::i32, ftol.getValue(1));
9613 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9614 MVT::i32, eax.getValue(2));
9615 SDValue Ops[] = { eax, edx };
9616 SDValue pair = IsReplace
9617 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9618 : DAG.getMergeValues(Ops, DL);
9619 return std::make_pair(pair, SDValue());
9623 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9624 const X86Subtarget *Subtarget) {
9625 MVT VT = Op->getSimpleValueType(0);
9626 SDValue In = Op->getOperand(0);
9627 MVT InVT = In.getSimpleValueType();
9630 // Optimize vectors in AVX mode:
9633 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9634 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9635 // Concat upper and lower parts.
9638 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9639 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9640 // Concat upper and lower parts.
9643 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9644 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9645 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9648 if (Subtarget->hasInt256())
9649 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9651 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9652 SDValue Undef = DAG.getUNDEF(InVT);
9653 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9654 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9655 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9657 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9658 VT.getVectorNumElements()/2);
9660 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9661 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9663 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9666 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9667 SelectionDAG &DAG) {
9668 MVT VT = Op->getSimpleValueType(0);
9669 SDValue In = Op->getOperand(0);
9670 MVT InVT = In.getSimpleValueType();
9672 unsigned int NumElts = VT.getVectorNumElements();
9673 if (NumElts != 8 && NumElts != 16)
9676 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9677 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9679 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9680 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9681 // Now we have only mask extension
9682 assert(InVT.getVectorElementType() == MVT::i1);
9683 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9684 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9685 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9686 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9687 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9688 MachinePointerInfo::getConstantPool(),
9689 false, false, false, Alignment);
9691 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9692 if (VT.is512BitVector())
9694 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9697 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9698 SelectionDAG &DAG) {
9699 if (Subtarget->hasFp256()) {
9700 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9708 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9709 SelectionDAG &DAG) {
9711 MVT VT = Op.getSimpleValueType();
9712 SDValue In = Op.getOperand(0);
9713 MVT SVT = In.getSimpleValueType();
9715 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9716 return LowerZERO_EXTEND_AVX512(Op, DAG);
9718 if (Subtarget->hasFp256()) {
9719 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9724 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9725 VT.getVectorNumElements() != SVT.getVectorNumElements());
9729 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9731 MVT VT = Op.getSimpleValueType();
9732 SDValue In = Op.getOperand(0);
9733 MVT InVT = In.getSimpleValueType();
9735 if (VT == MVT::i1) {
9736 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9737 "Invalid scalar TRUNCATE operation");
9738 if (InVT == MVT::i32)
9740 if (InVT.getSizeInBits() == 64)
9741 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9742 else if (InVT.getSizeInBits() < 32)
9743 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9744 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9746 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9747 "Invalid TRUNCATE operation");
9749 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9750 if (VT.getVectorElementType().getSizeInBits() >=8)
9751 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9753 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9754 unsigned NumElts = InVT.getVectorNumElements();
9755 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9756 if (InVT.getSizeInBits() < 512) {
9757 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9758 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9762 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9763 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9764 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9765 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9766 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9767 MachinePointerInfo::getConstantPool(),
9768 false, false, false, Alignment);
9769 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9770 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9771 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9774 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9775 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9776 if (Subtarget->hasInt256()) {
9777 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9778 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9779 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9781 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9782 DAG.getIntPtrConstant(0));
9785 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9786 DAG.getIntPtrConstant(0));
9787 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9788 DAG.getIntPtrConstant(2));
9789 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9790 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9791 static const int ShufMask[] = {0, 2, 4, 6};
9792 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9795 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9796 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9797 if (Subtarget->hasInt256()) {
9798 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9800 SmallVector<SDValue,32> pshufbMask;
9801 for (unsigned i = 0; i < 2; ++i) {
9802 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9803 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9804 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9805 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9806 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9807 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9808 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9809 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9810 for (unsigned j = 0; j < 8; ++j)
9811 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9813 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9814 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9815 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9817 static const int ShufMask[] = {0, 2, -1, -1};
9818 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9820 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9821 DAG.getIntPtrConstant(0));
9822 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9825 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9826 DAG.getIntPtrConstant(0));
9828 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9829 DAG.getIntPtrConstant(4));
9831 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9832 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9835 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9836 -1, -1, -1, -1, -1, -1, -1, -1};
9838 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9839 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9840 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9842 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9843 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9845 // The MOVLHPS Mask:
9846 static const int ShufMask2[] = {0, 1, 4, 5};
9847 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9848 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9851 // Handle truncation of V256 to V128 using shuffles.
9852 if (!VT.is128BitVector() || !InVT.is256BitVector())
9855 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9857 unsigned NumElems = VT.getVectorNumElements();
9858 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9860 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9861 // Prepare truncation shuffle mask
9862 for (unsigned i = 0; i != NumElems; ++i)
9864 SDValue V = DAG.getVectorShuffle(NVT, DL,
9865 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9866 DAG.getUNDEF(NVT), &MaskVec[0]);
9867 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9868 DAG.getIntPtrConstant(0));
9871 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9872 SelectionDAG &DAG) const {
9873 assert(!Op.getSimpleValueType().isVector());
9875 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9876 /*IsSigned=*/ true, /*IsReplace=*/ false);
9877 SDValue FIST = Vals.first, StackSlot = Vals.second;
9878 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9879 if (!FIST.getNode()) return Op;
9881 if (StackSlot.getNode())
9883 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9884 FIST, StackSlot, MachinePointerInfo(),
9885 false, false, false, 0);
9887 // The node is the result.
9891 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9892 SelectionDAG &DAG) const {
9893 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9894 /*IsSigned=*/ false, /*IsReplace=*/ false);
9895 SDValue FIST = Vals.first, StackSlot = Vals.second;
9896 assert(FIST.getNode() && "Unexpected failure");
9898 if (StackSlot.getNode())
9900 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9901 FIST, StackSlot, MachinePointerInfo(),
9902 false, false, false, 0);
9904 // The node is the result.
9908 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9910 MVT VT = Op.getSimpleValueType();
9911 SDValue In = Op.getOperand(0);
9912 MVT SVT = In.getSimpleValueType();
9914 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9916 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9917 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9918 In, DAG.getUNDEF(SVT)));
9921 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9922 LLVMContext *Context = DAG.getContext();
9924 MVT VT = Op.getSimpleValueType();
9926 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9927 if (VT.isVector()) {
9928 EltVT = VT.getVectorElementType();
9929 NumElts = VT.getVectorNumElements();
9932 if (EltVT == MVT::f64)
9933 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9934 APInt(64, ~(1ULL << 63))));
9936 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9937 APInt(32, ~(1U << 31))));
9938 C = ConstantVector::getSplat(NumElts, C);
9939 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9940 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9941 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9942 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9943 MachinePointerInfo::getConstantPool(),
9944 false, false, false, Alignment);
9945 if (VT.isVector()) {
9946 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9947 return DAG.getNode(ISD::BITCAST, dl, VT,
9948 DAG.getNode(ISD::AND, dl, ANDVT,
9949 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9951 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9953 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9956 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9957 LLVMContext *Context = DAG.getContext();
9959 MVT VT = Op.getSimpleValueType();
9961 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9962 if (VT.isVector()) {
9963 EltVT = VT.getVectorElementType();
9964 NumElts = VT.getVectorNumElements();
9967 if (EltVT == MVT::f64)
9968 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9969 APInt(64, 1ULL << 63)));
9971 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9972 APInt(32, 1U << 31)));
9973 C = ConstantVector::getSplat(NumElts, C);
9974 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9975 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9976 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9977 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9978 MachinePointerInfo::getConstantPool(),
9979 false, false, false, Alignment);
9980 if (VT.isVector()) {
9981 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9982 return DAG.getNode(ISD::BITCAST, dl, VT,
9983 DAG.getNode(ISD::XOR, dl, XORVT,
9984 DAG.getNode(ISD::BITCAST, dl, XORVT,
9986 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9989 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9992 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9993 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9994 LLVMContext *Context = DAG.getContext();
9995 SDValue Op0 = Op.getOperand(0);
9996 SDValue Op1 = Op.getOperand(1);
9998 MVT VT = Op.getSimpleValueType();
9999 MVT SrcVT = Op1.getSimpleValueType();
10001 // If second operand is smaller, extend it first.
10002 if (SrcVT.bitsLT(VT)) {
10003 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
10006 // And if it is bigger, shrink it first.
10007 if (SrcVT.bitsGT(VT)) {
10008 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
10012 // At this point the operands and the result should have the same
10013 // type, and that won't be f80 since that is not custom lowered.
10015 // First get the sign bit of second operand.
10016 SmallVector<Constant*,4> CV;
10017 if (SrcVT == MVT::f64) {
10018 const fltSemantics &Sem = APFloat::IEEEdouble;
10019 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
10020 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10022 const fltSemantics &Sem = APFloat::IEEEsingle;
10023 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
10024 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10025 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10026 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10028 Constant *C = ConstantVector::get(CV);
10029 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10030 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10031 MachinePointerInfo::getConstantPool(),
10032 false, false, false, 16);
10033 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10035 // Shift sign bit right or left if the two operands have different types.
10036 if (SrcVT.bitsGT(VT)) {
10037 // Op0 is MVT::f32, Op1 is MVT::f64.
10038 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10039 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10040 DAG.getConstant(32, MVT::i32));
10041 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10042 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10043 DAG.getIntPtrConstant(0));
10046 // Clear first operand sign bit.
10048 if (VT == MVT::f64) {
10049 const fltSemantics &Sem = APFloat::IEEEdouble;
10050 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10051 APInt(64, ~(1ULL << 63)))));
10052 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10054 const fltSemantics &Sem = APFloat::IEEEsingle;
10055 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10056 APInt(32, ~(1U << 31)))));
10057 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10058 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10059 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10061 C = ConstantVector::get(CV);
10062 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10063 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10064 MachinePointerInfo::getConstantPool(),
10065 false, false, false, 16);
10066 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10068 // Or the value with the sign bit.
10069 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10072 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10073 SDValue N0 = Op.getOperand(0);
10075 MVT VT = Op.getSimpleValueType();
10077 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10078 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10079 DAG.getConstant(1, VT));
10080 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10083 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10085 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10086 SelectionDAG &DAG) {
10087 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10089 if (!Subtarget->hasSSE41())
10092 if (!Op->hasOneUse())
10095 SDNode *N = Op.getNode();
10098 SmallVector<SDValue, 8> Opnds;
10099 DenseMap<SDValue, unsigned> VecInMap;
10100 SmallVector<SDValue, 8> VecIns;
10101 EVT VT = MVT::Other;
10103 // Recognize a special case where a vector is casted into wide integer to
10105 Opnds.push_back(N->getOperand(0));
10106 Opnds.push_back(N->getOperand(1));
10108 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10109 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10110 // BFS traverse all OR'd operands.
10111 if (I->getOpcode() == ISD::OR) {
10112 Opnds.push_back(I->getOperand(0));
10113 Opnds.push_back(I->getOperand(1));
10114 // Re-evaluate the number of nodes to be traversed.
10115 e += 2; // 2 more nodes (LHS and RHS) are pushed.
10119 // Quit if a non-EXTRACT_VECTOR_ELT
10120 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10123 // Quit if without a constant index.
10124 SDValue Idx = I->getOperand(1);
10125 if (!isa<ConstantSDNode>(Idx))
10128 SDValue ExtractedFromVec = I->getOperand(0);
10129 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10130 if (M == VecInMap.end()) {
10131 VT = ExtractedFromVec.getValueType();
10132 // Quit if not 128/256-bit vector.
10133 if (!VT.is128BitVector() && !VT.is256BitVector())
10135 // Quit if not the same type.
10136 if (VecInMap.begin() != VecInMap.end() &&
10137 VT != VecInMap.begin()->first.getValueType())
10139 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10140 VecIns.push_back(ExtractedFromVec);
10142 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10145 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10146 "Not extracted from 128-/256-bit vector.");
10148 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10150 for (DenseMap<SDValue, unsigned>::const_iterator
10151 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10152 // Quit if not all elements are used.
10153 if (I->second != FullMask)
10157 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10159 // Cast all vectors into TestVT for PTEST.
10160 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10161 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10163 // If more than one full vectors are evaluated, OR them first before PTEST.
10164 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10165 // Each iteration will OR 2 nodes and append the result until there is only
10166 // 1 node left, i.e. the final OR'd value of all vectors.
10167 SDValue LHS = VecIns[Slot];
10168 SDValue RHS = VecIns[Slot + 1];
10169 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10172 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10173 VecIns.back(), VecIns.back());
10176 /// \brief return true if \c Op has a use that doesn't just read flags.
10177 static bool hasNonFlagsUse(SDValue Op) {
10178 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10180 SDNode *User = *UI;
10181 unsigned UOpNo = UI.getOperandNo();
10182 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10183 // Look pass truncate.
10184 UOpNo = User->use_begin().getOperandNo();
10185 User = *User->use_begin();
10188 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10189 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10195 /// Emit nodes that will be selected as "test Op0,Op0", or something
10197 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10198 SelectionDAG &DAG) const {
10199 if (Op.getValueType() == MVT::i1)
10200 // KORTEST instruction should be selected
10201 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10202 DAG.getConstant(0, Op.getValueType()));
10204 // CF and OF aren't always set the way we want. Determine which
10205 // of these we need.
10206 bool NeedCF = false;
10207 bool NeedOF = false;
10210 case X86::COND_A: case X86::COND_AE:
10211 case X86::COND_B: case X86::COND_BE:
10214 case X86::COND_G: case X86::COND_GE:
10215 case X86::COND_L: case X86::COND_LE:
10216 case X86::COND_O: case X86::COND_NO: {
10217 // Check if we really need to set the
10218 // Overflow flag. If NoSignedWrap is present
10219 // that is not actually needed.
10220 switch (Op->getOpcode()) {
10225 const BinaryWithFlagsSDNode *BinNode =
10226 cast<BinaryWithFlagsSDNode>(Op.getNode());
10227 if (BinNode->hasNoSignedWrap())
10237 // See if we can use the EFLAGS value from the operand instead of
10238 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10239 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10240 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10241 // Emit a CMP with 0, which is the TEST pattern.
10242 //if (Op.getValueType() == MVT::i1)
10243 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10244 // DAG.getConstant(0, MVT::i1));
10245 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10246 DAG.getConstant(0, Op.getValueType()));
10248 unsigned Opcode = 0;
10249 unsigned NumOperands = 0;
10251 // Truncate operations may prevent the merge of the SETCC instruction
10252 // and the arithmetic instruction before it. Attempt to truncate the operands
10253 // of the arithmetic instruction and use a reduced bit-width instruction.
10254 bool NeedTruncation = false;
10255 SDValue ArithOp = Op;
10256 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10257 SDValue Arith = Op->getOperand(0);
10258 // Both the trunc and the arithmetic op need to have one user each.
10259 if (Arith->hasOneUse())
10260 switch (Arith.getOpcode()) {
10267 NeedTruncation = true;
10273 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10274 // which may be the result of a CAST. We use the variable 'Op', which is the
10275 // non-casted variable when we check for possible users.
10276 switch (ArithOp.getOpcode()) {
10278 // Due to an isel shortcoming, be conservative if this add is likely to be
10279 // selected as part of a load-modify-store instruction. When the root node
10280 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10281 // uses of other nodes in the match, such as the ADD in this case. This
10282 // leads to the ADD being left around and reselected, with the result being
10283 // two adds in the output. Alas, even if none our users are stores, that
10284 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10285 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10286 // climbing the DAG back to the root, and it doesn't seem to be worth the
10288 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10289 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10290 if (UI->getOpcode() != ISD::CopyToReg &&
10291 UI->getOpcode() != ISD::SETCC &&
10292 UI->getOpcode() != ISD::STORE)
10295 if (ConstantSDNode *C =
10296 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10297 // An add of one will be selected as an INC.
10298 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10299 Opcode = X86ISD::INC;
10304 // An add of negative one (subtract of one) will be selected as a DEC.
10305 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10306 Opcode = X86ISD::DEC;
10312 // Otherwise use a regular EFLAGS-setting add.
10313 Opcode = X86ISD::ADD;
10318 // If we have a constant logical shift that's only used in a comparison
10319 // against zero turn it into an equivalent AND. This allows turning it into
10320 // a TEST instruction later.
10321 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10322 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10323 EVT VT = Op.getValueType();
10324 unsigned BitWidth = VT.getSizeInBits();
10325 unsigned ShAmt = Op->getConstantOperandVal(1);
10326 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10328 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10329 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10330 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10331 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10333 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10334 DAG.getConstant(Mask, VT));
10335 DAG.ReplaceAllUsesWith(Op, New);
10341 // If the primary and result isn't used, don't bother using X86ISD::AND,
10342 // because a TEST instruction will be better.
10343 if (!hasNonFlagsUse(Op))
10349 // Due to the ISEL shortcoming noted above, be conservative if this op is
10350 // likely to be selected as part of a load-modify-store instruction.
10351 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10352 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10353 if (UI->getOpcode() == ISD::STORE)
10356 // Otherwise use a regular EFLAGS-setting instruction.
10357 switch (ArithOp.getOpcode()) {
10358 default: llvm_unreachable("unexpected operator!");
10359 case ISD::SUB: Opcode = X86ISD::SUB; break;
10360 case ISD::XOR: Opcode = X86ISD::XOR; break;
10361 case ISD::AND: Opcode = X86ISD::AND; break;
10363 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10364 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10365 if (EFLAGS.getNode())
10368 Opcode = X86ISD::OR;
10382 return SDValue(Op.getNode(), 1);
10388 // If we found that truncation is beneficial, perform the truncation and
10390 if (NeedTruncation) {
10391 EVT VT = Op.getValueType();
10392 SDValue WideVal = Op->getOperand(0);
10393 EVT WideVT = WideVal.getValueType();
10394 unsigned ConvertedOp = 0;
10395 // Use a target machine opcode to prevent further DAGCombine
10396 // optimizations that may separate the arithmetic operations
10397 // from the setcc node.
10398 switch (WideVal.getOpcode()) {
10400 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10401 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10402 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10403 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10404 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10408 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10409 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10410 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10411 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10412 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10418 // Emit a CMP with 0, which is the TEST pattern.
10419 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10420 DAG.getConstant(0, Op.getValueType()));
10422 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10423 SmallVector<SDValue, 4> Ops;
10424 for (unsigned i = 0; i != NumOperands; ++i)
10425 Ops.push_back(Op.getOperand(i));
10427 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10428 DAG.ReplaceAllUsesWith(Op, New);
10429 return SDValue(New.getNode(), 1);
10432 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10434 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10435 SDLoc dl, SelectionDAG &DAG) const {
10436 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10437 if (C->getAPIntValue() == 0)
10438 return EmitTest(Op0, X86CC, dl, DAG);
10440 if (Op0.getValueType() == MVT::i1)
10441 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10444 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10445 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10446 // Do the comparison at i32 if it's smaller, besides the Atom case.
10447 // This avoids subregister aliasing issues. Keep the smaller reference
10448 // if we're optimizing for size, however, as that'll allow better folding
10449 // of memory operations.
10450 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10451 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10452 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10453 !Subtarget->isAtom()) {
10454 unsigned ExtendOp =
10455 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10456 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10457 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10459 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10460 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10461 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10463 return SDValue(Sub.getNode(), 1);
10465 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10468 /// Convert a comparison if required by the subtarget.
10469 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10470 SelectionDAG &DAG) const {
10471 // If the subtarget does not support the FUCOMI instruction, floating-point
10472 // comparisons have to be converted.
10473 if (Subtarget->hasCMov() ||
10474 Cmp.getOpcode() != X86ISD::CMP ||
10475 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10476 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10479 // The instruction selector will select an FUCOM instruction instead of
10480 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10481 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10482 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10484 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10485 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10486 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10487 DAG.getConstant(8, MVT::i8));
10488 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10489 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10492 static bool isAllOnes(SDValue V) {
10493 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10494 return C && C->isAllOnesValue();
10497 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10498 /// if it's possible.
10499 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10500 SDLoc dl, SelectionDAG &DAG) const {
10501 SDValue Op0 = And.getOperand(0);
10502 SDValue Op1 = And.getOperand(1);
10503 if (Op0.getOpcode() == ISD::TRUNCATE)
10504 Op0 = Op0.getOperand(0);
10505 if (Op1.getOpcode() == ISD::TRUNCATE)
10506 Op1 = Op1.getOperand(0);
10509 if (Op1.getOpcode() == ISD::SHL)
10510 std::swap(Op0, Op1);
10511 if (Op0.getOpcode() == ISD::SHL) {
10512 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10513 if (And00C->getZExtValue() == 1) {
10514 // If we looked past a truncate, check that it's only truncating away
10516 unsigned BitWidth = Op0.getValueSizeInBits();
10517 unsigned AndBitWidth = And.getValueSizeInBits();
10518 if (BitWidth > AndBitWidth) {
10520 DAG.computeKnownBits(Op0, Zeros, Ones);
10521 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10525 RHS = Op0.getOperand(1);
10527 } else if (Op1.getOpcode() == ISD::Constant) {
10528 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10529 uint64_t AndRHSVal = AndRHS->getZExtValue();
10530 SDValue AndLHS = Op0;
10532 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10533 LHS = AndLHS.getOperand(0);
10534 RHS = AndLHS.getOperand(1);
10537 // Use BT if the immediate can't be encoded in a TEST instruction.
10538 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10540 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10544 if (LHS.getNode()) {
10545 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10546 // instruction. Since the shift amount is in-range-or-undefined, we know
10547 // that doing a bittest on the i32 value is ok. We extend to i32 because
10548 // the encoding for the i16 version is larger than the i32 version.
10549 // Also promote i16 to i32 for performance / code size reason.
10550 if (LHS.getValueType() == MVT::i8 ||
10551 LHS.getValueType() == MVT::i16)
10552 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10554 // If the operand types disagree, extend the shift amount to match. Since
10555 // BT ignores high bits (like shifts) we can use anyextend.
10556 if (LHS.getValueType() != RHS.getValueType())
10557 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10559 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10560 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10561 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10562 DAG.getConstant(Cond, MVT::i8), BT);
10568 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10570 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10575 // SSE Condition code mapping:
10584 switch (SetCCOpcode) {
10585 default: llvm_unreachable("Unexpected SETCC condition");
10587 case ISD::SETEQ: SSECC = 0; break;
10589 case ISD::SETGT: Swap = true; // Fallthrough
10591 case ISD::SETOLT: SSECC = 1; break;
10593 case ISD::SETGE: Swap = true; // Fallthrough
10595 case ISD::SETOLE: SSECC = 2; break;
10596 case ISD::SETUO: SSECC = 3; break;
10598 case ISD::SETNE: SSECC = 4; break;
10599 case ISD::SETULE: Swap = true; // Fallthrough
10600 case ISD::SETUGE: SSECC = 5; break;
10601 case ISD::SETULT: Swap = true; // Fallthrough
10602 case ISD::SETUGT: SSECC = 6; break;
10603 case ISD::SETO: SSECC = 7; break;
10605 case ISD::SETONE: SSECC = 8; break;
10608 std::swap(Op0, Op1);
10613 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10614 // ones, and then concatenate the result back.
10615 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10616 MVT VT = Op.getSimpleValueType();
10618 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10619 "Unsupported value type for operation");
10621 unsigned NumElems = VT.getVectorNumElements();
10623 SDValue CC = Op.getOperand(2);
10625 // Extract the LHS vectors
10626 SDValue LHS = Op.getOperand(0);
10627 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10628 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10630 // Extract the RHS vectors
10631 SDValue RHS = Op.getOperand(1);
10632 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10633 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10635 // Issue the operation on the smaller types and concatenate the result back
10636 MVT EltVT = VT.getVectorElementType();
10637 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10638 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10639 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10640 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10643 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10644 const X86Subtarget *Subtarget) {
10645 SDValue Op0 = Op.getOperand(0);
10646 SDValue Op1 = Op.getOperand(1);
10647 SDValue CC = Op.getOperand(2);
10648 MVT VT = Op.getSimpleValueType();
10651 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10652 Op.getValueType().getScalarType() == MVT::i1 &&
10653 "Cannot set masked compare for this operation");
10655 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10657 bool Unsigned = false;
10660 switch (SetCCOpcode) {
10661 default: llvm_unreachable("Unexpected SETCC condition");
10662 case ISD::SETNE: SSECC = 4; break;
10663 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10664 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10665 case ISD::SETLT: Swap = true; //fall-through
10666 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10667 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10668 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10669 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10670 case ISD::SETULE: Unsigned = true; //fall-through
10671 case ISD::SETLE: SSECC = 2; break;
10675 std::swap(Op0, Op1);
10677 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10678 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10679 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10680 DAG.getConstant(SSECC, MVT::i8));
10683 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10684 /// operand \p Op1. If non-trivial (for example because it's not constant)
10685 /// return an empty value.
10686 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10688 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10692 MVT VT = Op1.getSimpleValueType();
10693 MVT EVT = VT.getVectorElementType();
10694 unsigned n = VT.getVectorNumElements();
10695 SmallVector<SDValue, 8> ULTOp1;
10697 for (unsigned i = 0; i < n; ++i) {
10698 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10699 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10702 // Avoid underflow.
10703 APInt Val = Elt->getAPIntValue();
10707 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10710 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10713 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10714 SelectionDAG &DAG) {
10715 SDValue Op0 = Op.getOperand(0);
10716 SDValue Op1 = Op.getOperand(1);
10717 SDValue CC = Op.getOperand(2);
10718 MVT VT = Op.getSimpleValueType();
10719 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10720 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10725 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10726 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10729 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10730 unsigned Opc = X86ISD::CMPP;
10731 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10732 assert(VT.getVectorNumElements() <= 16);
10733 Opc = X86ISD::CMPM;
10735 // In the two special cases we can't handle, emit two comparisons.
10738 unsigned CombineOpc;
10739 if (SetCCOpcode == ISD::SETUEQ) {
10740 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10742 assert(SetCCOpcode == ISD::SETONE);
10743 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10746 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10747 DAG.getConstant(CC0, MVT::i8));
10748 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10749 DAG.getConstant(CC1, MVT::i8));
10750 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10752 // Handle all other FP comparisons here.
10753 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10754 DAG.getConstant(SSECC, MVT::i8));
10757 // Break 256-bit integer vector compare into smaller ones.
10758 if (VT.is256BitVector() && !Subtarget->hasInt256())
10759 return Lower256IntVSETCC(Op, DAG);
10761 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10762 EVT OpVT = Op1.getValueType();
10763 if (Subtarget->hasAVX512()) {
10764 if (Op1.getValueType().is512BitVector() ||
10765 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10766 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10768 // In AVX-512 architecture setcc returns mask with i1 elements,
10769 // But there is no compare instruction for i8 and i16 elements.
10770 // We are not talking about 512-bit operands in this case, these
10771 // types are illegal.
10773 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10774 OpVT.getVectorElementType().getSizeInBits() >= 8))
10775 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10776 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10779 // We are handling one of the integer comparisons here. Since SSE only has
10780 // GT and EQ comparisons for integer, swapping operands and multiple
10781 // operations may be required for some comparisons.
10783 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10784 bool Subus = false;
10786 switch (SetCCOpcode) {
10787 default: llvm_unreachable("Unexpected SETCC condition");
10788 case ISD::SETNE: Invert = true;
10789 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10790 case ISD::SETLT: Swap = true;
10791 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10792 case ISD::SETGE: Swap = true;
10793 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10794 Invert = true; break;
10795 case ISD::SETULT: Swap = true;
10796 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10797 FlipSigns = true; break;
10798 case ISD::SETUGE: Swap = true;
10799 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10800 FlipSigns = true; Invert = true; break;
10803 // Special case: Use min/max operations for SETULE/SETUGE
10804 MVT VET = VT.getVectorElementType();
10806 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10807 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10810 switch (SetCCOpcode) {
10812 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10813 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10816 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10819 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10820 if (!MinMax && hasSubus) {
10821 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10823 // t = psubus Op0, Op1
10824 // pcmpeq t, <0..0>
10825 switch (SetCCOpcode) {
10827 case ISD::SETULT: {
10828 // If the comparison is against a constant we can turn this into a
10829 // setule. With psubus, setule does not require a swap. This is
10830 // beneficial because the constant in the register is no longer
10831 // destructed as the destination so it can be hoisted out of a loop.
10832 // Only do this pre-AVX since vpcmp* is no longer destructive.
10833 if (Subtarget->hasAVX())
10835 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10836 if (ULEOp1.getNode()) {
10838 Subus = true; Invert = false; Swap = false;
10842 // Psubus is better than flip-sign because it requires no inversion.
10843 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10844 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10848 Opc = X86ISD::SUBUS;
10854 std::swap(Op0, Op1);
10856 // Check that the operation in question is available (most are plain SSE2,
10857 // but PCMPGTQ and PCMPEQQ have different requirements).
10858 if (VT == MVT::v2i64) {
10859 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10860 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10862 // First cast everything to the right type.
10863 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10864 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10866 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10867 // bits of the inputs before performing those operations. The lower
10868 // compare is always unsigned.
10871 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10873 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10874 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10875 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10876 Sign, Zero, Sign, Zero);
10878 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10879 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10881 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10882 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10883 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10885 // Create masks for only the low parts/high parts of the 64 bit integers.
10886 static const int MaskHi[] = { 1, 1, 3, 3 };
10887 static const int MaskLo[] = { 0, 0, 2, 2 };
10888 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10889 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10890 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10892 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10893 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10896 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10898 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10901 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10902 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10903 // pcmpeqd + pshufd + pand.
10904 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10906 // First cast everything to the right type.
10907 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10908 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10911 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10913 // Make sure the lower and upper halves are both all-ones.
10914 static const int Mask[] = { 1, 0, 3, 2 };
10915 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10916 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10919 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10921 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10925 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10926 // bits of the inputs before performing those operations.
10928 EVT EltVT = VT.getVectorElementType();
10929 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10930 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10931 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10934 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10936 // If the logical-not of the result is required, perform that now.
10938 Result = DAG.getNOT(dl, Result, VT);
10941 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10944 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10945 getZeroVector(VT, Subtarget, DAG, dl));
10950 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10952 MVT VT = Op.getSimpleValueType();
10954 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10956 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10957 && "SetCC type must be 8-bit or 1-bit integer");
10958 SDValue Op0 = Op.getOperand(0);
10959 SDValue Op1 = Op.getOperand(1);
10961 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10963 // Optimize to BT if possible.
10964 // Lower (X & (1 << N)) == 0 to BT(X, N).
10965 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10966 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10967 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10968 Op1.getOpcode() == ISD::Constant &&
10969 cast<ConstantSDNode>(Op1)->isNullValue() &&
10970 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10971 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10972 if (NewSetCC.getNode())
10976 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10978 if (Op1.getOpcode() == ISD::Constant &&
10979 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10980 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10981 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10983 // If the input is a setcc, then reuse the input setcc or use a new one with
10984 // the inverted condition.
10985 if (Op0.getOpcode() == X86ISD::SETCC) {
10986 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10987 bool Invert = (CC == ISD::SETNE) ^
10988 cast<ConstantSDNode>(Op1)->isNullValue();
10992 CCode = X86::GetOppositeBranchCondition(CCode);
10993 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10994 DAG.getConstant(CCode, MVT::i8),
10995 Op0.getOperand(1));
10997 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11001 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11002 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11003 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11005 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11006 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11009 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
11010 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
11011 if (X86CC == X86::COND_INVALID)
11014 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
11015 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11016 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11017 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11019 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11023 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11024 static bool isX86LogicalCmp(SDValue Op) {
11025 unsigned Opc = Op.getNode()->getOpcode();
11026 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11027 Opc == X86ISD::SAHF)
11029 if (Op.getResNo() == 1 &&
11030 (Opc == X86ISD::ADD ||
11031 Opc == X86ISD::SUB ||
11032 Opc == X86ISD::ADC ||
11033 Opc == X86ISD::SBB ||
11034 Opc == X86ISD::SMUL ||
11035 Opc == X86ISD::UMUL ||
11036 Opc == X86ISD::INC ||
11037 Opc == X86ISD::DEC ||
11038 Opc == X86ISD::OR ||
11039 Opc == X86ISD::XOR ||
11040 Opc == X86ISD::AND))
11043 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11049 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11050 if (V.getOpcode() != ISD::TRUNCATE)
11053 SDValue VOp0 = V.getOperand(0);
11054 unsigned InBits = VOp0.getValueSizeInBits();
11055 unsigned Bits = V.getValueSizeInBits();
11056 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11059 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11060 bool addTest = true;
11061 SDValue Cond = Op.getOperand(0);
11062 SDValue Op1 = Op.getOperand(1);
11063 SDValue Op2 = Op.getOperand(2);
11065 EVT VT = Op1.getValueType();
11068 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11069 // are available. Otherwise fp cmovs get lowered into a less efficient branch
11070 // sequence later on.
11071 if (Cond.getOpcode() == ISD::SETCC &&
11072 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11073 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11074 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11075 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11076 int SSECC = translateX86FSETCC(
11077 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11080 if (Subtarget->hasAVX512()) {
11081 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11082 DAG.getConstant(SSECC, MVT::i8));
11083 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11085 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11086 DAG.getConstant(SSECC, MVT::i8));
11087 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11088 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11089 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11093 if (Cond.getOpcode() == ISD::SETCC) {
11094 SDValue NewCond = LowerSETCC(Cond, DAG);
11095 if (NewCond.getNode())
11099 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11100 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11101 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11102 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11103 if (Cond.getOpcode() == X86ISD::SETCC &&
11104 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11105 isZero(Cond.getOperand(1).getOperand(1))) {
11106 SDValue Cmp = Cond.getOperand(1);
11108 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11110 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11111 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11112 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11114 SDValue CmpOp0 = Cmp.getOperand(0);
11115 // Apply further optimizations for special cases
11116 // (select (x != 0), -1, 0) -> neg & sbb
11117 // (select (x == 0), 0, -1) -> neg & sbb
11118 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11119 if (YC->isNullValue() &&
11120 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11121 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11122 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11123 DAG.getConstant(0, CmpOp0.getValueType()),
11125 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11126 DAG.getConstant(X86::COND_B, MVT::i8),
11127 SDValue(Neg.getNode(), 1));
11131 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11132 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11133 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11135 SDValue Res = // Res = 0 or -1.
11136 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11137 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11139 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11140 Res = DAG.getNOT(DL, Res, Res.getValueType());
11142 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11143 if (!N2C || !N2C->isNullValue())
11144 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11149 // Look past (and (setcc_carry (cmp ...)), 1).
11150 if (Cond.getOpcode() == ISD::AND &&
11151 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11152 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11153 if (C && C->getAPIntValue() == 1)
11154 Cond = Cond.getOperand(0);
11157 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11158 // setting operand in place of the X86ISD::SETCC.
11159 unsigned CondOpcode = Cond.getOpcode();
11160 if (CondOpcode == X86ISD::SETCC ||
11161 CondOpcode == X86ISD::SETCC_CARRY) {
11162 CC = Cond.getOperand(0);
11164 SDValue Cmp = Cond.getOperand(1);
11165 unsigned Opc = Cmp.getOpcode();
11166 MVT VT = Op.getSimpleValueType();
11168 bool IllegalFPCMov = false;
11169 if (VT.isFloatingPoint() && !VT.isVector() &&
11170 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11171 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11173 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11174 Opc == X86ISD::BT) { // FIXME
11178 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11179 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11180 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11181 Cond.getOperand(0).getValueType() != MVT::i8)) {
11182 SDValue LHS = Cond.getOperand(0);
11183 SDValue RHS = Cond.getOperand(1);
11184 unsigned X86Opcode;
11187 switch (CondOpcode) {
11188 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11189 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11190 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11191 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11192 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11193 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11194 default: llvm_unreachable("unexpected overflowing operator");
11196 if (CondOpcode == ISD::UMULO)
11197 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11200 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11202 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11204 if (CondOpcode == ISD::UMULO)
11205 Cond = X86Op.getValue(2);
11207 Cond = X86Op.getValue(1);
11209 CC = DAG.getConstant(X86Cond, MVT::i8);
11214 // Look pass the truncate if the high bits are known zero.
11215 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11216 Cond = Cond.getOperand(0);
11218 // We know the result of AND is compared against zero. Try to match
11220 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11221 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11222 if (NewSetCC.getNode()) {
11223 CC = NewSetCC.getOperand(0);
11224 Cond = NewSetCC.getOperand(1);
11231 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11232 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11235 // a < b ? -1 : 0 -> RES = ~setcc_carry
11236 // a < b ? 0 : -1 -> RES = setcc_carry
11237 // a >= b ? -1 : 0 -> RES = setcc_carry
11238 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11239 if (Cond.getOpcode() == X86ISD::SUB) {
11240 Cond = ConvertCmpIfNecessary(Cond, DAG);
11241 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11243 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11244 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11245 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11246 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11247 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11248 return DAG.getNOT(DL, Res, Res.getValueType());
11253 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11254 // widen the cmov and push the truncate through. This avoids introducing a new
11255 // branch during isel and doesn't add any extensions.
11256 if (Op.getValueType() == MVT::i8 &&
11257 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11258 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11259 if (T1.getValueType() == T2.getValueType() &&
11260 // Blacklist CopyFromReg to avoid partial register stalls.
11261 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11262 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11263 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11264 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11268 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11269 // condition is true.
11270 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11271 SDValue Ops[] = { Op2, Op1, CC, Cond };
11272 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11275 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11276 MVT VT = Op->getSimpleValueType(0);
11277 SDValue In = Op->getOperand(0);
11278 MVT InVT = In.getSimpleValueType();
11281 unsigned int NumElts = VT.getVectorNumElements();
11282 if (NumElts != 8 && NumElts != 16)
11285 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11286 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11288 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11289 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11291 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11292 Constant *C = ConstantInt::get(*DAG.getContext(),
11293 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11295 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11296 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11297 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11298 MachinePointerInfo::getConstantPool(),
11299 false, false, false, Alignment);
11300 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11301 if (VT.is512BitVector())
11303 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11306 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11307 SelectionDAG &DAG) {
11308 MVT VT = Op->getSimpleValueType(0);
11309 SDValue In = Op->getOperand(0);
11310 MVT InVT = In.getSimpleValueType();
11313 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11314 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11316 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11317 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11318 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11321 if (Subtarget->hasInt256())
11322 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11324 // Optimize vectors in AVX mode
11325 // Sign extend v8i16 to v8i32 and
11328 // Divide input vector into two parts
11329 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11330 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11331 // concat the vectors to original VT
11333 unsigned NumElems = InVT.getVectorNumElements();
11334 SDValue Undef = DAG.getUNDEF(InVT);
11336 SmallVector<int,8> ShufMask1(NumElems, -1);
11337 for (unsigned i = 0; i != NumElems/2; ++i)
11340 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11342 SmallVector<int,8> ShufMask2(NumElems, -1);
11343 for (unsigned i = 0; i != NumElems/2; ++i)
11344 ShufMask2[i] = i + NumElems/2;
11346 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11348 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11349 VT.getVectorNumElements()/2);
11351 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11352 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11354 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11357 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11358 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11359 // from the AND / OR.
11360 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11361 Opc = Op.getOpcode();
11362 if (Opc != ISD::OR && Opc != ISD::AND)
11364 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11365 Op.getOperand(0).hasOneUse() &&
11366 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11367 Op.getOperand(1).hasOneUse());
11370 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11371 // 1 and that the SETCC node has a single use.
11372 static bool isXor1OfSetCC(SDValue Op) {
11373 if (Op.getOpcode() != ISD::XOR)
11375 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11376 if (N1C && N1C->getAPIntValue() == 1) {
11377 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11378 Op.getOperand(0).hasOneUse();
11383 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11384 bool addTest = true;
11385 SDValue Chain = Op.getOperand(0);
11386 SDValue Cond = Op.getOperand(1);
11387 SDValue Dest = Op.getOperand(2);
11390 bool Inverted = false;
11392 if (Cond.getOpcode() == ISD::SETCC) {
11393 // Check for setcc([su]{add,sub,mul}o == 0).
11394 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11395 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11396 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11397 Cond.getOperand(0).getResNo() == 1 &&
11398 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11399 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11400 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11401 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11402 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11403 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11405 Cond = Cond.getOperand(0);
11407 SDValue NewCond = LowerSETCC(Cond, DAG);
11408 if (NewCond.getNode())
11413 // FIXME: LowerXALUO doesn't handle these!!
11414 else if (Cond.getOpcode() == X86ISD::ADD ||
11415 Cond.getOpcode() == X86ISD::SUB ||
11416 Cond.getOpcode() == X86ISD::SMUL ||
11417 Cond.getOpcode() == X86ISD::UMUL)
11418 Cond = LowerXALUO(Cond, DAG);
11421 // Look pass (and (setcc_carry (cmp ...)), 1).
11422 if (Cond.getOpcode() == ISD::AND &&
11423 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11424 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11425 if (C && C->getAPIntValue() == 1)
11426 Cond = Cond.getOperand(0);
11429 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11430 // setting operand in place of the X86ISD::SETCC.
11431 unsigned CondOpcode = Cond.getOpcode();
11432 if (CondOpcode == X86ISD::SETCC ||
11433 CondOpcode == X86ISD::SETCC_CARRY) {
11434 CC = Cond.getOperand(0);
11436 SDValue Cmp = Cond.getOperand(1);
11437 unsigned Opc = Cmp.getOpcode();
11438 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11439 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11443 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11447 // These can only come from an arithmetic instruction with overflow,
11448 // e.g. SADDO, UADDO.
11449 Cond = Cond.getNode()->getOperand(1);
11455 CondOpcode = Cond.getOpcode();
11456 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11457 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11458 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11459 Cond.getOperand(0).getValueType() != MVT::i8)) {
11460 SDValue LHS = Cond.getOperand(0);
11461 SDValue RHS = Cond.getOperand(1);
11462 unsigned X86Opcode;
11465 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11466 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11468 switch (CondOpcode) {
11469 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11471 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11473 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11476 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11477 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11479 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11481 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11484 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11485 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11486 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11487 default: llvm_unreachable("unexpected overflowing operator");
11490 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11491 if (CondOpcode == ISD::UMULO)
11492 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11495 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11497 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11499 if (CondOpcode == ISD::UMULO)
11500 Cond = X86Op.getValue(2);
11502 Cond = X86Op.getValue(1);
11504 CC = DAG.getConstant(X86Cond, MVT::i8);
11508 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11509 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11510 if (CondOpc == ISD::OR) {
11511 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11512 // two branches instead of an explicit OR instruction with a
11514 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11515 isX86LogicalCmp(Cmp)) {
11516 CC = Cond.getOperand(0).getOperand(0);
11517 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11518 Chain, Dest, CC, Cmp);
11519 CC = Cond.getOperand(1).getOperand(0);
11523 } else { // ISD::AND
11524 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11525 // two branches instead of an explicit AND instruction with a
11526 // separate test. However, we only do this if this block doesn't
11527 // have a fall-through edge, because this requires an explicit
11528 // jmp when the condition is false.
11529 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11530 isX86LogicalCmp(Cmp) &&
11531 Op.getNode()->hasOneUse()) {
11532 X86::CondCode CCode =
11533 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11534 CCode = X86::GetOppositeBranchCondition(CCode);
11535 CC = DAG.getConstant(CCode, MVT::i8);
11536 SDNode *User = *Op.getNode()->use_begin();
11537 // Look for an unconditional branch following this conditional branch.
11538 // We need this because we need to reverse the successors in order
11539 // to implement FCMP_OEQ.
11540 if (User->getOpcode() == ISD::BR) {
11541 SDValue FalseBB = User->getOperand(1);
11543 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11544 assert(NewBR == User);
11548 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11549 Chain, Dest, CC, Cmp);
11550 X86::CondCode CCode =
11551 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11552 CCode = X86::GetOppositeBranchCondition(CCode);
11553 CC = DAG.getConstant(CCode, MVT::i8);
11559 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11560 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11561 // It should be transformed during dag combiner except when the condition
11562 // is set by a arithmetics with overflow node.
11563 X86::CondCode CCode =
11564 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11565 CCode = X86::GetOppositeBranchCondition(CCode);
11566 CC = DAG.getConstant(CCode, MVT::i8);
11567 Cond = Cond.getOperand(0).getOperand(1);
11569 } else if (Cond.getOpcode() == ISD::SETCC &&
11570 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11571 // For FCMP_OEQ, we can emit
11572 // two branches instead of an explicit AND instruction with a
11573 // separate test. However, we only do this if this block doesn't
11574 // have a fall-through edge, because this requires an explicit
11575 // jmp when the condition is false.
11576 if (Op.getNode()->hasOneUse()) {
11577 SDNode *User = *Op.getNode()->use_begin();
11578 // Look for an unconditional branch following this conditional branch.
11579 // We need this because we need to reverse the successors in order
11580 // to implement FCMP_OEQ.
11581 if (User->getOpcode() == ISD::BR) {
11582 SDValue FalseBB = User->getOperand(1);
11584 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11585 assert(NewBR == User);
11589 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11590 Cond.getOperand(0), Cond.getOperand(1));
11591 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11592 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11593 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11594 Chain, Dest, CC, Cmp);
11595 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11600 } else if (Cond.getOpcode() == ISD::SETCC &&
11601 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11602 // For FCMP_UNE, we can emit
11603 // two branches instead of an explicit AND instruction with a
11604 // separate test. However, we only do this if this block doesn't
11605 // have a fall-through edge, because this requires an explicit
11606 // jmp when the condition is false.
11607 if (Op.getNode()->hasOneUse()) {
11608 SDNode *User = *Op.getNode()->use_begin();
11609 // Look for an unconditional branch following this conditional branch.
11610 // We need this because we need to reverse the successors in order
11611 // to implement FCMP_UNE.
11612 if (User->getOpcode() == ISD::BR) {
11613 SDValue FalseBB = User->getOperand(1);
11615 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11616 assert(NewBR == User);
11619 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11620 Cond.getOperand(0), Cond.getOperand(1));
11621 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11622 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11623 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11624 Chain, Dest, CC, Cmp);
11625 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11635 // Look pass the truncate if the high bits are known zero.
11636 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11637 Cond = Cond.getOperand(0);
11639 // We know the result of AND is compared against zero. Try to match
11641 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11642 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11643 if (NewSetCC.getNode()) {
11644 CC = NewSetCC.getOperand(0);
11645 Cond = NewSetCC.getOperand(1);
11652 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11653 CC = DAG.getConstant(X86Cond, MVT::i8);
11654 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11656 Cond = ConvertCmpIfNecessary(Cond, DAG);
11657 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11658 Chain, Dest, CC, Cond);
11661 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11662 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11663 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11664 // that the guard pages used by the OS virtual memory manager are allocated in
11665 // correct sequence.
11667 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11668 SelectionDAG &DAG) const {
11669 MachineFunction &MF = DAG.getMachineFunction();
11670 bool SplitStack = MF.shouldSplitStack();
11671 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11676 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11677 SDNode* Node = Op.getNode();
11679 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11680 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11681 " not tell us which reg is the stack pointer!");
11682 EVT VT = Node->getValueType(0);
11683 SDValue Tmp1 = SDValue(Node, 0);
11684 SDValue Tmp2 = SDValue(Node, 1);
11685 SDValue Tmp3 = Node->getOperand(2);
11686 SDValue Chain = Tmp1.getOperand(0);
11688 // Chain the dynamic stack allocation so that it doesn't modify the stack
11689 // pointer when other instructions are using the stack.
11690 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11693 SDValue Size = Tmp2.getOperand(1);
11694 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11695 Chain = SP.getValue(1);
11696 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11697 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
11698 unsigned StackAlign = TFI.getStackAlignment();
11699 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11700 if (Align > StackAlign)
11701 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11702 DAG.getConstant(-(uint64_t)Align, VT));
11703 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11705 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11706 DAG.getIntPtrConstant(0, true), SDValue(),
11709 SDValue Ops[2] = { Tmp1, Tmp2 };
11710 return DAG.getMergeValues(Ops, dl);
11714 SDValue Chain = Op.getOperand(0);
11715 SDValue Size = Op.getOperand(1);
11716 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11717 EVT VT = Op.getNode()->getValueType(0);
11719 bool Is64Bit = Subtarget->is64Bit();
11720 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11723 MachineRegisterInfo &MRI = MF.getRegInfo();
11726 // The 64 bit implementation of segmented stacks needs to clobber both r10
11727 // r11. This makes it impossible to use it along with nested parameters.
11728 const Function *F = MF.getFunction();
11730 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11732 if (I->hasNestAttr())
11733 report_fatal_error("Cannot use segmented stacks with functions that "
11734 "have nested arguments.");
11737 const TargetRegisterClass *AddrRegClass =
11738 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11739 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11740 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11741 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11742 DAG.getRegister(Vreg, SPTy));
11743 SDValue Ops1[2] = { Value, Chain };
11744 return DAG.getMergeValues(Ops1, dl);
11747 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11749 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11750 Flag = Chain.getValue(1);
11751 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11753 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11755 const X86RegisterInfo *RegInfo =
11756 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
11757 unsigned SPReg = RegInfo->getStackRegister();
11758 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11759 Chain = SP.getValue(1);
11762 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11763 DAG.getConstant(-(uint64_t)Align, VT));
11764 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11767 SDValue Ops1[2] = { SP, Chain };
11768 return DAG.getMergeValues(Ops1, dl);
11772 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11773 MachineFunction &MF = DAG.getMachineFunction();
11774 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11776 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11779 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11780 // vastart just stores the address of the VarArgsFrameIndex slot into the
11781 // memory location argument.
11782 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11784 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11785 MachinePointerInfo(SV), false, false, 0);
11789 // gp_offset (0 - 6 * 8)
11790 // fp_offset (48 - 48 + 8 * 16)
11791 // overflow_arg_area (point to parameters coming in memory).
11793 SmallVector<SDValue, 8> MemOps;
11794 SDValue FIN = Op.getOperand(1);
11796 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11797 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11799 FIN, MachinePointerInfo(SV), false, false, 0);
11800 MemOps.push_back(Store);
11803 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11804 FIN, DAG.getIntPtrConstant(4));
11805 Store = DAG.getStore(Op.getOperand(0), DL,
11806 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11808 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11809 MemOps.push_back(Store);
11811 // Store ptr to overflow_arg_area
11812 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11813 FIN, DAG.getIntPtrConstant(4));
11814 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11816 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11817 MachinePointerInfo(SV, 8),
11819 MemOps.push_back(Store);
11821 // Store ptr to reg_save_area.
11822 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11823 FIN, DAG.getIntPtrConstant(8));
11824 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11826 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11827 MachinePointerInfo(SV, 16), false, false, 0);
11828 MemOps.push_back(Store);
11829 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11832 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11833 assert(Subtarget->is64Bit() &&
11834 "LowerVAARG only handles 64-bit va_arg!");
11835 assert((Subtarget->isTargetLinux() ||
11836 Subtarget->isTargetDarwin()) &&
11837 "Unhandled target in LowerVAARG");
11838 assert(Op.getNode()->getNumOperands() == 4);
11839 SDValue Chain = Op.getOperand(0);
11840 SDValue SrcPtr = Op.getOperand(1);
11841 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11842 unsigned Align = Op.getConstantOperandVal(3);
11845 EVT ArgVT = Op.getNode()->getValueType(0);
11846 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11847 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11850 // Decide which area this value should be read from.
11851 // TODO: Implement the AMD64 ABI in its entirety. This simple
11852 // selection mechanism works only for the basic types.
11853 if (ArgVT == MVT::f80) {
11854 llvm_unreachable("va_arg for f80 not yet implemented");
11855 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11856 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11857 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11858 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11860 llvm_unreachable("Unhandled argument type in LowerVAARG");
11863 if (ArgMode == 2) {
11864 // Sanity Check: Make sure using fp_offset makes sense.
11865 assert(!DAG.getTarget().Options.UseSoftFloat &&
11866 !(DAG.getMachineFunction()
11867 .getFunction()->getAttributes()
11868 .hasAttribute(AttributeSet::FunctionIndex,
11869 Attribute::NoImplicitFloat)) &&
11870 Subtarget->hasSSE1());
11873 // Insert VAARG_64 node into the DAG
11874 // VAARG_64 returns two values: Variable Argument Address, Chain
11875 SmallVector<SDValue, 11> InstOps;
11876 InstOps.push_back(Chain);
11877 InstOps.push_back(SrcPtr);
11878 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11879 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11880 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11881 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11882 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11883 VTs, InstOps, MVT::i64,
11884 MachinePointerInfo(SV),
11886 /*Volatile=*/false,
11888 /*WriteMem=*/true);
11889 Chain = VAARG.getValue(1);
11891 // Load the next argument and return it
11892 return DAG.getLoad(ArgVT, dl,
11895 MachinePointerInfo(),
11896 false, false, false, 0);
11899 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11900 SelectionDAG &DAG) {
11901 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11902 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11903 SDValue Chain = Op.getOperand(0);
11904 SDValue DstPtr = Op.getOperand(1);
11905 SDValue SrcPtr = Op.getOperand(2);
11906 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11907 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11910 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11911 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11913 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11916 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11917 // amount is a constant. Takes immediate version of shift as input.
11918 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11919 SDValue SrcOp, uint64_t ShiftAmt,
11920 SelectionDAG &DAG) {
11921 MVT ElementType = VT.getVectorElementType();
11923 // Fold this packed shift into its first operand if ShiftAmt is 0.
11927 // Check for ShiftAmt >= element width
11928 if (ShiftAmt >= ElementType.getSizeInBits()) {
11929 if (Opc == X86ISD::VSRAI)
11930 ShiftAmt = ElementType.getSizeInBits() - 1;
11932 return DAG.getConstant(0, VT);
11935 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11936 && "Unknown target vector shift-by-constant node");
11938 // Fold this packed vector shift into a build vector if SrcOp is a
11939 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11940 if (VT == SrcOp.getSimpleValueType() &&
11941 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11942 SmallVector<SDValue, 8> Elts;
11943 unsigned NumElts = SrcOp->getNumOperands();
11944 ConstantSDNode *ND;
11947 default: llvm_unreachable(nullptr);
11948 case X86ISD::VSHLI:
11949 for (unsigned i=0; i!=NumElts; ++i) {
11950 SDValue CurrentOp = SrcOp->getOperand(i);
11951 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11952 Elts.push_back(CurrentOp);
11955 ND = cast<ConstantSDNode>(CurrentOp);
11956 const APInt &C = ND->getAPIntValue();
11957 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11960 case X86ISD::VSRLI:
11961 for (unsigned i=0; i!=NumElts; ++i) {
11962 SDValue CurrentOp = SrcOp->getOperand(i);
11963 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11964 Elts.push_back(CurrentOp);
11967 ND = cast<ConstantSDNode>(CurrentOp);
11968 const APInt &C = ND->getAPIntValue();
11969 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11972 case X86ISD::VSRAI:
11973 for (unsigned i=0; i!=NumElts; ++i) {
11974 SDValue CurrentOp = SrcOp->getOperand(i);
11975 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11976 Elts.push_back(CurrentOp);
11979 ND = cast<ConstantSDNode>(CurrentOp);
11980 const APInt &C = ND->getAPIntValue();
11981 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11986 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11989 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11992 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11993 // may or may not be a constant. Takes immediate version of shift as input.
11994 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11995 SDValue SrcOp, SDValue ShAmt,
11996 SelectionDAG &DAG) {
11997 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11999 // Catch shift-by-constant.
12000 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12001 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12002 CShAmt->getZExtValue(), DAG);
12004 // Change opcode to non-immediate version
12006 default: llvm_unreachable("Unknown target vector shift node");
12007 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12008 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12009 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12012 // Need to build a vector containing shift amount
12013 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12016 ShOps[1] = DAG.getConstant(0, MVT::i32);
12017 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12018 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12020 // The return type has to be a 128-bit type with the same element
12021 // type as the input type.
12022 MVT EltVT = VT.getVectorElementType();
12023 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12025 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12026 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12029 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12031 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12033 default: return SDValue(); // Don't custom lower most intrinsics.
12034 // Comparison intrinsics.
12035 case Intrinsic::x86_sse_comieq_ss:
12036 case Intrinsic::x86_sse_comilt_ss:
12037 case Intrinsic::x86_sse_comile_ss:
12038 case Intrinsic::x86_sse_comigt_ss:
12039 case Intrinsic::x86_sse_comige_ss:
12040 case Intrinsic::x86_sse_comineq_ss:
12041 case Intrinsic::x86_sse_ucomieq_ss:
12042 case Intrinsic::x86_sse_ucomilt_ss:
12043 case Intrinsic::x86_sse_ucomile_ss:
12044 case Intrinsic::x86_sse_ucomigt_ss:
12045 case Intrinsic::x86_sse_ucomige_ss:
12046 case Intrinsic::x86_sse_ucomineq_ss:
12047 case Intrinsic::x86_sse2_comieq_sd:
12048 case Intrinsic::x86_sse2_comilt_sd:
12049 case Intrinsic::x86_sse2_comile_sd:
12050 case Intrinsic::x86_sse2_comigt_sd:
12051 case Intrinsic::x86_sse2_comige_sd:
12052 case Intrinsic::x86_sse2_comineq_sd:
12053 case Intrinsic::x86_sse2_ucomieq_sd:
12054 case Intrinsic::x86_sse2_ucomilt_sd:
12055 case Intrinsic::x86_sse2_ucomile_sd:
12056 case Intrinsic::x86_sse2_ucomigt_sd:
12057 case Intrinsic::x86_sse2_ucomige_sd:
12058 case Intrinsic::x86_sse2_ucomineq_sd: {
12062 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12063 case Intrinsic::x86_sse_comieq_ss:
12064 case Intrinsic::x86_sse2_comieq_sd:
12065 Opc = X86ISD::COMI;
12068 case Intrinsic::x86_sse_comilt_ss:
12069 case Intrinsic::x86_sse2_comilt_sd:
12070 Opc = X86ISD::COMI;
12073 case Intrinsic::x86_sse_comile_ss:
12074 case Intrinsic::x86_sse2_comile_sd:
12075 Opc = X86ISD::COMI;
12078 case Intrinsic::x86_sse_comigt_ss:
12079 case Intrinsic::x86_sse2_comigt_sd:
12080 Opc = X86ISD::COMI;
12083 case Intrinsic::x86_sse_comige_ss:
12084 case Intrinsic::x86_sse2_comige_sd:
12085 Opc = X86ISD::COMI;
12088 case Intrinsic::x86_sse_comineq_ss:
12089 case Intrinsic::x86_sse2_comineq_sd:
12090 Opc = X86ISD::COMI;
12093 case Intrinsic::x86_sse_ucomieq_ss:
12094 case Intrinsic::x86_sse2_ucomieq_sd:
12095 Opc = X86ISD::UCOMI;
12098 case Intrinsic::x86_sse_ucomilt_ss:
12099 case Intrinsic::x86_sse2_ucomilt_sd:
12100 Opc = X86ISD::UCOMI;
12103 case Intrinsic::x86_sse_ucomile_ss:
12104 case Intrinsic::x86_sse2_ucomile_sd:
12105 Opc = X86ISD::UCOMI;
12108 case Intrinsic::x86_sse_ucomigt_ss:
12109 case Intrinsic::x86_sse2_ucomigt_sd:
12110 Opc = X86ISD::UCOMI;
12113 case Intrinsic::x86_sse_ucomige_ss:
12114 case Intrinsic::x86_sse2_ucomige_sd:
12115 Opc = X86ISD::UCOMI;
12118 case Intrinsic::x86_sse_ucomineq_ss:
12119 case Intrinsic::x86_sse2_ucomineq_sd:
12120 Opc = X86ISD::UCOMI;
12125 SDValue LHS = Op.getOperand(1);
12126 SDValue RHS = Op.getOperand(2);
12127 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12128 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12129 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12130 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12131 DAG.getConstant(X86CC, MVT::i8), Cond);
12132 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12135 // Arithmetic intrinsics.
12136 case Intrinsic::x86_sse2_pmulu_dq:
12137 case Intrinsic::x86_avx2_pmulu_dq:
12138 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12139 Op.getOperand(1), Op.getOperand(2));
12141 case Intrinsic::x86_sse41_pmuldq:
12142 case Intrinsic::x86_avx2_pmul_dq:
12143 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12144 Op.getOperand(1), Op.getOperand(2));
12146 case Intrinsic::x86_sse2_pmulhu_w:
12147 case Intrinsic::x86_avx2_pmulhu_w:
12148 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12149 Op.getOperand(1), Op.getOperand(2));
12151 case Intrinsic::x86_sse2_pmulh_w:
12152 case Intrinsic::x86_avx2_pmulh_w:
12153 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12154 Op.getOperand(1), Op.getOperand(2));
12156 // SSE2/AVX2 sub with unsigned saturation intrinsics
12157 case Intrinsic::x86_sse2_psubus_b:
12158 case Intrinsic::x86_sse2_psubus_w:
12159 case Intrinsic::x86_avx2_psubus_b:
12160 case Intrinsic::x86_avx2_psubus_w:
12161 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12162 Op.getOperand(1), Op.getOperand(2));
12164 // SSE3/AVX horizontal add/sub intrinsics
12165 case Intrinsic::x86_sse3_hadd_ps:
12166 case Intrinsic::x86_sse3_hadd_pd:
12167 case Intrinsic::x86_avx_hadd_ps_256:
12168 case Intrinsic::x86_avx_hadd_pd_256:
12169 case Intrinsic::x86_sse3_hsub_ps:
12170 case Intrinsic::x86_sse3_hsub_pd:
12171 case Intrinsic::x86_avx_hsub_ps_256:
12172 case Intrinsic::x86_avx_hsub_pd_256:
12173 case Intrinsic::x86_ssse3_phadd_w_128:
12174 case Intrinsic::x86_ssse3_phadd_d_128:
12175 case Intrinsic::x86_avx2_phadd_w:
12176 case Intrinsic::x86_avx2_phadd_d:
12177 case Intrinsic::x86_ssse3_phsub_w_128:
12178 case Intrinsic::x86_ssse3_phsub_d_128:
12179 case Intrinsic::x86_avx2_phsub_w:
12180 case Intrinsic::x86_avx2_phsub_d: {
12183 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12184 case Intrinsic::x86_sse3_hadd_ps:
12185 case Intrinsic::x86_sse3_hadd_pd:
12186 case Intrinsic::x86_avx_hadd_ps_256:
12187 case Intrinsic::x86_avx_hadd_pd_256:
12188 Opcode = X86ISD::FHADD;
12190 case Intrinsic::x86_sse3_hsub_ps:
12191 case Intrinsic::x86_sse3_hsub_pd:
12192 case Intrinsic::x86_avx_hsub_ps_256:
12193 case Intrinsic::x86_avx_hsub_pd_256:
12194 Opcode = X86ISD::FHSUB;
12196 case Intrinsic::x86_ssse3_phadd_w_128:
12197 case Intrinsic::x86_ssse3_phadd_d_128:
12198 case Intrinsic::x86_avx2_phadd_w:
12199 case Intrinsic::x86_avx2_phadd_d:
12200 Opcode = X86ISD::HADD;
12202 case Intrinsic::x86_ssse3_phsub_w_128:
12203 case Intrinsic::x86_ssse3_phsub_d_128:
12204 case Intrinsic::x86_avx2_phsub_w:
12205 case Intrinsic::x86_avx2_phsub_d:
12206 Opcode = X86ISD::HSUB;
12209 return DAG.getNode(Opcode, dl, Op.getValueType(),
12210 Op.getOperand(1), Op.getOperand(2));
12213 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12214 case Intrinsic::x86_sse2_pmaxu_b:
12215 case Intrinsic::x86_sse41_pmaxuw:
12216 case Intrinsic::x86_sse41_pmaxud:
12217 case Intrinsic::x86_avx2_pmaxu_b:
12218 case Intrinsic::x86_avx2_pmaxu_w:
12219 case Intrinsic::x86_avx2_pmaxu_d:
12220 case Intrinsic::x86_sse2_pminu_b:
12221 case Intrinsic::x86_sse41_pminuw:
12222 case Intrinsic::x86_sse41_pminud:
12223 case Intrinsic::x86_avx2_pminu_b:
12224 case Intrinsic::x86_avx2_pminu_w:
12225 case Intrinsic::x86_avx2_pminu_d:
12226 case Intrinsic::x86_sse41_pmaxsb:
12227 case Intrinsic::x86_sse2_pmaxs_w:
12228 case Intrinsic::x86_sse41_pmaxsd:
12229 case Intrinsic::x86_avx2_pmaxs_b:
12230 case Intrinsic::x86_avx2_pmaxs_w:
12231 case Intrinsic::x86_avx2_pmaxs_d:
12232 case Intrinsic::x86_sse41_pminsb:
12233 case Intrinsic::x86_sse2_pmins_w:
12234 case Intrinsic::x86_sse41_pminsd:
12235 case Intrinsic::x86_avx2_pmins_b:
12236 case Intrinsic::x86_avx2_pmins_w:
12237 case Intrinsic::x86_avx2_pmins_d: {
12240 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12241 case Intrinsic::x86_sse2_pmaxu_b:
12242 case Intrinsic::x86_sse41_pmaxuw:
12243 case Intrinsic::x86_sse41_pmaxud:
12244 case Intrinsic::x86_avx2_pmaxu_b:
12245 case Intrinsic::x86_avx2_pmaxu_w:
12246 case Intrinsic::x86_avx2_pmaxu_d:
12247 Opcode = X86ISD::UMAX;
12249 case Intrinsic::x86_sse2_pminu_b:
12250 case Intrinsic::x86_sse41_pminuw:
12251 case Intrinsic::x86_sse41_pminud:
12252 case Intrinsic::x86_avx2_pminu_b:
12253 case Intrinsic::x86_avx2_pminu_w:
12254 case Intrinsic::x86_avx2_pminu_d:
12255 Opcode = X86ISD::UMIN;
12257 case Intrinsic::x86_sse41_pmaxsb:
12258 case Intrinsic::x86_sse2_pmaxs_w:
12259 case Intrinsic::x86_sse41_pmaxsd:
12260 case Intrinsic::x86_avx2_pmaxs_b:
12261 case Intrinsic::x86_avx2_pmaxs_w:
12262 case Intrinsic::x86_avx2_pmaxs_d:
12263 Opcode = X86ISD::SMAX;
12265 case Intrinsic::x86_sse41_pminsb:
12266 case Intrinsic::x86_sse2_pmins_w:
12267 case Intrinsic::x86_sse41_pminsd:
12268 case Intrinsic::x86_avx2_pmins_b:
12269 case Intrinsic::x86_avx2_pmins_w:
12270 case Intrinsic::x86_avx2_pmins_d:
12271 Opcode = X86ISD::SMIN;
12274 return DAG.getNode(Opcode, dl, Op.getValueType(),
12275 Op.getOperand(1), Op.getOperand(2));
12278 // SSE/SSE2/AVX floating point max/min intrinsics.
12279 case Intrinsic::x86_sse_max_ps:
12280 case Intrinsic::x86_sse2_max_pd:
12281 case Intrinsic::x86_avx_max_ps_256:
12282 case Intrinsic::x86_avx_max_pd_256:
12283 case Intrinsic::x86_sse_min_ps:
12284 case Intrinsic::x86_sse2_min_pd:
12285 case Intrinsic::x86_avx_min_ps_256:
12286 case Intrinsic::x86_avx_min_pd_256: {
12289 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12290 case Intrinsic::x86_sse_max_ps:
12291 case Intrinsic::x86_sse2_max_pd:
12292 case Intrinsic::x86_avx_max_ps_256:
12293 case Intrinsic::x86_avx_max_pd_256:
12294 Opcode = X86ISD::FMAX;
12296 case Intrinsic::x86_sse_min_ps:
12297 case Intrinsic::x86_sse2_min_pd:
12298 case Intrinsic::x86_avx_min_ps_256:
12299 case Intrinsic::x86_avx_min_pd_256:
12300 Opcode = X86ISD::FMIN;
12303 return DAG.getNode(Opcode, dl, Op.getValueType(),
12304 Op.getOperand(1), Op.getOperand(2));
12307 // AVX2 variable shift intrinsics
12308 case Intrinsic::x86_avx2_psllv_d:
12309 case Intrinsic::x86_avx2_psllv_q:
12310 case Intrinsic::x86_avx2_psllv_d_256:
12311 case Intrinsic::x86_avx2_psllv_q_256:
12312 case Intrinsic::x86_avx2_psrlv_d:
12313 case Intrinsic::x86_avx2_psrlv_q:
12314 case Intrinsic::x86_avx2_psrlv_d_256:
12315 case Intrinsic::x86_avx2_psrlv_q_256:
12316 case Intrinsic::x86_avx2_psrav_d:
12317 case Intrinsic::x86_avx2_psrav_d_256: {
12320 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12321 case Intrinsic::x86_avx2_psllv_d:
12322 case Intrinsic::x86_avx2_psllv_q:
12323 case Intrinsic::x86_avx2_psllv_d_256:
12324 case Intrinsic::x86_avx2_psllv_q_256:
12327 case Intrinsic::x86_avx2_psrlv_d:
12328 case Intrinsic::x86_avx2_psrlv_q:
12329 case Intrinsic::x86_avx2_psrlv_d_256:
12330 case Intrinsic::x86_avx2_psrlv_q_256:
12333 case Intrinsic::x86_avx2_psrav_d:
12334 case Intrinsic::x86_avx2_psrav_d_256:
12338 return DAG.getNode(Opcode, dl, Op.getValueType(),
12339 Op.getOperand(1), Op.getOperand(2));
12342 case Intrinsic::x86_ssse3_pshuf_b_128:
12343 case Intrinsic::x86_avx2_pshuf_b:
12344 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12345 Op.getOperand(1), Op.getOperand(2));
12347 case Intrinsic::x86_ssse3_psign_b_128:
12348 case Intrinsic::x86_ssse3_psign_w_128:
12349 case Intrinsic::x86_ssse3_psign_d_128:
12350 case Intrinsic::x86_avx2_psign_b:
12351 case Intrinsic::x86_avx2_psign_w:
12352 case Intrinsic::x86_avx2_psign_d:
12353 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12354 Op.getOperand(1), Op.getOperand(2));
12356 case Intrinsic::x86_sse41_insertps:
12357 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12358 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12360 case Intrinsic::x86_avx_vperm2f128_ps_256:
12361 case Intrinsic::x86_avx_vperm2f128_pd_256:
12362 case Intrinsic::x86_avx_vperm2f128_si_256:
12363 case Intrinsic::x86_avx2_vperm2i128:
12364 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12365 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12367 case Intrinsic::x86_avx2_permd:
12368 case Intrinsic::x86_avx2_permps:
12369 // Operands intentionally swapped. Mask is last operand to intrinsic,
12370 // but second operand for node/instruction.
12371 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12372 Op.getOperand(2), Op.getOperand(1));
12374 case Intrinsic::x86_sse_sqrt_ps:
12375 case Intrinsic::x86_sse2_sqrt_pd:
12376 case Intrinsic::x86_avx_sqrt_ps_256:
12377 case Intrinsic::x86_avx_sqrt_pd_256:
12378 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12380 // ptest and testp intrinsics. The intrinsic these come from are designed to
12381 // return an integer value, not just an instruction so lower it to the ptest
12382 // or testp pattern and a setcc for the result.
12383 case Intrinsic::x86_sse41_ptestz:
12384 case Intrinsic::x86_sse41_ptestc:
12385 case Intrinsic::x86_sse41_ptestnzc:
12386 case Intrinsic::x86_avx_ptestz_256:
12387 case Intrinsic::x86_avx_ptestc_256:
12388 case Intrinsic::x86_avx_ptestnzc_256:
12389 case Intrinsic::x86_avx_vtestz_ps:
12390 case Intrinsic::x86_avx_vtestc_ps:
12391 case Intrinsic::x86_avx_vtestnzc_ps:
12392 case Intrinsic::x86_avx_vtestz_pd:
12393 case Intrinsic::x86_avx_vtestc_pd:
12394 case Intrinsic::x86_avx_vtestnzc_pd:
12395 case Intrinsic::x86_avx_vtestz_ps_256:
12396 case Intrinsic::x86_avx_vtestc_ps_256:
12397 case Intrinsic::x86_avx_vtestnzc_ps_256:
12398 case Intrinsic::x86_avx_vtestz_pd_256:
12399 case Intrinsic::x86_avx_vtestc_pd_256:
12400 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12401 bool IsTestPacked = false;
12404 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12405 case Intrinsic::x86_avx_vtestz_ps:
12406 case Intrinsic::x86_avx_vtestz_pd:
12407 case Intrinsic::x86_avx_vtestz_ps_256:
12408 case Intrinsic::x86_avx_vtestz_pd_256:
12409 IsTestPacked = true; // Fallthrough
12410 case Intrinsic::x86_sse41_ptestz:
12411 case Intrinsic::x86_avx_ptestz_256:
12413 X86CC = X86::COND_E;
12415 case Intrinsic::x86_avx_vtestc_ps:
12416 case Intrinsic::x86_avx_vtestc_pd:
12417 case Intrinsic::x86_avx_vtestc_ps_256:
12418 case Intrinsic::x86_avx_vtestc_pd_256:
12419 IsTestPacked = true; // Fallthrough
12420 case Intrinsic::x86_sse41_ptestc:
12421 case Intrinsic::x86_avx_ptestc_256:
12423 X86CC = X86::COND_B;
12425 case Intrinsic::x86_avx_vtestnzc_ps:
12426 case Intrinsic::x86_avx_vtestnzc_pd:
12427 case Intrinsic::x86_avx_vtestnzc_ps_256:
12428 case Intrinsic::x86_avx_vtestnzc_pd_256:
12429 IsTestPacked = true; // Fallthrough
12430 case Intrinsic::x86_sse41_ptestnzc:
12431 case Intrinsic::x86_avx_ptestnzc_256:
12433 X86CC = X86::COND_A;
12437 SDValue LHS = Op.getOperand(1);
12438 SDValue RHS = Op.getOperand(2);
12439 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12440 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12441 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12442 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12443 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12445 case Intrinsic::x86_avx512_kortestz_w:
12446 case Intrinsic::x86_avx512_kortestc_w: {
12447 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12448 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12449 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12450 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12451 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12452 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12453 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12456 // SSE/AVX shift intrinsics
12457 case Intrinsic::x86_sse2_psll_w:
12458 case Intrinsic::x86_sse2_psll_d:
12459 case Intrinsic::x86_sse2_psll_q:
12460 case Intrinsic::x86_avx2_psll_w:
12461 case Intrinsic::x86_avx2_psll_d:
12462 case Intrinsic::x86_avx2_psll_q:
12463 case Intrinsic::x86_sse2_psrl_w:
12464 case Intrinsic::x86_sse2_psrl_d:
12465 case Intrinsic::x86_sse2_psrl_q:
12466 case Intrinsic::x86_avx2_psrl_w:
12467 case Intrinsic::x86_avx2_psrl_d:
12468 case Intrinsic::x86_avx2_psrl_q:
12469 case Intrinsic::x86_sse2_psra_w:
12470 case Intrinsic::x86_sse2_psra_d:
12471 case Intrinsic::x86_avx2_psra_w:
12472 case Intrinsic::x86_avx2_psra_d: {
12475 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12476 case Intrinsic::x86_sse2_psll_w:
12477 case Intrinsic::x86_sse2_psll_d:
12478 case Intrinsic::x86_sse2_psll_q:
12479 case Intrinsic::x86_avx2_psll_w:
12480 case Intrinsic::x86_avx2_psll_d:
12481 case Intrinsic::x86_avx2_psll_q:
12482 Opcode = X86ISD::VSHL;
12484 case Intrinsic::x86_sse2_psrl_w:
12485 case Intrinsic::x86_sse2_psrl_d:
12486 case Intrinsic::x86_sse2_psrl_q:
12487 case Intrinsic::x86_avx2_psrl_w:
12488 case Intrinsic::x86_avx2_psrl_d:
12489 case Intrinsic::x86_avx2_psrl_q:
12490 Opcode = X86ISD::VSRL;
12492 case Intrinsic::x86_sse2_psra_w:
12493 case Intrinsic::x86_sse2_psra_d:
12494 case Intrinsic::x86_avx2_psra_w:
12495 case Intrinsic::x86_avx2_psra_d:
12496 Opcode = X86ISD::VSRA;
12499 return DAG.getNode(Opcode, dl, Op.getValueType(),
12500 Op.getOperand(1), Op.getOperand(2));
12503 // SSE/AVX immediate shift intrinsics
12504 case Intrinsic::x86_sse2_pslli_w:
12505 case Intrinsic::x86_sse2_pslli_d:
12506 case Intrinsic::x86_sse2_pslli_q:
12507 case Intrinsic::x86_avx2_pslli_w:
12508 case Intrinsic::x86_avx2_pslli_d:
12509 case Intrinsic::x86_avx2_pslli_q:
12510 case Intrinsic::x86_sse2_psrli_w:
12511 case Intrinsic::x86_sse2_psrli_d:
12512 case Intrinsic::x86_sse2_psrli_q:
12513 case Intrinsic::x86_avx2_psrli_w:
12514 case Intrinsic::x86_avx2_psrli_d:
12515 case Intrinsic::x86_avx2_psrli_q:
12516 case Intrinsic::x86_sse2_psrai_w:
12517 case Intrinsic::x86_sse2_psrai_d:
12518 case Intrinsic::x86_avx2_psrai_w:
12519 case Intrinsic::x86_avx2_psrai_d: {
12522 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12523 case Intrinsic::x86_sse2_pslli_w:
12524 case Intrinsic::x86_sse2_pslli_d:
12525 case Intrinsic::x86_sse2_pslli_q:
12526 case Intrinsic::x86_avx2_pslli_w:
12527 case Intrinsic::x86_avx2_pslli_d:
12528 case Intrinsic::x86_avx2_pslli_q:
12529 Opcode = X86ISD::VSHLI;
12531 case Intrinsic::x86_sse2_psrli_w:
12532 case Intrinsic::x86_sse2_psrli_d:
12533 case Intrinsic::x86_sse2_psrli_q:
12534 case Intrinsic::x86_avx2_psrli_w:
12535 case Intrinsic::x86_avx2_psrli_d:
12536 case Intrinsic::x86_avx2_psrli_q:
12537 Opcode = X86ISD::VSRLI;
12539 case Intrinsic::x86_sse2_psrai_w:
12540 case Intrinsic::x86_sse2_psrai_d:
12541 case Intrinsic::x86_avx2_psrai_w:
12542 case Intrinsic::x86_avx2_psrai_d:
12543 Opcode = X86ISD::VSRAI;
12546 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12547 Op.getOperand(1), Op.getOperand(2), DAG);
12550 case Intrinsic::x86_sse42_pcmpistria128:
12551 case Intrinsic::x86_sse42_pcmpestria128:
12552 case Intrinsic::x86_sse42_pcmpistric128:
12553 case Intrinsic::x86_sse42_pcmpestric128:
12554 case Intrinsic::x86_sse42_pcmpistrio128:
12555 case Intrinsic::x86_sse42_pcmpestrio128:
12556 case Intrinsic::x86_sse42_pcmpistris128:
12557 case Intrinsic::x86_sse42_pcmpestris128:
12558 case Intrinsic::x86_sse42_pcmpistriz128:
12559 case Intrinsic::x86_sse42_pcmpestriz128: {
12563 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12564 case Intrinsic::x86_sse42_pcmpistria128:
12565 Opcode = X86ISD::PCMPISTRI;
12566 X86CC = X86::COND_A;
12568 case Intrinsic::x86_sse42_pcmpestria128:
12569 Opcode = X86ISD::PCMPESTRI;
12570 X86CC = X86::COND_A;
12572 case Intrinsic::x86_sse42_pcmpistric128:
12573 Opcode = X86ISD::PCMPISTRI;
12574 X86CC = X86::COND_B;
12576 case Intrinsic::x86_sse42_pcmpestric128:
12577 Opcode = X86ISD::PCMPESTRI;
12578 X86CC = X86::COND_B;
12580 case Intrinsic::x86_sse42_pcmpistrio128:
12581 Opcode = X86ISD::PCMPISTRI;
12582 X86CC = X86::COND_O;
12584 case Intrinsic::x86_sse42_pcmpestrio128:
12585 Opcode = X86ISD::PCMPESTRI;
12586 X86CC = X86::COND_O;
12588 case Intrinsic::x86_sse42_pcmpistris128:
12589 Opcode = X86ISD::PCMPISTRI;
12590 X86CC = X86::COND_S;
12592 case Intrinsic::x86_sse42_pcmpestris128:
12593 Opcode = X86ISD::PCMPESTRI;
12594 X86CC = X86::COND_S;
12596 case Intrinsic::x86_sse42_pcmpistriz128:
12597 Opcode = X86ISD::PCMPISTRI;
12598 X86CC = X86::COND_E;
12600 case Intrinsic::x86_sse42_pcmpestriz128:
12601 Opcode = X86ISD::PCMPESTRI;
12602 X86CC = X86::COND_E;
12605 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12606 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12607 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12608 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12609 DAG.getConstant(X86CC, MVT::i8),
12610 SDValue(PCMP.getNode(), 1));
12611 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12614 case Intrinsic::x86_sse42_pcmpistri128:
12615 case Intrinsic::x86_sse42_pcmpestri128: {
12617 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12618 Opcode = X86ISD::PCMPISTRI;
12620 Opcode = X86ISD::PCMPESTRI;
12622 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12623 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12624 return DAG.getNode(Opcode, dl, VTs, NewOps);
12626 case Intrinsic::x86_fma_vfmadd_ps:
12627 case Intrinsic::x86_fma_vfmadd_pd:
12628 case Intrinsic::x86_fma_vfmsub_ps:
12629 case Intrinsic::x86_fma_vfmsub_pd:
12630 case Intrinsic::x86_fma_vfnmadd_ps:
12631 case Intrinsic::x86_fma_vfnmadd_pd:
12632 case Intrinsic::x86_fma_vfnmsub_ps:
12633 case Intrinsic::x86_fma_vfnmsub_pd:
12634 case Intrinsic::x86_fma_vfmaddsub_ps:
12635 case Intrinsic::x86_fma_vfmaddsub_pd:
12636 case Intrinsic::x86_fma_vfmsubadd_ps:
12637 case Intrinsic::x86_fma_vfmsubadd_pd:
12638 case Intrinsic::x86_fma_vfmadd_ps_256:
12639 case Intrinsic::x86_fma_vfmadd_pd_256:
12640 case Intrinsic::x86_fma_vfmsub_ps_256:
12641 case Intrinsic::x86_fma_vfmsub_pd_256:
12642 case Intrinsic::x86_fma_vfnmadd_ps_256:
12643 case Intrinsic::x86_fma_vfnmadd_pd_256:
12644 case Intrinsic::x86_fma_vfnmsub_ps_256:
12645 case Intrinsic::x86_fma_vfnmsub_pd_256:
12646 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12647 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12648 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12649 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12650 case Intrinsic::x86_fma_vfmadd_ps_512:
12651 case Intrinsic::x86_fma_vfmadd_pd_512:
12652 case Intrinsic::x86_fma_vfmsub_ps_512:
12653 case Intrinsic::x86_fma_vfmsub_pd_512:
12654 case Intrinsic::x86_fma_vfnmadd_ps_512:
12655 case Intrinsic::x86_fma_vfnmadd_pd_512:
12656 case Intrinsic::x86_fma_vfnmsub_ps_512:
12657 case Intrinsic::x86_fma_vfnmsub_pd_512:
12658 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12659 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12660 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12661 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12664 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12665 case Intrinsic::x86_fma_vfmadd_ps:
12666 case Intrinsic::x86_fma_vfmadd_pd:
12667 case Intrinsic::x86_fma_vfmadd_ps_256:
12668 case Intrinsic::x86_fma_vfmadd_pd_256:
12669 case Intrinsic::x86_fma_vfmadd_ps_512:
12670 case Intrinsic::x86_fma_vfmadd_pd_512:
12671 Opc = X86ISD::FMADD;
12673 case Intrinsic::x86_fma_vfmsub_ps:
12674 case Intrinsic::x86_fma_vfmsub_pd:
12675 case Intrinsic::x86_fma_vfmsub_ps_256:
12676 case Intrinsic::x86_fma_vfmsub_pd_256:
12677 case Intrinsic::x86_fma_vfmsub_ps_512:
12678 case Intrinsic::x86_fma_vfmsub_pd_512:
12679 Opc = X86ISD::FMSUB;
12681 case Intrinsic::x86_fma_vfnmadd_ps:
12682 case Intrinsic::x86_fma_vfnmadd_pd:
12683 case Intrinsic::x86_fma_vfnmadd_ps_256:
12684 case Intrinsic::x86_fma_vfnmadd_pd_256:
12685 case Intrinsic::x86_fma_vfnmadd_ps_512:
12686 case Intrinsic::x86_fma_vfnmadd_pd_512:
12687 Opc = X86ISD::FNMADD;
12689 case Intrinsic::x86_fma_vfnmsub_ps:
12690 case Intrinsic::x86_fma_vfnmsub_pd:
12691 case Intrinsic::x86_fma_vfnmsub_ps_256:
12692 case Intrinsic::x86_fma_vfnmsub_pd_256:
12693 case Intrinsic::x86_fma_vfnmsub_ps_512:
12694 case Intrinsic::x86_fma_vfnmsub_pd_512:
12695 Opc = X86ISD::FNMSUB;
12697 case Intrinsic::x86_fma_vfmaddsub_ps:
12698 case Intrinsic::x86_fma_vfmaddsub_pd:
12699 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12700 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12701 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12702 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12703 Opc = X86ISD::FMADDSUB;
12705 case Intrinsic::x86_fma_vfmsubadd_ps:
12706 case Intrinsic::x86_fma_vfmsubadd_pd:
12707 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12708 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12709 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12710 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12711 Opc = X86ISD::FMSUBADD;
12715 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12716 Op.getOperand(2), Op.getOperand(3));
12721 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12722 SDValue Src, SDValue Mask, SDValue Base,
12723 SDValue Index, SDValue ScaleOp, SDValue Chain,
12724 const X86Subtarget * Subtarget) {
12726 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12727 assert(C && "Invalid scale type");
12728 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12729 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12730 Index.getSimpleValueType().getVectorNumElements());
12732 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12734 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12736 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12737 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12738 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12739 SDValue Segment = DAG.getRegister(0, MVT::i32);
12740 if (Src.getOpcode() == ISD::UNDEF)
12741 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12742 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12743 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12744 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12745 return DAG.getMergeValues(RetOps, dl);
12748 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12749 SDValue Src, SDValue Mask, SDValue Base,
12750 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12752 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12753 assert(C && "Invalid scale type");
12754 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12755 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12756 SDValue Segment = DAG.getRegister(0, MVT::i32);
12757 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12758 Index.getSimpleValueType().getVectorNumElements());
12760 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12762 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12764 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12765 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12766 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12767 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12768 return SDValue(Res, 1);
12771 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12772 SDValue Mask, SDValue Base, SDValue Index,
12773 SDValue ScaleOp, SDValue Chain) {
12775 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12776 assert(C && "Invalid scale type");
12777 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12778 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12779 SDValue Segment = DAG.getRegister(0, MVT::i32);
12781 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12783 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12785 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12787 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12788 //SDVTList VTs = DAG.getVTList(MVT::Other);
12789 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12790 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12791 return SDValue(Res, 0);
12794 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12795 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12796 // also used to custom lower READCYCLECOUNTER nodes.
12797 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12798 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12799 SmallVectorImpl<SDValue> &Results) {
12800 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12801 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12804 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12805 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12806 // and the EAX register is loaded with the low-order 32 bits.
12807 if (Subtarget->is64Bit()) {
12808 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12809 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12812 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12813 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12816 SDValue Chain = HI.getValue(1);
12818 if (Opcode == X86ISD::RDTSCP_DAG) {
12819 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12821 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12822 // the ECX register. Add 'ecx' explicitly to the chain.
12823 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12825 // Explicitly store the content of ECX at the location passed in input
12826 // to the 'rdtscp' intrinsic.
12827 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12828 MachinePointerInfo(), false, false, 0);
12831 if (Subtarget->is64Bit()) {
12832 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12833 // the EAX register is loaded with the low-order 32 bits.
12834 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12835 DAG.getConstant(32, MVT::i8));
12836 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12837 Results.push_back(Chain);
12841 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12842 SDValue Ops[] = { LO, HI };
12843 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12844 Results.push_back(Pair);
12845 Results.push_back(Chain);
12848 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12849 SelectionDAG &DAG) {
12850 SmallVector<SDValue, 2> Results;
12852 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12854 return DAG.getMergeValues(Results, DL);
12857 enum IntrinsicType {
12858 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12861 struct IntrinsicData {
12862 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12863 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12864 IntrinsicType Type;
12869 std::map < unsigned, IntrinsicData> IntrMap;
12870 static void InitIntinsicsMap() {
12871 static bool Initialized = false;
12874 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12875 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12876 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12877 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12878 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12879 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12880 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12881 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12882 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12883 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12884 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
12885 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12886 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
12887 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12888 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
12889 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12890 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
12891 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12893 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12894 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12895 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
12896 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12897 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
12898 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12899 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
12900 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12901 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
12902 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12903 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
12904 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12905 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
12906 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12907 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
12908 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12910 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
12911 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12912 X86::VGATHERPF1QPSm)));
12913 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
12914 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12915 X86::VGATHERPF1QPDm)));
12916 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
12917 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12918 X86::VGATHERPF1DPDm)));
12919 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
12920 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12921 X86::VGATHERPF1DPSm)));
12922 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
12923 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12924 X86::VSCATTERPF1QPSm)));
12925 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
12926 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12927 X86::VSCATTERPF1QPDm)));
12928 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
12929 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12930 X86::VSCATTERPF1DPDm)));
12931 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
12932 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12933 X86::VSCATTERPF1DPSm)));
12934 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12935 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12936 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12937 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12938 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12939 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12940 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12941 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12942 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12943 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12944 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12945 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12946 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12947 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
12948 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12949 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
12950 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12951 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
12952 Initialized = true;
12955 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12956 SelectionDAG &DAG) {
12957 InitIntinsicsMap();
12958 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12959 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12960 if (itr == IntrMap.end())
12964 IntrinsicData Intr = itr->second;
12965 switch(Intr.Type) {
12968 // Emit the node with the right value type.
12969 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12970 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12972 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12973 // Otherwise return the value from Rand, which is always 0, casted to i32.
12974 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12975 DAG.getConstant(1, Op->getValueType(1)),
12976 DAG.getConstant(X86::COND_B, MVT::i32),
12977 SDValue(Result.getNode(), 1) };
12978 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12979 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12982 // Return { result, isValid, chain }.
12983 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12984 SDValue(Result.getNode(), 2));
12987 //gather(v1, mask, index, base, scale);
12988 SDValue Chain = Op.getOperand(0);
12989 SDValue Src = Op.getOperand(2);
12990 SDValue Base = Op.getOperand(3);
12991 SDValue Index = Op.getOperand(4);
12992 SDValue Mask = Op.getOperand(5);
12993 SDValue Scale = Op.getOperand(6);
12994 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12998 //scatter(base, mask, index, v1, scale);
12999 SDValue Chain = Op.getOperand(0);
13000 SDValue Base = Op.getOperand(2);
13001 SDValue Mask = Op.getOperand(3);
13002 SDValue Index = Op.getOperand(4);
13003 SDValue Src = Op.getOperand(5);
13004 SDValue Scale = Op.getOperand(6);
13005 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13008 SDValue Hint = Op.getOperand(6);
13010 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13011 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13012 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13013 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13014 SDValue Chain = Op.getOperand(0);
13015 SDValue Mask = Op.getOperand(2);
13016 SDValue Index = Op.getOperand(3);
13017 SDValue Base = Op.getOperand(4);
13018 SDValue Scale = Op.getOperand(5);
13019 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13021 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13023 SmallVector<SDValue, 2> Results;
13024 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13025 return DAG.getMergeValues(Results, dl);
13027 // XTEST intrinsics.
13029 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13030 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13031 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13032 DAG.getConstant(X86::COND_NE, MVT::i8),
13034 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13035 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13036 Ret, SDValue(InTrans.getNode(), 1));
13039 llvm_unreachable("Unknown Intrinsic Type");
13042 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13043 SelectionDAG &DAG) const {
13044 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13045 MFI->setReturnAddressIsTaken(true);
13047 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13050 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13052 EVT PtrVT = getPointerTy();
13055 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13056 const X86RegisterInfo *RegInfo =
13057 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13058 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13059 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13060 DAG.getNode(ISD::ADD, dl, PtrVT,
13061 FrameAddr, Offset),
13062 MachinePointerInfo(), false, false, false, 0);
13065 // Just load the return address.
13066 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13067 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13068 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13071 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13072 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13073 MFI->setFrameAddressIsTaken(true);
13075 EVT VT = Op.getValueType();
13076 SDLoc dl(Op); // FIXME probably not meaningful
13077 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13078 const X86RegisterInfo *RegInfo =
13079 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13080 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13081 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13082 (FrameReg == X86::EBP && VT == MVT::i32)) &&
13083 "Invalid Frame Register!");
13084 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13086 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13087 MachinePointerInfo(),
13088 false, false, false, 0);
13092 // FIXME? Maybe this could be a TableGen attribute on some registers and
13093 // this table could be generated automatically from RegInfo.
13094 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13096 unsigned Reg = StringSwitch<unsigned>(RegName)
13097 .Case("esp", X86::ESP)
13098 .Case("rsp", X86::RSP)
13102 report_fatal_error("Invalid register name global variable");
13105 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13106 SelectionDAG &DAG) const {
13107 const X86RegisterInfo *RegInfo =
13108 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13109 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13112 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13113 SDValue Chain = Op.getOperand(0);
13114 SDValue Offset = Op.getOperand(1);
13115 SDValue Handler = Op.getOperand(2);
13118 EVT PtrVT = getPointerTy();
13119 const X86RegisterInfo *RegInfo =
13120 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13121 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13122 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13123 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13124 "Invalid Frame Register!");
13125 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13126 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13128 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13129 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13130 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13131 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13133 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13135 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13136 DAG.getRegister(StoreAddrReg, PtrVT));
13139 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13140 SelectionDAG &DAG) const {
13142 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13143 DAG.getVTList(MVT::i32, MVT::Other),
13144 Op.getOperand(0), Op.getOperand(1));
13147 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13148 SelectionDAG &DAG) const {
13150 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13151 Op.getOperand(0), Op.getOperand(1));
13154 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13155 return Op.getOperand(0);
13158 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13159 SelectionDAG &DAG) const {
13160 SDValue Root = Op.getOperand(0);
13161 SDValue Trmp = Op.getOperand(1); // trampoline
13162 SDValue FPtr = Op.getOperand(2); // nested function
13163 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13166 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13167 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13169 if (Subtarget->is64Bit()) {
13170 SDValue OutChains[6];
13172 // Large code-model.
13173 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13174 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13176 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13177 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13179 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13181 // Load the pointer to the nested function into R11.
13182 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13183 SDValue Addr = Trmp;
13184 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13185 Addr, MachinePointerInfo(TrmpAddr),
13188 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13189 DAG.getConstant(2, MVT::i64));
13190 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13191 MachinePointerInfo(TrmpAddr, 2),
13194 // Load the 'nest' parameter value into R10.
13195 // R10 is specified in X86CallingConv.td
13196 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13197 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13198 DAG.getConstant(10, MVT::i64));
13199 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13200 Addr, MachinePointerInfo(TrmpAddr, 10),
13203 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13204 DAG.getConstant(12, MVT::i64));
13205 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13206 MachinePointerInfo(TrmpAddr, 12),
13209 // Jump to the nested function.
13210 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13211 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13212 DAG.getConstant(20, MVT::i64));
13213 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13214 Addr, MachinePointerInfo(TrmpAddr, 20),
13217 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13218 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13219 DAG.getConstant(22, MVT::i64));
13220 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13221 MachinePointerInfo(TrmpAddr, 22),
13224 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13226 const Function *Func =
13227 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13228 CallingConv::ID CC = Func->getCallingConv();
13233 llvm_unreachable("Unsupported calling convention");
13234 case CallingConv::C:
13235 case CallingConv::X86_StdCall: {
13236 // Pass 'nest' parameter in ECX.
13237 // Must be kept in sync with X86CallingConv.td
13238 NestReg = X86::ECX;
13240 // Check that ECX wasn't needed by an 'inreg' parameter.
13241 FunctionType *FTy = Func->getFunctionType();
13242 const AttributeSet &Attrs = Func->getAttributes();
13244 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13245 unsigned InRegCount = 0;
13248 for (FunctionType::param_iterator I = FTy->param_begin(),
13249 E = FTy->param_end(); I != E; ++I, ++Idx)
13250 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13251 // FIXME: should only count parameters that are lowered to integers.
13252 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13254 if (InRegCount > 2) {
13255 report_fatal_error("Nest register in use - reduce number of inreg"
13261 case CallingConv::X86_FastCall:
13262 case CallingConv::X86_ThisCall:
13263 case CallingConv::Fast:
13264 // Pass 'nest' parameter in EAX.
13265 // Must be kept in sync with X86CallingConv.td
13266 NestReg = X86::EAX;
13270 SDValue OutChains[4];
13271 SDValue Addr, Disp;
13273 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13274 DAG.getConstant(10, MVT::i32));
13275 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13277 // This is storing the opcode for MOV32ri.
13278 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13279 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13280 OutChains[0] = DAG.getStore(Root, dl,
13281 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13282 Trmp, MachinePointerInfo(TrmpAddr),
13285 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13286 DAG.getConstant(1, MVT::i32));
13287 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13288 MachinePointerInfo(TrmpAddr, 1),
13291 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13292 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13293 DAG.getConstant(5, MVT::i32));
13294 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13295 MachinePointerInfo(TrmpAddr, 5),
13298 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13299 DAG.getConstant(6, MVT::i32));
13300 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13301 MachinePointerInfo(TrmpAddr, 6),
13304 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13308 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13309 SelectionDAG &DAG) const {
13311 The rounding mode is in bits 11:10 of FPSR, and has the following
13313 00 Round to nearest
13318 FLT_ROUNDS, on the other hand, expects the following:
13325 To perform the conversion, we do:
13326 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13329 MachineFunction &MF = DAG.getMachineFunction();
13330 const TargetMachine &TM = MF.getTarget();
13331 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13332 unsigned StackAlignment = TFI.getStackAlignment();
13333 MVT VT = Op.getSimpleValueType();
13336 // Save FP Control Word to stack slot
13337 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13338 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13340 MachineMemOperand *MMO =
13341 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13342 MachineMemOperand::MOStore, 2, 2);
13344 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13345 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13346 DAG.getVTList(MVT::Other),
13347 Ops, MVT::i16, MMO);
13349 // Load FP Control Word from stack slot
13350 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13351 MachinePointerInfo(), false, false, false, 0);
13353 // Transform as necessary
13355 DAG.getNode(ISD::SRL, DL, MVT::i16,
13356 DAG.getNode(ISD::AND, DL, MVT::i16,
13357 CWD, DAG.getConstant(0x800, MVT::i16)),
13358 DAG.getConstant(11, MVT::i8));
13360 DAG.getNode(ISD::SRL, DL, MVT::i16,
13361 DAG.getNode(ISD::AND, DL, MVT::i16,
13362 CWD, DAG.getConstant(0x400, MVT::i16)),
13363 DAG.getConstant(9, MVT::i8));
13366 DAG.getNode(ISD::AND, DL, MVT::i16,
13367 DAG.getNode(ISD::ADD, DL, MVT::i16,
13368 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13369 DAG.getConstant(1, MVT::i16)),
13370 DAG.getConstant(3, MVT::i16));
13372 return DAG.getNode((VT.getSizeInBits() < 16 ?
13373 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13376 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13377 MVT VT = Op.getSimpleValueType();
13379 unsigned NumBits = VT.getSizeInBits();
13382 Op = Op.getOperand(0);
13383 if (VT == MVT::i8) {
13384 // Zero extend to i32 since there is not an i8 bsr.
13386 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13389 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13390 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13391 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13393 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13396 DAG.getConstant(NumBits+NumBits-1, OpVT),
13397 DAG.getConstant(X86::COND_E, MVT::i8),
13400 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13402 // Finally xor with NumBits-1.
13403 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13406 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13410 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13411 MVT VT = Op.getSimpleValueType();
13413 unsigned NumBits = VT.getSizeInBits();
13416 Op = Op.getOperand(0);
13417 if (VT == MVT::i8) {
13418 // Zero extend to i32 since there is not an i8 bsr.
13420 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13423 // Issue a bsr (scan bits in reverse).
13424 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13425 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13427 // And xor with NumBits-1.
13428 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13431 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13435 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13436 MVT VT = Op.getSimpleValueType();
13437 unsigned NumBits = VT.getSizeInBits();
13439 Op = Op.getOperand(0);
13441 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13442 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13443 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13445 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13448 DAG.getConstant(NumBits, VT),
13449 DAG.getConstant(X86::COND_E, MVT::i8),
13452 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13455 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13456 // ones, and then concatenate the result back.
13457 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13458 MVT VT = Op.getSimpleValueType();
13460 assert(VT.is256BitVector() && VT.isInteger() &&
13461 "Unsupported value type for operation");
13463 unsigned NumElems = VT.getVectorNumElements();
13466 // Extract the LHS vectors
13467 SDValue LHS = Op.getOperand(0);
13468 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13469 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13471 // Extract the RHS vectors
13472 SDValue RHS = Op.getOperand(1);
13473 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13474 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13476 MVT EltVT = VT.getVectorElementType();
13477 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13479 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13480 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13481 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13484 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13485 assert(Op.getSimpleValueType().is256BitVector() &&
13486 Op.getSimpleValueType().isInteger() &&
13487 "Only handle AVX 256-bit vector integer operation");
13488 return Lower256IntArith(Op, DAG);
13491 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13492 assert(Op.getSimpleValueType().is256BitVector() &&
13493 Op.getSimpleValueType().isInteger() &&
13494 "Only handle AVX 256-bit vector integer operation");
13495 return Lower256IntArith(Op, DAG);
13498 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13499 SelectionDAG &DAG) {
13501 MVT VT = Op.getSimpleValueType();
13503 // Decompose 256-bit ops into smaller 128-bit ops.
13504 if (VT.is256BitVector() && !Subtarget->hasInt256())
13505 return Lower256IntArith(Op, DAG);
13507 SDValue A = Op.getOperand(0);
13508 SDValue B = Op.getOperand(1);
13510 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13511 if (VT == MVT::v4i32) {
13512 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13513 "Should not custom lower when pmuldq is available!");
13515 // Extract the odd parts.
13516 static const int UnpackMask[] = { 1, -1, 3, -1 };
13517 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13518 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13520 // Multiply the even parts.
13521 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13522 // Now multiply odd parts.
13523 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13525 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13526 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13528 // Merge the two vectors back together with a shuffle. This expands into 2
13530 static const int ShufMask[] = { 0, 4, 2, 6 };
13531 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13534 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13535 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13537 // Ahi = psrlqi(a, 32);
13538 // Bhi = psrlqi(b, 32);
13540 // AloBlo = pmuludq(a, b);
13541 // AloBhi = pmuludq(a, Bhi);
13542 // AhiBlo = pmuludq(Ahi, b);
13544 // AloBhi = psllqi(AloBhi, 32);
13545 // AhiBlo = psllqi(AhiBlo, 32);
13546 // return AloBlo + AloBhi + AhiBlo;
13548 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13549 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13551 // Bit cast to 32-bit vectors for MULUDQ
13552 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13553 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13554 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13555 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13556 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13557 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13559 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13560 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13561 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13563 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13564 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13566 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13567 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13570 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13571 assert(Subtarget->isTargetWin64() && "Unexpected target");
13572 EVT VT = Op.getValueType();
13573 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13574 "Unexpected return type for lowering");
13578 switch (Op->getOpcode()) {
13579 default: llvm_unreachable("Unexpected request for libcall!");
13580 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13581 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13582 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13583 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13584 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13585 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13589 SDValue InChain = DAG.getEntryNode();
13591 TargetLowering::ArgListTy Args;
13592 TargetLowering::ArgListEntry Entry;
13593 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13594 EVT ArgVT = Op->getOperand(i).getValueType();
13595 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13596 "Unexpected argument type for lowering");
13597 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13598 Entry.Node = StackPtr;
13599 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13601 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13602 Entry.Ty = PointerType::get(ArgTy,0);
13603 Entry.isSExt = false;
13604 Entry.isZExt = false;
13605 Args.push_back(Entry);
13608 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13611 TargetLowering::CallLoweringInfo CLI(DAG);
13612 CLI.setDebugLoc(dl).setChain(InChain)
13613 .setCallee(getLibcallCallingConv(LC),
13614 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13616 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13618 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13619 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13622 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13623 SelectionDAG &DAG) {
13624 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13625 EVT VT = Op0.getValueType();
13628 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13629 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13631 // Get the high parts.
13632 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13633 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13634 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13636 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13638 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13639 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13641 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13642 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13643 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13644 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13645 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13647 // Shuffle it back into the right order.
13648 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13649 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13650 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13651 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13653 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13654 // unsigned multiply.
13655 if (IsSigned && !Subtarget->hasSSE41()) {
13657 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13658 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13659 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13660 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13661 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13663 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13664 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13667 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13670 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13671 const X86Subtarget *Subtarget) {
13672 MVT VT = Op.getSimpleValueType();
13674 SDValue R = Op.getOperand(0);
13675 SDValue Amt = Op.getOperand(1);
13677 // Optimize shl/srl/sra with constant shift amount.
13678 if (isSplatVector(Amt.getNode())) {
13679 SDValue SclrAmt = Amt->getOperand(0);
13680 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13681 uint64_t ShiftAmt = C->getZExtValue();
13683 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13684 (Subtarget->hasInt256() &&
13685 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13686 (Subtarget->hasAVX512() &&
13687 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13688 if (Op.getOpcode() == ISD::SHL)
13689 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13691 if (Op.getOpcode() == ISD::SRL)
13692 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13694 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13695 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13699 if (VT == MVT::v16i8) {
13700 if (Op.getOpcode() == ISD::SHL) {
13701 // Make a large shift.
13702 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13703 MVT::v8i16, R, ShiftAmt,
13705 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13706 // Zero out the rightmost bits.
13707 SmallVector<SDValue, 16> V(16,
13708 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13710 return DAG.getNode(ISD::AND, dl, VT, SHL,
13711 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13713 if (Op.getOpcode() == ISD::SRL) {
13714 // Make a large shift.
13715 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13716 MVT::v8i16, R, ShiftAmt,
13718 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13719 // Zero out the leftmost bits.
13720 SmallVector<SDValue, 16> V(16,
13721 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13723 return DAG.getNode(ISD::AND, dl, VT, SRL,
13724 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13726 if (Op.getOpcode() == ISD::SRA) {
13727 if (ShiftAmt == 7) {
13728 // R s>> 7 === R s< 0
13729 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13730 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13733 // R s>> a === ((R u>> a) ^ m) - m
13734 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13735 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13737 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13738 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13739 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13742 llvm_unreachable("Unknown shift opcode.");
13745 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13746 if (Op.getOpcode() == ISD::SHL) {
13747 // Make a large shift.
13748 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13749 MVT::v16i16, R, ShiftAmt,
13751 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13752 // Zero out the rightmost bits.
13753 SmallVector<SDValue, 32> V(32,
13754 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13756 return DAG.getNode(ISD::AND, dl, VT, SHL,
13757 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13759 if (Op.getOpcode() == ISD::SRL) {
13760 // Make a large shift.
13761 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13762 MVT::v16i16, R, ShiftAmt,
13764 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13765 // Zero out the leftmost bits.
13766 SmallVector<SDValue, 32> V(32,
13767 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13769 return DAG.getNode(ISD::AND, dl, VT, SRL,
13770 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13772 if (Op.getOpcode() == ISD::SRA) {
13773 if (ShiftAmt == 7) {
13774 // R s>> 7 === R s< 0
13775 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13776 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13779 // R s>> a === ((R u>> a) ^ m) - m
13780 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13781 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13783 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13784 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13785 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13788 llvm_unreachable("Unknown shift opcode.");
13793 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13794 if (!Subtarget->is64Bit() &&
13795 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13796 Amt.getOpcode() == ISD::BITCAST &&
13797 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13798 Amt = Amt.getOperand(0);
13799 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13800 VT.getVectorNumElements();
13801 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13802 uint64_t ShiftAmt = 0;
13803 for (unsigned i = 0; i != Ratio; ++i) {
13804 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13808 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13810 // Check remaining shift amounts.
13811 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13812 uint64_t ShAmt = 0;
13813 for (unsigned j = 0; j != Ratio; ++j) {
13814 ConstantSDNode *C =
13815 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13819 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13821 if (ShAmt != ShiftAmt)
13824 switch (Op.getOpcode()) {
13826 llvm_unreachable("Unknown shift opcode!");
13828 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13831 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13834 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13842 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13843 const X86Subtarget* Subtarget) {
13844 MVT VT = Op.getSimpleValueType();
13846 SDValue R = Op.getOperand(0);
13847 SDValue Amt = Op.getOperand(1);
13849 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13850 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13851 (Subtarget->hasInt256() &&
13852 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13853 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13854 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13856 EVT EltVT = VT.getVectorElementType();
13858 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13859 unsigned NumElts = VT.getVectorNumElements();
13861 for (i = 0; i != NumElts; ++i) {
13862 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13866 for (j = i; j != NumElts; ++j) {
13867 SDValue Arg = Amt.getOperand(j);
13868 if (Arg.getOpcode() == ISD::UNDEF) continue;
13869 if (Arg != Amt.getOperand(i))
13872 if (i != NumElts && j == NumElts)
13873 BaseShAmt = Amt.getOperand(i);
13875 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13876 Amt = Amt.getOperand(0);
13877 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13878 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13879 SDValue InVec = Amt.getOperand(0);
13880 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13881 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13883 for (; i != NumElts; ++i) {
13884 SDValue Arg = InVec.getOperand(i);
13885 if (Arg.getOpcode() == ISD::UNDEF) continue;
13889 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13890 if (ConstantSDNode *C =
13891 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13892 unsigned SplatIdx =
13893 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13894 if (C->getZExtValue() == SplatIdx)
13895 BaseShAmt = InVec.getOperand(1);
13898 if (!BaseShAmt.getNode())
13899 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13900 DAG.getIntPtrConstant(0));
13904 if (BaseShAmt.getNode()) {
13905 if (EltVT.bitsGT(MVT::i32))
13906 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13907 else if (EltVT.bitsLT(MVT::i32))
13908 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13910 switch (Op.getOpcode()) {
13912 llvm_unreachable("Unknown shift opcode!");
13914 switch (VT.SimpleTy) {
13915 default: return SDValue();
13924 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13927 switch (VT.SimpleTy) {
13928 default: return SDValue();
13935 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13938 switch (VT.SimpleTy) {
13939 default: return SDValue();
13948 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13954 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13955 if (!Subtarget->is64Bit() &&
13956 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13957 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13958 Amt.getOpcode() == ISD::BITCAST &&
13959 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13960 Amt = Amt.getOperand(0);
13961 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13962 VT.getVectorNumElements();
13963 std::vector<SDValue> Vals(Ratio);
13964 for (unsigned i = 0; i != Ratio; ++i)
13965 Vals[i] = Amt.getOperand(i);
13966 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13967 for (unsigned j = 0; j != Ratio; ++j)
13968 if (Vals[j] != Amt.getOperand(i + j))
13971 switch (Op.getOpcode()) {
13973 llvm_unreachable("Unknown shift opcode!");
13975 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13977 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13979 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13986 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13987 SelectionDAG &DAG) {
13989 MVT VT = Op.getSimpleValueType();
13991 SDValue R = Op.getOperand(0);
13992 SDValue Amt = Op.getOperand(1);
13995 if (!Subtarget->hasSSE2())
13998 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14002 V = LowerScalarVariableShift(Op, DAG, Subtarget);
14006 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14008 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14009 if (Subtarget->hasInt256()) {
14010 if (Op.getOpcode() == ISD::SRL &&
14011 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14012 VT == MVT::v4i64 || VT == MVT::v8i32))
14014 if (Op.getOpcode() == ISD::SHL &&
14015 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14016 VT == MVT::v4i64 || VT == MVT::v8i32))
14018 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14022 // If possible, lower this packed shift into a vector multiply instead of
14023 // expanding it into a sequence of scalar shifts.
14024 // Do this only if the vector shift count is a constant build_vector.
14025 if (Op.getOpcode() == ISD::SHL &&
14026 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14027 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14028 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14029 SmallVector<SDValue, 8> Elts;
14030 EVT SVT = VT.getScalarType();
14031 unsigned SVTBits = SVT.getSizeInBits();
14032 const APInt &One = APInt(SVTBits, 1);
14033 unsigned NumElems = VT.getVectorNumElements();
14035 for (unsigned i=0; i !=NumElems; ++i) {
14036 SDValue Op = Amt->getOperand(i);
14037 if (Op->getOpcode() == ISD::UNDEF) {
14038 Elts.push_back(Op);
14042 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14043 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14044 uint64_t ShAmt = C.getZExtValue();
14045 if (ShAmt >= SVTBits) {
14046 Elts.push_back(DAG.getUNDEF(SVT));
14049 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14051 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14052 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14055 // Lower SHL with variable shift amount.
14056 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14057 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14059 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14060 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14061 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14062 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14065 // If possible, lower this shift as a sequence of two shifts by
14066 // constant plus a MOVSS/MOVSD instead of scalarizing it.
14068 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14070 // Could be rewritten as:
14071 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14073 // The advantage is that the two shifts from the example would be
14074 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14075 // the vector shift into four scalar shifts plus four pairs of vector
14077 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14078 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14079 unsigned TargetOpcode = X86ISD::MOVSS;
14080 bool CanBeSimplified;
14081 // The splat value for the first packed shift (the 'X' from the example).
14082 SDValue Amt1 = Amt->getOperand(0);
14083 // The splat value for the second packed shift (the 'Y' from the example).
14084 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14085 Amt->getOperand(2);
14087 // See if it is possible to replace this node with a sequence of
14088 // two shifts followed by a MOVSS/MOVSD
14089 if (VT == MVT::v4i32) {
14090 // Check if it is legal to use a MOVSS.
14091 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14092 Amt2 == Amt->getOperand(3);
14093 if (!CanBeSimplified) {
14094 // Otherwise, check if we can still simplify this node using a MOVSD.
14095 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14096 Amt->getOperand(2) == Amt->getOperand(3);
14097 TargetOpcode = X86ISD::MOVSD;
14098 Amt2 = Amt->getOperand(2);
14101 // Do similar checks for the case where the machine value type
14103 CanBeSimplified = Amt1 == Amt->getOperand(1);
14104 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14105 CanBeSimplified = Amt2 == Amt->getOperand(i);
14107 if (!CanBeSimplified) {
14108 TargetOpcode = X86ISD::MOVSD;
14109 CanBeSimplified = true;
14110 Amt2 = Amt->getOperand(4);
14111 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14112 CanBeSimplified = Amt1 == Amt->getOperand(i);
14113 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14114 CanBeSimplified = Amt2 == Amt->getOperand(j);
14118 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14119 isa<ConstantSDNode>(Amt2)) {
14120 // Replace this node with two shifts followed by a MOVSS/MOVSD.
14121 EVT CastVT = MVT::v4i32;
14123 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14124 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14126 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14127 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14128 if (TargetOpcode == X86ISD::MOVSD)
14129 CastVT = MVT::v2i64;
14130 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14131 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14132 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14134 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14138 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14139 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14142 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14143 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14145 // Turn 'a' into a mask suitable for VSELECT
14146 SDValue VSelM = DAG.getConstant(0x80, VT);
14147 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14148 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14150 SDValue CM1 = DAG.getConstant(0x0f, VT);
14151 SDValue CM2 = DAG.getConstant(0x3f, VT);
14153 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14154 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14155 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14156 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14157 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14160 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14161 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14162 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14164 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14165 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14166 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14167 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14168 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14171 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14172 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14173 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14175 // return VSELECT(r, r+r, a);
14176 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14177 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14181 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14182 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14183 // solution better.
14184 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14185 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14187 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14188 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14189 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14190 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14191 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14194 // Decompose 256-bit shifts into smaller 128-bit shifts.
14195 if (VT.is256BitVector()) {
14196 unsigned NumElems = VT.getVectorNumElements();
14197 MVT EltVT = VT.getVectorElementType();
14198 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14200 // Extract the two vectors
14201 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14202 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14204 // Recreate the shift amount vectors
14205 SDValue Amt1, Amt2;
14206 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14207 // Constant shift amount
14208 SmallVector<SDValue, 4> Amt1Csts;
14209 SmallVector<SDValue, 4> Amt2Csts;
14210 for (unsigned i = 0; i != NumElems/2; ++i)
14211 Amt1Csts.push_back(Amt->getOperand(i));
14212 for (unsigned i = NumElems/2; i != NumElems; ++i)
14213 Amt2Csts.push_back(Amt->getOperand(i));
14215 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14216 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14218 // Variable shift amount
14219 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14220 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14223 // Issue new vector shifts for the smaller types
14224 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14225 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14227 // Concatenate the result back
14228 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14234 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14235 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14236 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14237 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14238 // has only one use.
14239 SDNode *N = Op.getNode();
14240 SDValue LHS = N->getOperand(0);
14241 SDValue RHS = N->getOperand(1);
14242 unsigned BaseOp = 0;
14245 switch (Op.getOpcode()) {
14246 default: llvm_unreachable("Unknown ovf instruction!");
14248 // A subtract of one will be selected as a INC. Note that INC doesn't
14249 // set CF, so we can't do this for UADDO.
14250 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14252 BaseOp = X86ISD::INC;
14253 Cond = X86::COND_O;
14256 BaseOp = X86ISD::ADD;
14257 Cond = X86::COND_O;
14260 BaseOp = X86ISD::ADD;
14261 Cond = X86::COND_B;
14264 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14265 // set CF, so we can't do this for USUBO.
14266 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14268 BaseOp = X86ISD::DEC;
14269 Cond = X86::COND_O;
14272 BaseOp = X86ISD::SUB;
14273 Cond = X86::COND_O;
14276 BaseOp = X86ISD::SUB;
14277 Cond = X86::COND_B;
14280 BaseOp = X86ISD::SMUL;
14281 Cond = X86::COND_O;
14283 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14284 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14286 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14289 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14290 DAG.getConstant(X86::COND_O, MVT::i32),
14291 SDValue(Sum.getNode(), 2));
14293 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14297 // Also sets EFLAGS.
14298 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14299 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14302 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14303 DAG.getConstant(Cond, MVT::i32),
14304 SDValue(Sum.getNode(), 1));
14306 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14309 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14310 SelectionDAG &DAG) const {
14312 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14313 MVT VT = Op.getSimpleValueType();
14315 if (!Subtarget->hasSSE2() || !VT.isVector())
14318 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14319 ExtraVT.getScalarType().getSizeInBits();
14321 switch (VT.SimpleTy) {
14322 default: return SDValue();
14325 if (!Subtarget->hasFp256())
14327 if (!Subtarget->hasInt256()) {
14328 // needs to be split
14329 unsigned NumElems = VT.getVectorNumElements();
14331 // Extract the LHS vectors
14332 SDValue LHS = Op.getOperand(0);
14333 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14334 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14336 MVT EltVT = VT.getVectorElementType();
14337 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14339 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14340 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14341 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14343 SDValue Extra = DAG.getValueType(ExtraVT);
14345 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14346 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14348 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14353 SDValue Op0 = Op.getOperand(0);
14354 SDValue Op00 = Op0.getOperand(0);
14356 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14357 if (Op0.getOpcode() == ISD::BITCAST &&
14358 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14359 // (sext (vzext x)) -> (vsext x)
14360 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14361 if (Tmp1.getNode()) {
14362 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14363 // This folding is only valid when the in-reg type is a vector of i8,
14365 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14366 ExtraEltVT == MVT::i32) {
14367 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14368 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14369 "This optimization is invalid without a VZEXT.");
14370 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14376 // If the above didn't work, then just use Shift-Left + Shift-Right.
14377 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14379 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14385 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14386 SelectionDAG &DAG) {
14388 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14389 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14390 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14391 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14393 // The only fence that needs an instruction is a sequentially-consistent
14394 // cross-thread fence.
14395 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14396 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14397 // no-sse2). There isn't any reason to disable it if the target processor
14399 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14400 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14402 SDValue Chain = Op.getOperand(0);
14403 SDValue Zero = DAG.getConstant(0, MVT::i32);
14405 DAG.getRegister(X86::ESP, MVT::i32), // Base
14406 DAG.getTargetConstant(1, MVT::i8), // Scale
14407 DAG.getRegister(0, MVT::i32), // Index
14408 DAG.getTargetConstant(0, MVT::i32), // Disp
14409 DAG.getRegister(0, MVT::i32), // Segment.
14413 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14414 return SDValue(Res, 0);
14417 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14418 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14421 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14422 SelectionDAG &DAG) {
14423 MVT T = Op.getSimpleValueType();
14427 switch(T.SimpleTy) {
14428 default: llvm_unreachable("Invalid value type!");
14429 case MVT::i8: Reg = X86::AL; size = 1; break;
14430 case MVT::i16: Reg = X86::AX; size = 2; break;
14431 case MVT::i32: Reg = X86::EAX; size = 4; break;
14433 assert(Subtarget->is64Bit() && "Node not type legal!");
14434 Reg = X86::RAX; size = 8;
14437 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14438 Op.getOperand(2), SDValue());
14439 SDValue Ops[] = { cpIn.getValue(0),
14442 DAG.getTargetConstant(size, MVT::i8),
14443 cpIn.getValue(1) };
14444 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14445 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14446 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14449 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14453 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14454 SelectionDAG &DAG) {
14455 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14456 MVT DstVT = Op.getSimpleValueType();
14458 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14459 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14460 if (DstVT != MVT::f64)
14461 // This conversion needs to be expanded.
14464 SDValue InVec = Op->getOperand(0);
14466 unsigned NumElts = SrcVT.getVectorNumElements();
14467 EVT SVT = SrcVT.getVectorElementType();
14469 // Widen the vector in input in the case of MVT::v2i32.
14470 // Example: from MVT::v2i32 to MVT::v4i32.
14471 SmallVector<SDValue, 16> Elts;
14472 for (unsigned i = 0, e = NumElts; i != e; ++i)
14473 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14474 DAG.getIntPtrConstant(i)));
14476 // Explicitly mark the extra elements as Undef.
14477 SDValue Undef = DAG.getUNDEF(SVT);
14478 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14479 Elts.push_back(Undef);
14481 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14482 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14483 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14484 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14485 DAG.getIntPtrConstant(0));
14488 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14489 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14490 assert((DstVT == MVT::i64 ||
14491 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14492 "Unexpected custom BITCAST");
14493 // i64 <=> MMX conversions are Legal.
14494 if (SrcVT==MVT::i64 && DstVT.isVector())
14496 if (DstVT==MVT::i64 && SrcVT.isVector())
14498 // MMX <=> MMX conversions are Legal.
14499 if (SrcVT.isVector() && DstVT.isVector())
14501 // All other conversions need to be expanded.
14505 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14506 SDNode *Node = Op.getNode();
14508 EVT T = Node->getValueType(0);
14509 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14510 DAG.getConstant(0, T), Node->getOperand(2));
14511 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14512 cast<AtomicSDNode>(Node)->getMemoryVT(),
14513 Node->getOperand(0),
14514 Node->getOperand(1), negOp,
14515 cast<AtomicSDNode>(Node)->getMemOperand(),
14516 cast<AtomicSDNode>(Node)->getOrdering(),
14517 cast<AtomicSDNode>(Node)->getSynchScope());
14520 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14521 SDNode *Node = Op.getNode();
14523 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14525 // Convert seq_cst store -> xchg
14526 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14527 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14528 // (The only way to get a 16-byte store is cmpxchg16b)
14529 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14530 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14531 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14532 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14533 cast<AtomicSDNode>(Node)->getMemoryVT(),
14534 Node->getOperand(0),
14535 Node->getOperand(1), Node->getOperand(2),
14536 cast<AtomicSDNode>(Node)->getMemOperand(),
14537 cast<AtomicSDNode>(Node)->getOrdering(),
14538 cast<AtomicSDNode>(Node)->getSynchScope());
14539 return Swap.getValue(1);
14541 // Other atomic stores have a simple pattern.
14545 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14546 EVT VT = Op.getNode()->getSimpleValueType(0);
14548 // Let legalize expand this if it isn't a legal type yet.
14549 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14552 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14555 bool ExtraOp = false;
14556 switch (Op.getOpcode()) {
14557 default: llvm_unreachable("Invalid code");
14558 case ISD::ADDC: Opc = X86ISD::ADD; break;
14559 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14560 case ISD::SUBC: Opc = X86ISD::SUB; break;
14561 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14565 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14567 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14568 Op.getOperand(1), Op.getOperand(2));
14571 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14572 SelectionDAG &DAG) {
14573 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14575 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14576 // which returns the values as { float, float } (in XMM0) or
14577 // { double, double } (which is returned in XMM0, XMM1).
14579 SDValue Arg = Op.getOperand(0);
14580 EVT ArgVT = Arg.getValueType();
14581 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14583 TargetLowering::ArgListTy Args;
14584 TargetLowering::ArgListEntry Entry;
14588 Entry.isSExt = false;
14589 Entry.isZExt = false;
14590 Args.push_back(Entry);
14592 bool isF64 = ArgVT == MVT::f64;
14593 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14594 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14595 // the results are returned via SRet in memory.
14596 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14597 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14598 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14600 Type *RetTy = isF64
14601 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14602 : (Type*)VectorType::get(ArgTy, 4);
14604 TargetLowering::CallLoweringInfo CLI(DAG);
14605 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14606 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14608 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14611 // Returned in xmm0 and xmm1.
14612 return CallResult.first;
14614 // Returned in bits 0:31 and 32:64 xmm0.
14615 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14616 CallResult.first, DAG.getIntPtrConstant(0));
14617 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14618 CallResult.first, DAG.getIntPtrConstant(1));
14619 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14620 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14623 /// LowerOperation - Provide custom lowering hooks for some operations.
14625 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14626 switch (Op.getOpcode()) {
14627 default: llvm_unreachable("Should not custom lower this!");
14628 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14629 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14630 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14631 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14632 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14633 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14634 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14635 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14636 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14637 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14638 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14639 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14640 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14641 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14642 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14643 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14644 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14645 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14646 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14647 case ISD::SHL_PARTS:
14648 case ISD::SRA_PARTS:
14649 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14650 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14651 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14652 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14653 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14654 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14655 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14656 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14657 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14658 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14659 case ISD::FABS: return LowerFABS(Op, DAG);
14660 case ISD::FNEG: return LowerFNEG(Op, DAG);
14661 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14662 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14663 case ISD::SETCC: return LowerSETCC(Op, DAG);
14664 case ISD::SELECT: return LowerSELECT(Op, DAG);
14665 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14666 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14667 case ISD::VASTART: return LowerVASTART(Op, DAG);
14668 case ISD::VAARG: return LowerVAARG(Op, DAG);
14669 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14670 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14671 case ISD::INTRINSIC_VOID:
14672 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14673 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14674 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14675 case ISD::FRAME_TO_ARGS_OFFSET:
14676 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14677 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14678 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14679 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14680 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14681 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14682 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14683 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14684 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14685 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14686 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14687 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14688 case ISD::UMUL_LOHI:
14689 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14692 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14698 case ISD::UMULO: return LowerXALUO(Op, DAG);
14699 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14700 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14704 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14705 case ISD::ADD: return LowerADD(Op, DAG);
14706 case ISD::SUB: return LowerSUB(Op, DAG);
14707 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14711 static void ReplaceATOMIC_LOAD(SDNode *Node,
14712 SmallVectorImpl<SDValue> &Results,
14713 SelectionDAG &DAG) {
14715 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14717 // Convert wide load -> cmpxchg8b/cmpxchg16b
14718 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14719 // (The only way to get a 16-byte load is cmpxchg16b)
14720 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14721 SDValue Zero = DAG.getConstant(0, VT);
14722 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14723 Node->getOperand(0),
14724 Node->getOperand(1), Zero, Zero,
14725 cast<AtomicSDNode>(Node)->getMemOperand(),
14726 cast<AtomicSDNode>(Node)->getOrdering(),
14727 cast<AtomicSDNode>(Node)->getOrdering(),
14728 cast<AtomicSDNode>(Node)->getSynchScope());
14729 Results.push_back(Swap.getValue(0));
14730 Results.push_back(Swap.getValue(1));
14734 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14735 SelectionDAG &DAG, unsigned NewOp) {
14737 assert (Node->getValueType(0) == MVT::i64 &&
14738 "Only know how to expand i64 atomics");
14740 SDValue Chain = Node->getOperand(0);
14741 SDValue In1 = Node->getOperand(1);
14742 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14743 Node->getOperand(2), DAG.getIntPtrConstant(0));
14744 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14745 Node->getOperand(2), DAG.getIntPtrConstant(1));
14746 SDValue Ops[] = { Chain, In1, In2L, In2H };
14747 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14749 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14750 cast<MemSDNode>(Node)->getMemOperand());
14751 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14752 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14753 Results.push_back(Result.getValue(2));
14756 /// ReplaceNodeResults - Replace a node with an illegal result type
14757 /// with a new node built out of custom code.
14758 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14759 SmallVectorImpl<SDValue>&Results,
14760 SelectionDAG &DAG) const {
14762 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14763 switch (N->getOpcode()) {
14765 llvm_unreachable("Do not know how to custom type legalize this operation!");
14766 case ISD::SIGN_EXTEND_INREG:
14771 // We don't want to expand or promote these.
14778 case ISD::UDIVREM: {
14779 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14780 Results.push_back(V);
14783 case ISD::FP_TO_SINT:
14784 case ISD::FP_TO_UINT: {
14785 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14787 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14790 std::pair<SDValue,SDValue> Vals =
14791 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14792 SDValue FIST = Vals.first, StackSlot = Vals.second;
14793 if (FIST.getNode()) {
14794 EVT VT = N->getValueType(0);
14795 // Return a load from the stack slot.
14796 if (StackSlot.getNode())
14797 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14798 MachinePointerInfo(),
14799 false, false, false, 0));
14801 Results.push_back(FIST);
14805 case ISD::UINT_TO_FP: {
14806 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14807 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14808 N->getValueType(0) != MVT::v2f32)
14810 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14812 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14814 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14815 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14816 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14817 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14818 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14819 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14822 case ISD::FP_ROUND: {
14823 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14825 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14826 Results.push_back(V);
14829 case ISD::INTRINSIC_W_CHAIN: {
14830 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14832 default : llvm_unreachable("Do not know how to custom type "
14833 "legalize this intrinsic operation!");
14834 case Intrinsic::x86_rdtsc:
14835 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14837 case Intrinsic::x86_rdtscp:
14838 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14842 case ISD::READCYCLECOUNTER: {
14843 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14846 case ISD::ATOMIC_CMP_SWAP: {
14847 EVT T = N->getValueType(0);
14848 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14849 bool Regs64bit = T == MVT::i128;
14850 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14851 SDValue cpInL, cpInH;
14852 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14853 DAG.getConstant(0, HalfT));
14854 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14855 DAG.getConstant(1, HalfT));
14856 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14857 Regs64bit ? X86::RAX : X86::EAX,
14859 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14860 Regs64bit ? X86::RDX : X86::EDX,
14861 cpInH, cpInL.getValue(1));
14862 SDValue swapInL, swapInH;
14863 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14864 DAG.getConstant(0, HalfT));
14865 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14866 DAG.getConstant(1, HalfT));
14867 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14868 Regs64bit ? X86::RBX : X86::EBX,
14869 swapInL, cpInH.getValue(1));
14870 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14871 Regs64bit ? X86::RCX : X86::ECX,
14872 swapInH, swapInL.getValue(1));
14873 SDValue Ops[] = { swapInH.getValue(0),
14875 swapInH.getValue(1) };
14876 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14877 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14878 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14879 X86ISD::LCMPXCHG8_DAG;
14880 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14881 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14882 Regs64bit ? X86::RAX : X86::EAX,
14883 HalfT, Result.getValue(1));
14884 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14885 Regs64bit ? X86::RDX : X86::EDX,
14886 HalfT, cpOutL.getValue(2));
14887 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14888 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14889 Results.push_back(cpOutH.getValue(1));
14892 case ISD::ATOMIC_LOAD_ADD:
14893 case ISD::ATOMIC_LOAD_AND:
14894 case ISD::ATOMIC_LOAD_NAND:
14895 case ISD::ATOMIC_LOAD_OR:
14896 case ISD::ATOMIC_LOAD_SUB:
14897 case ISD::ATOMIC_LOAD_XOR:
14898 case ISD::ATOMIC_LOAD_MAX:
14899 case ISD::ATOMIC_LOAD_MIN:
14900 case ISD::ATOMIC_LOAD_UMAX:
14901 case ISD::ATOMIC_LOAD_UMIN:
14902 case ISD::ATOMIC_SWAP: {
14904 switch (N->getOpcode()) {
14905 default: llvm_unreachable("Unexpected opcode");
14906 case ISD::ATOMIC_LOAD_ADD:
14907 Opc = X86ISD::ATOMADD64_DAG;
14909 case ISD::ATOMIC_LOAD_AND:
14910 Opc = X86ISD::ATOMAND64_DAG;
14912 case ISD::ATOMIC_LOAD_NAND:
14913 Opc = X86ISD::ATOMNAND64_DAG;
14915 case ISD::ATOMIC_LOAD_OR:
14916 Opc = X86ISD::ATOMOR64_DAG;
14918 case ISD::ATOMIC_LOAD_SUB:
14919 Opc = X86ISD::ATOMSUB64_DAG;
14921 case ISD::ATOMIC_LOAD_XOR:
14922 Opc = X86ISD::ATOMXOR64_DAG;
14924 case ISD::ATOMIC_LOAD_MAX:
14925 Opc = X86ISD::ATOMMAX64_DAG;
14927 case ISD::ATOMIC_LOAD_MIN:
14928 Opc = X86ISD::ATOMMIN64_DAG;
14930 case ISD::ATOMIC_LOAD_UMAX:
14931 Opc = X86ISD::ATOMUMAX64_DAG;
14933 case ISD::ATOMIC_LOAD_UMIN:
14934 Opc = X86ISD::ATOMUMIN64_DAG;
14936 case ISD::ATOMIC_SWAP:
14937 Opc = X86ISD::ATOMSWAP64_DAG;
14940 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14943 case ISD::ATOMIC_LOAD: {
14944 ReplaceATOMIC_LOAD(N, Results, DAG);
14947 case ISD::BITCAST: {
14948 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14949 EVT DstVT = N->getValueType(0);
14950 EVT SrcVT = N->getOperand(0)->getValueType(0);
14952 if (SrcVT != MVT::f64 ||
14953 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14956 unsigned NumElts = DstVT.getVectorNumElements();
14957 EVT SVT = DstVT.getVectorElementType();
14958 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14959 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14960 MVT::v2f64, N->getOperand(0));
14961 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14963 SmallVector<SDValue, 8> Elts;
14964 for (unsigned i = 0, e = NumElts; i != e; ++i)
14965 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14966 ToVecInt, DAG.getIntPtrConstant(i)));
14968 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14973 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14975 default: return nullptr;
14976 case X86ISD::BSF: return "X86ISD::BSF";
14977 case X86ISD::BSR: return "X86ISD::BSR";
14978 case X86ISD::SHLD: return "X86ISD::SHLD";
14979 case X86ISD::SHRD: return "X86ISD::SHRD";
14980 case X86ISD::FAND: return "X86ISD::FAND";
14981 case X86ISD::FANDN: return "X86ISD::FANDN";
14982 case X86ISD::FOR: return "X86ISD::FOR";
14983 case X86ISD::FXOR: return "X86ISD::FXOR";
14984 case X86ISD::FSRL: return "X86ISD::FSRL";
14985 case X86ISD::FILD: return "X86ISD::FILD";
14986 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14987 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14988 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14989 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14990 case X86ISD::FLD: return "X86ISD::FLD";
14991 case X86ISD::FST: return "X86ISD::FST";
14992 case X86ISD::CALL: return "X86ISD::CALL";
14993 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14994 case X86ISD::BT: return "X86ISD::BT";
14995 case X86ISD::CMP: return "X86ISD::CMP";
14996 case X86ISD::COMI: return "X86ISD::COMI";
14997 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14998 case X86ISD::CMPM: return "X86ISD::CMPM";
14999 case X86ISD::CMPMU: return "X86ISD::CMPMU";
15000 case X86ISD::SETCC: return "X86ISD::SETCC";
15001 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
15002 case X86ISD::FSETCC: return "X86ISD::FSETCC";
15003 case X86ISD::CMOV: return "X86ISD::CMOV";
15004 case X86ISD::BRCOND: return "X86ISD::BRCOND";
15005 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
15006 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
15007 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
15008 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
15009 case X86ISD::Wrapper: return "X86ISD::Wrapper";
15010 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
15011 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
15012 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
15013 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
15014 case X86ISD::PINSRB: return "X86ISD::PINSRB";
15015 case X86ISD::PINSRW: return "X86ISD::PINSRW";
15016 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
15017 case X86ISD::ANDNP: return "X86ISD::ANDNP";
15018 case X86ISD::PSIGN: return "X86ISD::PSIGN";
15019 case X86ISD::BLENDV: return "X86ISD::BLENDV";
15020 case X86ISD::BLENDI: return "X86ISD::BLENDI";
15021 case X86ISD::SUBUS: return "X86ISD::SUBUS";
15022 case X86ISD::HADD: return "X86ISD::HADD";
15023 case X86ISD::HSUB: return "X86ISD::HSUB";
15024 case X86ISD::FHADD: return "X86ISD::FHADD";
15025 case X86ISD::FHSUB: return "X86ISD::FHSUB";
15026 case X86ISD::UMAX: return "X86ISD::UMAX";
15027 case X86ISD::UMIN: return "X86ISD::UMIN";
15028 case X86ISD::SMAX: return "X86ISD::SMAX";
15029 case X86ISD::SMIN: return "X86ISD::SMIN";
15030 case X86ISD::FMAX: return "X86ISD::FMAX";
15031 case X86ISD::FMIN: return "X86ISD::FMIN";
15032 case X86ISD::FMAXC: return "X86ISD::FMAXC";
15033 case X86ISD::FMINC: return "X86ISD::FMINC";
15034 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
15035 case X86ISD::FRCP: return "X86ISD::FRCP";
15036 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
15037 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
15038 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
15039 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
15040 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
15041 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
15042 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
15043 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
15044 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
15045 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
15046 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
15047 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
15048 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
15049 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
15050 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
15051 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
15052 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
15053 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
15054 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
15055 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
15056 case X86ISD::VZEXT: return "X86ISD::VZEXT";
15057 case X86ISD::VSEXT: return "X86ISD::VSEXT";
15058 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
15059 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
15060 case X86ISD::VINSERT: return "X86ISD::VINSERT";
15061 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
15062 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
15063 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
15064 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
15065 case X86ISD::VSHL: return "X86ISD::VSHL";
15066 case X86ISD::VSRL: return "X86ISD::VSRL";
15067 case X86ISD::VSRA: return "X86ISD::VSRA";
15068 case X86ISD::VSHLI: return "X86ISD::VSHLI";
15069 case X86ISD::VSRLI: return "X86ISD::VSRLI";
15070 case X86ISD::VSRAI: return "X86ISD::VSRAI";
15071 case X86ISD::CMPP: return "X86ISD::CMPP";
15072 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
15073 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
15074 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
15075 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
15076 case X86ISD::ADD: return "X86ISD::ADD";
15077 case X86ISD::SUB: return "X86ISD::SUB";
15078 case X86ISD::ADC: return "X86ISD::ADC";
15079 case X86ISD::SBB: return "X86ISD::SBB";
15080 case X86ISD::SMUL: return "X86ISD::SMUL";
15081 case X86ISD::UMUL: return "X86ISD::UMUL";
15082 case X86ISD::INC: return "X86ISD::INC";
15083 case X86ISD::DEC: return "X86ISD::DEC";
15084 case X86ISD::OR: return "X86ISD::OR";
15085 case X86ISD::XOR: return "X86ISD::XOR";
15086 case X86ISD::AND: return "X86ISD::AND";
15087 case X86ISD::BEXTR: return "X86ISD::BEXTR";
15088 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
15089 case X86ISD::PTEST: return "X86ISD::PTEST";
15090 case X86ISD::TESTP: return "X86ISD::TESTP";
15091 case X86ISD::TESTM: return "X86ISD::TESTM";
15092 case X86ISD::TESTNM: return "X86ISD::TESTNM";
15093 case X86ISD::KORTEST: return "X86ISD::KORTEST";
15094 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
15095 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
15096 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
15097 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
15098 case X86ISD::SHUFP: return "X86ISD::SHUFP";
15099 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
15100 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
15101 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
15102 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
15103 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
15104 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
15105 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
15106 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
15107 case X86ISD::MOVSD: return "X86ISD::MOVSD";
15108 case X86ISD::MOVSS: return "X86ISD::MOVSS";
15109 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
15110 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
15111 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
15112 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
15113 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
15114 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
15115 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
15116 case X86ISD::VPERMV: return "X86ISD::VPERMV";
15117 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
15118 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
15119 case X86ISD::VPERMI: return "X86ISD::VPERMI";
15120 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
15121 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
15122 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15123 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
15124 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
15125 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
15126 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
15127 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
15128 case X86ISD::SAHF: return "X86ISD::SAHF";
15129 case X86ISD::RDRAND: return "X86ISD::RDRAND";
15130 case X86ISD::RDSEED: return "X86ISD::RDSEED";
15131 case X86ISD::FMADD: return "X86ISD::FMADD";
15132 case X86ISD::FMSUB: return "X86ISD::FMSUB";
15133 case X86ISD::FNMADD: return "X86ISD::FNMADD";
15134 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
15135 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
15136 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
15137 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
15138 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
15139 case X86ISD::XTEST: return "X86ISD::XTEST";
15143 // isLegalAddressingMode - Return true if the addressing mode represented
15144 // by AM is legal for this target, for a load/store of the specified type.
15145 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15147 // X86 supports extremely general addressing modes.
15148 CodeModel::Model M = getTargetMachine().getCodeModel();
15149 Reloc::Model R = getTargetMachine().getRelocationModel();
15151 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15152 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15157 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15159 // If a reference to this global requires an extra load, we can't fold it.
15160 if (isGlobalStubReference(GVFlags))
15163 // If BaseGV requires a register for the PIC base, we cannot also have a
15164 // BaseReg specified.
15165 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15168 // If lower 4G is not available, then we must use rip-relative addressing.
15169 if ((M != CodeModel::Small || R != Reloc::Static) &&
15170 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15174 switch (AM.Scale) {
15180 // These scales always work.
15185 // These scales are formed with basereg+scalereg. Only accept if there is
15190 default: // Other stuff never works.
15197 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15198 unsigned Bits = Ty->getScalarSizeInBits();
15200 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15201 // particularly cheaper than those without.
15205 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15206 // variable shifts just as cheap as scalar ones.
15207 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15210 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15211 // fully general vector.
15215 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15216 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15218 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15219 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15220 return NumBits1 > NumBits2;
15223 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15224 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15227 if (!isTypeLegal(EVT::getEVT(Ty1)))
15230 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15232 // Assuming the caller doesn't have a zeroext or signext return parameter,
15233 // truncation all the way down to i1 is valid.
15237 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15238 return isInt<32>(Imm);
15241 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15242 // Can also use sub to handle negated immediates.
15243 return isInt<32>(Imm);
15246 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15247 if (!VT1.isInteger() || !VT2.isInteger())
15249 unsigned NumBits1 = VT1.getSizeInBits();
15250 unsigned NumBits2 = VT2.getSizeInBits();
15251 return NumBits1 > NumBits2;
15254 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15255 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15256 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15259 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15260 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15261 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15264 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15265 EVT VT1 = Val.getValueType();
15266 if (isZExtFree(VT1, VT2))
15269 if (Val.getOpcode() != ISD::LOAD)
15272 if (!VT1.isSimple() || !VT1.isInteger() ||
15273 !VT2.isSimple() || !VT2.isInteger())
15276 switch (VT1.getSimpleVT().SimpleTy) {
15281 // X86 has 8, 16, and 32-bit zero-extending loads.
15289 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15290 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15293 VT = VT.getScalarType();
15295 if (!VT.isSimple())
15298 switch (VT.getSimpleVT().SimpleTy) {
15309 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15310 // i16 instructions are longer (0x66 prefix) and potentially slower.
15311 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15314 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15315 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15316 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15317 /// are assumed to be legal.
15319 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15321 if (!VT.isSimple())
15324 MVT SVT = VT.getSimpleVT();
15326 // Very little shuffling can be done for 64-bit vectors right now.
15327 if (VT.getSizeInBits() == 64)
15330 // If this is a single-input shuffle with no 128 bit lane crossings we can
15331 // lower it into pshufb.
15332 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15333 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15334 bool isLegal = true;
15335 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15336 if (M[I] >= (int)SVT.getVectorNumElements() ||
15337 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15346 // FIXME: blends, shifts.
15347 return (SVT.getVectorNumElements() == 2 ||
15348 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15349 isMOVLMask(M, SVT) ||
15350 isSHUFPMask(M, SVT) ||
15351 isPSHUFDMask(M, SVT) ||
15352 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15353 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15354 isPALIGNRMask(M, SVT, Subtarget) ||
15355 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15356 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15357 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15358 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15359 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15363 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15365 if (!VT.isSimple())
15368 MVT SVT = VT.getSimpleVT();
15369 unsigned NumElts = SVT.getVectorNumElements();
15370 // FIXME: This collection of masks seems suspect.
15373 if (NumElts == 4 && SVT.is128BitVector()) {
15374 return (isMOVLMask(Mask, SVT) ||
15375 isCommutedMOVLMask(Mask, SVT, true) ||
15376 isSHUFPMask(Mask, SVT) ||
15377 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15382 //===----------------------------------------------------------------------===//
15383 // X86 Scheduler Hooks
15384 //===----------------------------------------------------------------------===//
15386 /// Utility function to emit xbegin specifying the start of an RTM region.
15387 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15388 const TargetInstrInfo *TII) {
15389 DebugLoc DL = MI->getDebugLoc();
15391 const BasicBlock *BB = MBB->getBasicBlock();
15392 MachineFunction::iterator I = MBB;
15395 // For the v = xbegin(), we generate
15406 MachineBasicBlock *thisMBB = MBB;
15407 MachineFunction *MF = MBB->getParent();
15408 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15409 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15410 MF->insert(I, mainMBB);
15411 MF->insert(I, sinkMBB);
15413 // Transfer the remainder of BB and its successor edges to sinkMBB.
15414 sinkMBB->splice(sinkMBB->begin(), MBB,
15415 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15416 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15420 // # fallthrough to mainMBB
15421 // # abortion to sinkMBB
15422 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15423 thisMBB->addSuccessor(mainMBB);
15424 thisMBB->addSuccessor(sinkMBB);
15428 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15429 mainMBB->addSuccessor(sinkMBB);
15432 // EAX is live into the sinkMBB
15433 sinkMBB->addLiveIn(X86::EAX);
15434 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15435 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15438 MI->eraseFromParent();
15442 // Get CMPXCHG opcode for the specified data type.
15443 static unsigned getCmpXChgOpcode(EVT VT) {
15444 switch (VT.getSimpleVT().SimpleTy) {
15445 case MVT::i8: return X86::LCMPXCHG8;
15446 case MVT::i16: return X86::LCMPXCHG16;
15447 case MVT::i32: return X86::LCMPXCHG32;
15448 case MVT::i64: return X86::LCMPXCHG64;
15452 llvm_unreachable("Invalid operand size!");
15455 // Get LOAD opcode for the specified data type.
15456 static unsigned getLoadOpcode(EVT VT) {
15457 switch (VT.getSimpleVT().SimpleTy) {
15458 case MVT::i8: return X86::MOV8rm;
15459 case MVT::i16: return X86::MOV16rm;
15460 case MVT::i32: return X86::MOV32rm;
15461 case MVT::i64: return X86::MOV64rm;
15465 llvm_unreachable("Invalid operand size!");
15468 // Get opcode of the non-atomic one from the specified atomic instruction.
15469 static unsigned getNonAtomicOpcode(unsigned Opc) {
15471 case X86::ATOMAND8: return X86::AND8rr;
15472 case X86::ATOMAND16: return X86::AND16rr;
15473 case X86::ATOMAND32: return X86::AND32rr;
15474 case X86::ATOMAND64: return X86::AND64rr;
15475 case X86::ATOMOR8: return X86::OR8rr;
15476 case X86::ATOMOR16: return X86::OR16rr;
15477 case X86::ATOMOR32: return X86::OR32rr;
15478 case X86::ATOMOR64: return X86::OR64rr;
15479 case X86::ATOMXOR8: return X86::XOR8rr;
15480 case X86::ATOMXOR16: return X86::XOR16rr;
15481 case X86::ATOMXOR32: return X86::XOR32rr;
15482 case X86::ATOMXOR64: return X86::XOR64rr;
15484 llvm_unreachable("Unhandled atomic-load-op opcode!");
15487 // Get opcode of the non-atomic one from the specified atomic instruction with
15489 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15490 unsigned &ExtraOpc) {
15492 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15493 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15494 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15495 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15496 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15497 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15498 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15499 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15500 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15501 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15502 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15503 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15504 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15505 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15506 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15507 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15508 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15509 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15510 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15511 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15513 llvm_unreachable("Unhandled atomic-load-op opcode!");
15516 // Get opcode of the non-atomic one from the specified atomic instruction for
15517 // 64-bit data type on 32-bit target.
15518 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15520 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15521 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15522 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15523 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15524 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15525 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15526 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15527 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15528 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15529 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15531 llvm_unreachable("Unhandled atomic-load-op opcode!");
15534 // Get opcode of the non-atomic one from the specified atomic instruction for
15535 // 64-bit data type on 32-bit target with extra opcode.
15536 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15538 unsigned &ExtraOpc) {
15540 case X86::ATOMNAND6432:
15541 ExtraOpc = X86::NOT32r;
15542 HiOpc = X86::AND32rr;
15543 return X86::AND32rr;
15545 llvm_unreachable("Unhandled atomic-load-op opcode!");
15548 // Get pseudo CMOV opcode from the specified data type.
15549 static unsigned getPseudoCMOVOpc(EVT VT) {
15550 switch (VT.getSimpleVT().SimpleTy) {
15551 case MVT::i8: return X86::CMOV_GR8;
15552 case MVT::i16: return X86::CMOV_GR16;
15553 case MVT::i32: return X86::CMOV_GR32;
15557 llvm_unreachable("Unknown CMOV opcode!");
15560 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15561 // They will be translated into a spin-loop or compare-exchange loop from
15564 // dst = atomic-fetch-op MI.addr, MI.val
15570 // t1 = LOAD MI.addr
15572 // t4 = phi(t1, t3 / loop)
15573 // t2 = OP MI.val, t4
15575 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15581 MachineBasicBlock *
15582 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15583 MachineBasicBlock *MBB) const {
15584 MachineFunction *MF = MBB->getParent();
15585 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15586 DebugLoc DL = MI->getDebugLoc();
15588 MachineRegisterInfo &MRI = MF->getRegInfo();
15590 const BasicBlock *BB = MBB->getBasicBlock();
15591 MachineFunction::iterator I = MBB;
15594 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15595 "Unexpected number of operands");
15597 assert(MI->hasOneMemOperand() &&
15598 "Expected atomic-load-op to have one memoperand");
15600 // Memory Reference
15601 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15602 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15604 unsigned DstReg, SrcReg;
15605 unsigned MemOpndSlot;
15607 unsigned CurOp = 0;
15609 DstReg = MI->getOperand(CurOp++).getReg();
15610 MemOpndSlot = CurOp;
15611 CurOp += X86::AddrNumOperands;
15612 SrcReg = MI->getOperand(CurOp++).getReg();
15614 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15615 MVT::SimpleValueType VT = *RC->vt_begin();
15616 unsigned t1 = MRI.createVirtualRegister(RC);
15617 unsigned t2 = MRI.createVirtualRegister(RC);
15618 unsigned t3 = MRI.createVirtualRegister(RC);
15619 unsigned t4 = MRI.createVirtualRegister(RC);
15620 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15622 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15623 unsigned LOADOpc = getLoadOpcode(VT);
15625 // For the atomic load-arith operator, we generate
15628 // t1 = LOAD [MI.addr]
15630 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15631 // t1 = OP MI.val, EAX
15633 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15639 MachineBasicBlock *thisMBB = MBB;
15640 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15641 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15642 MF->insert(I, mainMBB);
15643 MF->insert(I, sinkMBB);
15645 MachineInstrBuilder MIB;
15647 // Transfer the remainder of BB and its successor edges to sinkMBB.
15648 sinkMBB->splice(sinkMBB->begin(), MBB,
15649 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15650 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15653 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15654 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15655 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15657 NewMO.setIsKill(false);
15658 MIB.addOperand(NewMO);
15660 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15661 unsigned flags = (*MMOI)->getFlags();
15662 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15663 MachineMemOperand *MMO =
15664 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15665 (*MMOI)->getSize(),
15666 (*MMOI)->getBaseAlignment(),
15667 (*MMOI)->getTBAAInfo(),
15668 (*MMOI)->getRanges());
15669 MIB.addMemOperand(MMO);
15672 thisMBB->addSuccessor(mainMBB);
15675 MachineBasicBlock *origMainMBB = mainMBB;
15678 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15679 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15681 unsigned Opc = MI->getOpcode();
15684 llvm_unreachable("Unhandled atomic-load-op opcode!");
15685 case X86::ATOMAND8:
15686 case X86::ATOMAND16:
15687 case X86::ATOMAND32:
15688 case X86::ATOMAND64:
15690 case X86::ATOMOR16:
15691 case X86::ATOMOR32:
15692 case X86::ATOMOR64:
15693 case X86::ATOMXOR8:
15694 case X86::ATOMXOR16:
15695 case X86::ATOMXOR32:
15696 case X86::ATOMXOR64: {
15697 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15698 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15702 case X86::ATOMNAND8:
15703 case X86::ATOMNAND16:
15704 case X86::ATOMNAND32:
15705 case X86::ATOMNAND64: {
15706 unsigned Tmp = MRI.createVirtualRegister(RC);
15708 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15709 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15711 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15714 case X86::ATOMMAX8:
15715 case X86::ATOMMAX16:
15716 case X86::ATOMMAX32:
15717 case X86::ATOMMAX64:
15718 case X86::ATOMMIN8:
15719 case X86::ATOMMIN16:
15720 case X86::ATOMMIN32:
15721 case X86::ATOMMIN64:
15722 case X86::ATOMUMAX8:
15723 case X86::ATOMUMAX16:
15724 case X86::ATOMUMAX32:
15725 case X86::ATOMUMAX64:
15726 case X86::ATOMUMIN8:
15727 case X86::ATOMUMIN16:
15728 case X86::ATOMUMIN32:
15729 case X86::ATOMUMIN64: {
15731 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15733 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15737 if (Subtarget->hasCMov()) {
15738 if (VT != MVT::i8) {
15740 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15744 // Promote i8 to i32 to use CMOV32
15745 const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
15746 const TargetRegisterClass *RC32 =
15747 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15748 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15749 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15750 unsigned Tmp = MRI.createVirtualRegister(RC32);
15752 unsigned Undef = MRI.createVirtualRegister(RC32);
15753 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15755 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15758 .addImm(X86::sub_8bit);
15759 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15762 .addImm(X86::sub_8bit);
15764 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15768 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15769 .addReg(Tmp, 0, X86::sub_8bit);
15772 // Use pseudo select and lower them.
15773 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15774 "Invalid atomic-load-op transformation!");
15775 unsigned SelOpc = getPseudoCMOVOpc(VT);
15776 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15777 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15778 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15779 .addReg(SrcReg).addReg(t4)
15781 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15782 // Replace the original PHI node as mainMBB is changed after CMOV
15784 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15785 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15786 Phi->eraseFromParent();
15792 // Copy PhyReg back from virtual register.
15793 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15796 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15797 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15798 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15800 NewMO.setIsKill(false);
15801 MIB.addOperand(NewMO);
15804 MIB.setMemRefs(MMOBegin, MMOEnd);
15806 // Copy PhyReg back to virtual register.
15807 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15810 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15812 mainMBB->addSuccessor(origMainMBB);
15813 mainMBB->addSuccessor(sinkMBB);
15816 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15817 TII->get(TargetOpcode::COPY), DstReg)
15820 MI->eraseFromParent();
15824 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15825 // instructions. They will be translated into a spin-loop or compare-exchange
15829 // dst = atomic-fetch-op MI.addr, MI.val
15835 // t1L = LOAD [MI.addr + 0]
15836 // t1H = LOAD [MI.addr + 4]
15838 // t4L = phi(t1L, t3L / loop)
15839 // t4H = phi(t1H, t3H / loop)
15840 // t2L = OP MI.val.lo, t4L
15841 // t2H = OP MI.val.hi, t4H
15846 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15854 MachineBasicBlock *
15855 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15856 MachineBasicBlock *MBB) const {
15857 MachineFunction *MF = MBB->getParent();
15858 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15859 DebugLoc DL = MI->getDebugLoc();
15861 MachineRegisterInfo &MRI = MF->getRegInfo();
15863 const BasicBlock *BB = MBB->getBasicBlock();
15864 MachineFunction::iterator I = MBB;
15867 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15868 "Unexpected number of operands");
15870 assert(MI->hasOneMemOperand() &&
15871 "Expected atomic-load-op32 to have one memoperand");
15873 // Memory Reference
15874 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15875 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15877 unsigned DstLoReg, DstHiReg;
15878 unsigned SrcLoReg, SrcHiReg;
15879 unsigned MemOpndSlot;
15881 unsigned CurOp = 0;
15883 DstLoReg = MI->getOperand(CurOp++).getReg();
15884 DstHiReg = MI->getOperand(CurOp++).getReg();
15885 MemOpndSlot = CurOp;
15886 CurOp += X86::AddrNumOperands;
15887 SrcLoReg = MI->getOperand(CurOp++).getReg();
15888 SrcHiReg = MI->getOperand(CurOp++).getReg();
15890 const TargetRegisterClass *RC = &X86::GR32RegClass;
15891 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15893 unsigned t1L = MRI.createVirtualRegister(RC);
15894 unsigned t1H = MRI.createVirtualRegister(RC);
15895 unsigned t2L = MRI.createVirtualRegister(RC);
15896 unsigned t2H = MRI.createVirtualRegister(RC);
15897 unsigned t3L = MRI.createVirtualRegister(RC);
15898 unsigned t3H = MRI.createVirtualRegister(RC);
15899 unsigned t4L = MRI.createVirtualRegister(RC);
15900 unsigned t4H = MRI.createVirtualRegister(RC);
15902 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15903 unsigned LOADOpc = X86::MOV32rm;
15905 // For the atomic load-arith operator, we generate
15908 // t1L = LOAD [MI.addr + 0]
15909 // t1H = LOAD [MI.addr + 4]
15911 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15912 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15913 // t2L = OP MI.val.lo, t4L
15914 // t2H = OP MI.val.hi, t4H
15917 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15925 MachineBasicBlock *thisMBB = MBB;
15926 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15927 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15928 MF->insert(I, mainMBB);
15929 MF->insert(I, sinkMBB);
15931 MachineInstrBuilder MIB;
15933 // Transfer the remainder of BB and its successor edges to sinkMBB.
15934 sinkMBB->splice(sinkMBB->begin(), MBB,
15935 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15936 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15940 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15941 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15942 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15944 NewMO.setIsKill(false);
15945 MIB.addOperand(NewMO);
15947 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15948 unsigned flags = (*MMOI)->getFlags();
15949 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15950 MachineMemOperand *MMO =
15951 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15952 (*MMOI)->getSize(),
15953 (*MMOI)->getBaseAlignment(),
15954 (*MMOI)->getTBAAInfo(),
15955 (*MMOI)->getRanges());
15956 MIB.addMemOperand(MMO);
15958 MachineInstr *LowMI = MIB;
15961 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15962 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15963 if (i == X86::AddrDisp) {
15964 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15966 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15968 NewMO.setIsKill(false);
15969 MIB.addOperand(NewMO);
15972 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15974 thisMBB->addSuccessor(mainMBB);
15977 MachineBasicBlock *origMainMBB = mainMBB;
15980 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15981 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15982 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15983 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15985 unsigned Opc = MI->getOpcode();
15988 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15989 case X86::ATOMAND6432:
15990 case X86::ATOMOR6432:
15991 case X86::ATOMXOR6432:
15992 case X86::ATOMADD6432:
15993 case X86::ATOMSUB6432: {
15995 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15996 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15998 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
16002 case X86::ATOMNAND6432: {
16003 unsigned HiOpc, NOTOpc;
16004 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
16005 unsigned TmpL = MRI.createVirtualRegister(RC);
16006 unsigned TmpH = MRI.createVirtualRegister(RC);
16007 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16009 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16011 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16012 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16015 case X86::ATOMMAX6432:
16016 case X86::ATOMMIN6432:
16017 case X86::ATOMUMAX6432:
16018 case X86::ATOMUMIN6432: {
16020 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16021 unsigned cL = MRI.createVirtualRegister(RC8);
16022 unsigned cH = MRI.createVirtualRegister(RC8);
16023 unsigned cL32 = MRI.createVirtualRegister(RC);
16024 unsigned cH32 = MRI.createVirtualRegister(RC);
16025 unsigned cc = MRI.createVirtualRegister(RC);
16026 // cl := cmp src_lo, lo
16027 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16028 .addReg(SrcLoReg).addReg(t4L);
16029 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16030 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16031 // ch := cmp src_hi, hi
16032 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16033 .addReg(SrcHiReg).addReg(t4H);
16034 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16035 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16036 // cc := if (src_hi == hi) ? cl : ch;
16037 if (Subtarget->hasCMov()) {
16038 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16039 .addReg(cH32).addReg(cL32);
16041 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16042 .addReg(cH32).addReg(cL32)
16043 .addImm(X86::COND_E);
16044 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16046 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16047 if (Subtarget->hasCMov()) {
16048 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16049 .addReg(SrcLoReg).addReg(t4L);
16050 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16051 .addReg(SrcHiReg).addReg(t4H);
16053 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16054 .addReg(SrcLoReg).addReg(t4L)
16055 .addImm(X86::COND_NE);
16056 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16057 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16058 // 2nd CMOV lowering.
16059 mainMBB->addLiveIn(X86::EFLAGS);
16060 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16061 .addReg(SrcHiReg).addReg(t4H)
16062 .addImm(X86::COND_NE);
16063 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16064 // Replace the original PHI node as mainMBB is changed after CMOV
16066 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16067 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16068 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16069 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16070 PhiL->eraseFromParent();
16071 PhiH->eraseFromParent();
16075 case X86::ATOMSWAP6432: {
16077 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16078 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16079 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16084 // Copy EDX:EAX back from HiReg:LoReg
16085 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16086 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16087 // Copy ECX:EBX from t1H:t1L
16088 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16089 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16091 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16092 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16093 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16095 NewMO.setIsKill(false);
16096 MIB.addOperand(NewMO);
16098 MIB.setMemRefs(MMOBegin, MMOEnd);
16100 // Copy EDX:EAX back to t3H:t3L
16101 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16102 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16104 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16106 mainMBB->addSuccessor(origMainMBB);
16107 mainMBB->addSuccessor(sinkMBB);
16110 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16111 TII->get(TargetOpcode::COPY), DstLoReg)
16113 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16114 TII->get(TargetOpcode::COPY), DstHiReg)
16117 MI->eraseFromParent();
16121 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16122 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16123 // in the .td file.
16124 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16125 const TargetInstrInfo *TII) {
16127 switch (MI->getOpcode()) {
16128 default: llvm_unreachable("illegal opcode!");
16129 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16130 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16131 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16132 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16133 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16134 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16135 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16136 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16139 DebugLoc dl = MI->getDebugLoc();
16140 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16142 unsigned NumArgs = MI->getNumOperands();
16143 for (unsigned i = 1; i < NumArgs; ++i) {
16144 MachineOperand &Op = MI->getOperand(i);
16145 if (!(Op.isReg() && Op.isImplicit()))
16146 MIB.addOperand(Op);
16148 if (MI->hasOneMemOperand())
16149 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16151 BuildMI(*BB, MI, dl,
16152 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16153 .addReg(X86::XMM0);
16155 MI->eraseFromParent();
16159 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16160 // defs in an instruction pattern
16161 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16162 const TargetInstrInfo *TII) {
16164 switch (MI->getOpcode()) {
16165 default: llvm_unreachable("illegal opcode!");
16166 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16167 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16168 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16169 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16170 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16171 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16172 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16173 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16176 DebugLoc dl = MI->getDebugLoc();
16177 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16179 unsigned NumArgs = MI->getNumOperands(); // remove the results
16180 for (unsigned i = 1; i < NumArgs; ++i) {
16181 MachineOperand &Op = MI->getOperand(i);
16182 if (!(Op.isReg() && Op.isImplicit()))
16183 MIB.addOperand(Op);
16185 if (MI->hasOneMemOperand())
16186 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16188 BuildMI(*BB, MI, dl,
16189 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16192 MI->eraseFromParent();
16196 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16197 const TargetInstrInfo *TII,
16198 const X86Subtarget* Subtarget) {
16199 DebugLoc dl = MI->getDebugLoc();
16201 // Address into RAX/EAX, other two args into ECX, EDX.
16202 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16203 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16204 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16205 for (int i = 0; i < X86::AddrNumOperands; ++i)
16206 MIB.addOperand(MI->getOperand(i));
16208 unsigned ValOps = X86::AddrNumOperands;
16209 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16210 .addReg(MI->getOperand(ValOps).getReg());
16211 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16212 .addReg(MI->getOperand(ValOps+1).getReg());
16214 // The instruction doesn't actually take any operands though.
16215 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16217 MI->eraseFromParent(); // The pseudo is gone now.
16221 MachineBasicBlock *
16222 X86TargetLowering::EmitVAARG64WithCustomInserter(
16224 MachineBasicBlock *MBB) const {
16225 // Emit va_arg instruction on X86-64.
16227 // Operands to this pseudo-instruction:
16228 // 0 ) Output : destination address (reg)
16229 // 1-5) Input : va_list address (addr, i64mem)
16230 // 6 ) ArgSize : Size (in bytes) of vararg type
16231 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16232 // 8 ) Align : Alignment of type
16233 // 9 ) EFLAGS (implicit-def)
16235 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16236 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16238 unsigned DestReg = MI->getOperand(0).getReg();
16239 MachineOperand &Base = MI->getOperand(1);
16240 MachineOperand &Scale = MI->getOperand(2);
16241 MachineOperand &Index = MI->getOperand(3);
16242 MachineOperand &Disp = MI->getOperand(4);
16243 MachineOperand &Segment = MI->getOperand(5);
16244 unsigned ArgSize = MI->getOperand(6).getImm();
16245 unsigned ArgMode = MI->getOperand(7).getImm();
16246 unsigned Align = MI->getOperand(8).getImm();
16248 // Memory Reference
16249 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16250 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16251 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16253 // Machine Information
16254 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16255 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16256 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16257 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16258 DebugLoc DL = MI->getDebugLoc();
16260 // struct va_list {
16263 // i64 overflow_area (address)
16264 // i64 reg_save_area (address)
16266 // sizeof(va_list) = 24
16267 // alignment(va_list) = 8
16269 unsigned TotalNumIntRegs = 6;
16270 unsigned TotalNumXMMRegs = 8;
16271 bool UseGPOffset = (ArgMode == 1);
16272 bool UseFPOffset = (ArgMode == 2);
16273 unsigned MaxOffset = TotalNumIntRegs * 8 +
16274 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16276 /* Align ArgSize to a multiple of 8 */
16277 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16278 bool NeedsAlign = (Align > 8);
16280 MachineBasicBlock *thisMBB = MBB;
16281 MachineBasicBlock *overflowMBB;
16282 MachineBasicBlock *offsetMBB;
16283 MachineBasicBlock *endMBB;
16285 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16286 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16287 unsigned OffsetReg = 0;
16289 if (!UseGPOffset && !UseFPOffset) {
16290 // If we only pull from the overflow region, we don't create a branch.
16291 // We don't need to alter control flow.
16292 OffsetDestReg = 0; // unused
16293 OverflowDestReg = DestReg;
16295 offsetMBB = nullptr;
16296 overflowMBB = thisMBB;
16299 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16300 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16301 // If not, pull from overflow_area. (branch to overflowMBB)
16306 // offsetMBB overflowMBB
16311 // Registers for the PHI in endMBB
16312 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16313 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16315 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16316 MachineFunction *MF = MBB->getParent();
16317 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16318 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16319 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16321 MachineFunction::iterator MBBIter = MBB;
16324 // Insert the new basic blocks
16325 MF->insert(MBBIter, offsetMBB);
16326 MF->insert(MBBIter, overflowMBB);
16327 MF->insert(MBBIter, endMBB);
16329 // Transfer the remainder of MBB and its successor edges to endMBB.
16330 endMBB->splice(endMBB->begin(), thisMBB,
16331 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16332 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16334 // Make offsetMBB and overflowMBB successors of thisMBB
16335 thisMBB->addSuccessor(offsetMBB);
16336 thisMBB->addSuccessor(overflowMBB);
16338 // endMBB is a successor of both offsetMBB and overflowMBB
16339 offsetMBB->addSuccessor(endMBB);
16340 overflowMBB->addSuccessor(endMBB);
16342 // Load the offset value into a register
16343 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16344 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16348 .addDisp(Disp, UseFPOffset ? 4 : 0)
16349 .addOperand(Segment)
16350 .setMemRefs(MMOBegin, MMOEnd);
16352 // Check if there is enough room left to pull this argument.
16353 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16355 .addImm(MaxOffset + 8 - ArgSizeA8);
16357 // Branch to "overflowMBB" if offset >= max
16358 // Fall through to "offsetMBB" otherwise
16359 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16360 .addMBB(overflowMBB);
16363 // In offsetMBB, emit code to use the reg_save_area.
16365 assert(OffsetReg != 0);
16367 // Read the reg_save_area address.
16368 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16369 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16374 .addOperand(Segment)
16375 .setMemRefs(MMOBegin, MMOEnd);
16377 // Zero-extend the offset
16378 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16379 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16382 .addImm(X86::sub_32bit);
16384 // Add the offset to the reg_save_area to get the final address.
16385 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16386 .addReg(OffsetReg64)
16387 .addReg(RegSaveReg);
16389 // Compute the offset for the next argument
16390 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16391 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16393 .addImm(UseFPOffset ? 16 : 8);
16395 // Store it back into the va_list.
16396 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16400 .addDisp(Disp, UseFPOffset ? 4 : 0)
16401 .addOperand(Segment)
16402 .addReg(NextOffsetReg)
16403 .setMemRefs(MMOBegin, MMOEnd);
16406 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16411 // Emit code to use overflow area
16414 // Load the overflow_area address into a register.
16415 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16416 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16421 .addOperand(Segment)
16422 .setMemRefs(MMOBegin, MMOEnd);
16424 // If we need to align it, do so. Otherwise, just copy the address
16425 // to OverflowDestReg.
16427 // Align the overflow address
16428 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16429 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16431 // aligned_addr = (addr + (align-1)) & ~(align-1)
16432 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16433 .addReg(OverflowAddrReg)
16436 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16438 .addImm(~(uint64_t)(Align-1));
16440 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16441 .addReg(OverflowAddrReg);
16444 // Compute the next overflow address after this argument.
16445 // (the overflow address should be kept 8-byte aligned)
16446 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16447 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16448 .addReg(OverflowDestReg)
16449 .addImm(ArgSizeA8);
16451 // Store the new overflow address.
16452 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16457 .addOperand(Segment)
16458 .addReg(NextAddrReg)
16459 .setMemRefs(MMOBegin, MMOEnd);
16461 // If we branched, emit the PHI to the front of endMBB.
16463 BuildMI(*endMBB, endMBB->begin(), DL,
16464 TII->get(X86::PHI), DestReg)
16465 .addReg(OffsetDestReg).addMBB(offsetMBB)
16466 .addReg(OverflowDestReg).addMBB(overflowMBB);
16469 // Erase the pseudo instruction
16470 MI->eraseFromParent();
16475 MachineBasicBlock *
16476 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16478 MachineBasicBlock *MBB) const {
16479 // Emit code to save XMM registers to the stack. The ABI says that the
16480 // number of registers to save is given in %al, so it's theoretically
16481 // possible to do an indirect jump trick to avoid saving all of them,
16482 // however this code takes a simpler approach and just executes all
16483 // of the stores if %al is non-zero. It's less code, and it's probably
16484 // easier on the hardware branch predictor, and stores aren't all that
16485 // expensive anyway.
16487 // Create the new basic blocks. One block contains all the XMM stores,
16488 // and one block is the final destination regardless of whether any
16489 // stores were performed.
16490 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16491 MachineFunction *F = MBB->getParent();
16492 MachineFunction::iterator MBBIter = MBB;
16494 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16495 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16496 F->insert(MBBIter, XMMSaveMBB);
16497 F->insert(MBBIter, EndMBB);
16499 // Transfer the remainder of MBB and its successor edges to EndMBB.
16500 EndMBB->splice(EndMBB->begin(), MBB,
16501 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16502 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16504 // The original block will now fall through to the XMM save block.
16505 MBB->addSuccessor(XMMSaveMBB);
16506 // The XMMSaveMBB will fall through to the end block.
16507 XMMSaveMBB->addSuccessor(EndMBB);
16509 // Now add the instructions.
16510 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16511 DebugLoc DL = MI->getDebugLoc();
16513 unsigned CountReg = MI->getOperand(0).getReg();
16514 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16515 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16517 if (!Subtarget->isTargetWin64()) {
16518 // If %al is 0, branch around the XMM save block.
16519 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16520 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16521 MBB->addSuccessor(EndMBB);
16524 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16525 // that was just emitted, but clearly shouldn't be "saved".
16526 assert((MI->getNumOperands() <= 3 ||
16527 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16528 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16529 && "Expected last argument to be EFLAGS");
16530 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16531 // In the XMM save block, save all the XMM argument registers.
16532 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16533 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16534 MachineMemOperand *MMO =
16535 F->getMachineMemOperand(
16536 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16537 MachineMemOperand::MOStore,
16538 /*Size=*/16, /*Align=*/16);
16539 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16540 .addFrameIndex(RegSaveFrameIndex)
16541 .addImm(/*Scale=*/1)
16542 .addReg(/*IndexReg=*/0)
16543 .addImm(/*Disp=*/Offset)
16544 .addReg(/*Segment=*/0)
16545 .addReg(MI->getOperand(i).getReg())
16546 .addMemOperand(MMO);
16549 MI->eraseFromParent(); // The pseudo instruction is gone now.
16554 // The EFLAGS operand of SelectItr might be missing a kill marker
16555 // because there were multiple uses of EFLAGS, and ISel didn't know
16556 // which to mark. Figure out whether SelectItr should have had a
16557 // kill marker, and set it if it should. Returns the correct kill
16559 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16560 MachineBasicBlock* BB,
16561 const TargetRegisterInfo* TRI) {
16562 // Scan forward through BB for a use/def of EFLAGS.
16563 MachineBasicBlock::iterator miI(std::next(SelectItr));
16564 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16565 const MachineInstr& mi = *miI;
16566 if (mi.readsRegister(X86::EFLAGS))
16568 if (mi.definesRegister(X86::EFLAGS))
16569 break; // Should have kill-flag - update below.
16572 // If we hit the end of the block, check whether EFLAGS is live into a
16574 if (miI == BB->end()) {
16575 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16576 sEnd = BB->succ_end();
16577 sItr != sEnd; ++sItr) {
16578 MachineBasicBlock* succ = *sItr;
16579 if (succ->isLiveIn(X86::EFLAGS))
16584 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16585 // out. SelectMI should have a kill flag on EFLAGS.
16586 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16590 MachineBasicBlock *
16591 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16592 MachineBasicBlock *BB) const {
16593 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16594 DebugLoc DL = MI->getDebugLoc();
16596 // To "insert" a SELECT_CC instruction, we actually have to insert the
16597 // diamond control-flow pattern. The incoming instruction knows the
16598 // destination vreg to set, the condition code register to branch on, the
16599 // true/false values to select between, and a branch opcode to use.
16600 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16601 MachineFunction::iterator It = BB;
16607 // cmpTY ccX, r1, r2
16609 // fallthrough --> copy0MBB
16610 MachineBasicBlock *thisMBB = BB;
16611 MachineFunction *F = BB->getParent();
16612 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16613 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16614 F->insert(It, copy0MBB);
16615 F->insert(It, sinkMBB);
16617 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16618 // live into the sink and copy blocks.
16619 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16620 if (!MI->killsRegister(X86::EFLAGS) &&
16621 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16622 copy0MBB->addLiveIn(X86::EFLAGS);
16623 sinkMBB->addLiveIn(X86::EFLAGS);
16626 // Transfer the remainder of BB and its successor edges to sinkMBB.
16627 sinkMBB->splice(sinkMBB->begin(), BB,
16628 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16629 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16631 // Add the true and fallthrough blocks as its successors.
16632 BB->addSuccessor(copy0MBB);
16633 BB->addSuccessor(sinkMBB);
16635 // Create the conditional branch instruction.
16637 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16638 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16641 // %FalseValue = ...
16642 // # fallthrough to sinkMBB
16643 copy0MBB->addSuccessor(sinkMBB);
16646 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16648 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16649 TII->get(X86::PHI), MI->getOperand(0).getReg())
16650 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16651 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16653 MI->eraseFromParent(); // The pseudo instruction is gone now.
16657 MachineBasicBlock *
16658 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16659 bool Is64Bit) const {
16660 MachineFunction *MF = BB->getParent();
16661 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16662 DebugLoc DL = MI->getDebugLoc();
16663 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16665 assert(MF->shouldSplitStack());
16667 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16668 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16671 // ... [Till the alloca]
16672 // If stacklet is not large enough, jump to mallocMBB
16675 // Allocate by subtracting from RSP
16676 // Jump to continueMBB
16679 // Allocate by call to runtime
16683 // [rest of original BB]
16686 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16687 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16688 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16690 MachineRegisterInfo &MRI = MF->getRegInfo();
16691 const TargetRegisterClass *AddrRegClass =
16692 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16694 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16695 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16696 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16697 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16698 sizeVReg = MI->getOperand(1).getReg(),
16699 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16701 MachineFunction::iterator MBBIter = BB;
16704 MF->insert(MBBIter, bumpMBB);
16705 MF->insert(MBBIter, mallocMBB);
16706 MF->insert(MBBIter, continueMBB);
16708 continueMBB->splice(continueMBB->begin(), BB,
16709 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16710 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16712 // Add code to the main basic block to check if the stack limit has been hit,
16713 // and if so, jump to mallocMBB otherwise to bumpMBB.
16714 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16715 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16716 .addReg(tmpSPVReg).addReg(sizeVReg);
16717 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16718 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16719 .addReg(SPLimitVReg);
16720 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16722 // bumpMBB simply decreases the stack pointer, since we know the current
16723 // stacklet has enough space.
16724 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16725 .addReg(SPLimitVReg);
16726 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16727 .addReg(SPLimitVReg);
16728 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16730 // Calls into a routine in libgcc to allocate more space from the heap.
16731 const uint32_t *RegMask =
16732 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16734 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16736 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16737 .addExternalSymbol("__morestack_allocate_stack_space")
16738 .addRegMask(RegMask)
16739 .addReg(X86::RDI, RegState::Implicit)
16740 .addReg(X86::RAX, RegState::ImplicitDefine);
16742 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16744 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16745 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16746 .addExternalSymbol("__morestack_allocate_stack_space")
16747 .addRegMask(RegMask)
16748 .addReg(X86::EAX, RegState::ImplicitDefine);
16752 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16755 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16756 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16757 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16759 // Set up the CFG correctly.
16760 BB->addSuccessor(bumpMBB);
16761 BB->addSuccessor(mallocMBB);
16762 mallocMBB->addSuccessor(continueMBB);
16763 bumpMBB->addSuccessor(continueMBB);
16765 // Take care of the PHI nodes.
16766 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16767 MI->getOperand(0).getReg())
16768 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16769 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16771 // Delete the original pseudo instruction.
16772 MI->eraseFromParent();
16775 return continueMBB;
16778 MachineBasicBlock *
16779 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16780 MachineBasicBlock *BB) const {
16781 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16782 DebugLoc DL = MI->getDebugLoc();
16784 assert(!Subtarget->isTargetMacho());
16786 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16787 // non-trivial part is impdef of ESP.
16789 if (Subtarget->isTargetWin64()) {
16790 if (Subtarget->isTargetCygMing()) {
16791 // ___chkstk(Mingw64):
16792 // Clobbers R10, R11, RAX and EFLAGS.
16794 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16795 .addExternalSymbol("___chkstk")
16796 .addReg(X86::RAX, RegState::Implicit)
16797 .addReg(X86::RSP, RegState::Implicit)
16798 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16799 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16800 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16802 // __chkstk(MSVCRT): does not update stack pointer.
16803 // Clobbers R10, R11 and EFLAGS.
16804 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16805 .addExternalSymbol("__chkstk")
16806 .addReg(X86::RAX, RegState::Implicit)
16807 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16808 // RAX has the offset to be subtracted from RSP.
16809 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16814 const char *StackProbeSymbol =
16815 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16817 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16818 .addExternalSymbol(StackProbeSymbol)
16819 .addReg(X86::EAX, RegState::Implicit)
16820 .addReg(X86::ESP, RegState::Implicit)
16821 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16822 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16823 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16826 MI->eraseFromParent(); // The pseudo instruction is gone now.
16830 MachineBasicBlock *
16831 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16832 MachineBasicBlock *BB) const {
16833 // This is pretty easy. We're taking the value that we received from
16834 // our load from the relocation, sticking it in either RDI (x86-64)
16835 // or EAX and doing an indirect call. The return value will then
16836 // be in the normal return register.
16837 MachineFunction *F = BB->getParent();
16838 const X86InstrInfo *TII
16839 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
16840 DebugLoc DL = MI->getDebugLoc();
16842 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16843 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16845 // Get a register mask for the lowered call.
16846 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16847 // proper register mask.
16848 const uint32_t *RegMask =
16849 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16850 if (Subtarget->is64Bit()) {
16851 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16852 TII->get(X86::MOV64rm), X86::RDI)
16854 .addImm(0).addReg(0)
16855 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16856 MI->getOperand(3).getTargetFlags())
16858 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16859 addDirectMem(MIB, X86::RDI);
16860 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16861 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
16862 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16863 TII->get(X86::MOV32rm), X86::EAX)
16865 .addImm(0).addReg(0)
16866 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16867 MI->getOperand(3).getTargetFlags())
16869 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16870 addDirectMem(MIB, X86::EAX);
16871 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16873 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16874 TII->get(X86::MOV32rm), X86::EAX)
16875 .addReg(TII->getGlobalBaseReg(F))
16876 .addImm(0).addReg(0)
16877 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16878 MI->getOperand(3).getTargetFlags())
16880 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16881 addDirectMem(MIB, X86::EAX);
16882 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16885 MI->eraseFromParent(); // The pseudo instruction is gone now.
16889 MachineBasicBlock *
16890 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16891 MachineBasicBlock *MBB) const {
16892 DebugLoc DL = MI->getDebugLoc();
16893 MachineFunction *MF = MBB->getParent();
16894 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16895 MachineRegisterInfo &MRI = MF->getRegInfo();
16897 const BasicBlock *BB = MBB->getBasicBlock();
16898 MachineFunction::iterator I = MBB;
16901 // Memory Reference
16902 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16903 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16906 unsigned MemOpndSlot = 0;
16908 unsigned CurOp = 0;
16910 DstReg = MI->getOperand(CurOp++).getReg();
16911 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16912 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16913 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16914 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16916 MemOpndSlot = CurOp;
16918 MVT PVT = getPointerTy();
16919 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16920 "Invalid Pointer Size!");
16922 // For v = setjmp(buf), we generate
16925 // buf[LabelOffset] = restoreMBB
16926 // SjLjSetup restoreMBB
16932 // v = phi(main, restore)
16937 MachineBasicBlock *thisMBB = MBB;
16938 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16939 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16940 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16941 MF->insert(I, mainMBB);
16942 MF->insert(I, sinkMBB);
16943 MF->push_back(restoreMBB);
16945 MachineInstrBuilder MIB;
16947 // Transfer the remainder of BB and its successor edges to sinkMBB.
16948 sinkMBB->splice(sinkMBB->begin(), MBB,
16949 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16950 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16953 unsigned PtrStoreOpc = 0;
16954 unsigned LabelReg = 0;
16955 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16956 Reloc::Model RM = MF->getTarget().getRelocationModel();
16957 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
16958 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16960 // Prepare IP either in reg or imm.
16961 if (!UseImmLabel) {
16962 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16963 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16964 LabelReg = MRI.createVirtualRegister(PtrRC);
16965 if (Subtarget->is64Bit()) {
16966 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16970 .addMBB(restoreMBB)
16973 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16974 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16975 .addReg(XII->getGlobalBaseReg(MF))
16978 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16982 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16984 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16985 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16986 if (i == X86::AddrDisp)
16987 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16989 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16992 MIB.addReg(LabelReg);
16994 MIB.addMBB(restoreMBB);
16995 MIB.setMemRefs(MMOBegin, MMOEnd);
16997 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16998 .addMBB(restoreMBB);
17000 const X86RegisterInfo *RegInfo =
17001 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17002 MIB.addRegMask(RegInfo->getNoPreservedMask());
17003 thisMBB->addSuccessor(mainMBB);
17004 thisMBB->addSuccessor(restoreMBB);
17008 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17009 mainMBB->addSuccessor(sinkMBB);
17012 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17013 TII->get(X86::PHI), DstReg)
17014 .addReg(mainDstReg).addMBB(mainMBB)
17015 .addReg(restoreDstReg).addMBB(restoreMBB);
17018 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17019 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17020 restoreMBB->addSuccessor(sinkMBB);
17022 MI->eraseFromParent();
17026 MachineBasicBlock *
17027 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17028 MachineBasicBlock *MBB) const {
17029 DebugLoc DL = MI->getDebugLoc();
17030 MachineFunction *MF = MBB->getParent();
17031 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17032 MachineRegisterInfo &MRI = MF->getRegInfo();
17034 // Memory Reference
17035 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17036 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17038 MVT PVT = getPointerTy();
17039 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17040 "Invalid Pointer Size!");
17042 const TargetRegisterClass *RC =
17043 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17044 unsigned Tmp = MRI.createVirtualRegister(RC);
17045 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17046 const X86RegisterInfo *RegInfo =
17047 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17048 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17049 unsigned SP = RegInfo->getStackRegister();
17051 MachineInstrBuilder MIB;
17053 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17054 const int64_t SPOffset = 2 * PVT.getStoreSize();
17056 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17057 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17060 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17061 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17062 MIB.addOperand(MI->getOperand(i));
17063 MIB.setMemRefs(MMOBegin, MMOEnd);
17065 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17066 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17067 if (i == X86::AddrDisp)
17068 MIB.addDisp(MI->getOperand(i), LabelOffset);
17070 MIB.addOperand(MI->getOperand(i));
17072 MIB.setMemRefs(MMOBegin, MMOEnd);
17074 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17075 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17076 if (i == X86::AddrDisp)
17077 MIB.addDisp(MI->getOperand(i), SPOffset);
17079 MIB.addOperand(MI->getOperand(i));
17081 MIB.setMemRefs(MMOBegin, MMOEnd);
17083 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17085 MI->eraseFromParent();
17089 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17090 // accumulator loops. Writing back to the accumulator allows the coalescer
17091 // to remove extra copies in the loop.
17092 MachineBasicBlock *
17093 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17094 MachineBasicBlock *MBB) const {
17095 MachineOperand &AddendOp = MI->getOperand(3);
17097 // Bail out early if the addend isn't a register - we can't switch these.
17098 if (!AddendOp.isReg())
17101 MachineFunction &MF = *MBB->getParent();
17102 MachineRegisterInfo &MRI = MF.getRegInfo();
17104 // Check whether the addend is defined by a PHI:
17105 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17106 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17107 if (!AddendDef.isPHI())
17110 // Look for the following pattern:
17112 // %addend = phi [%entry, 0], [%loop, %result]
17114 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17118 // %addend = phi [%entry, 0], [%loop, %result]
17120 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17122 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17123 assert(AddendDef.getOperand(i).isReg());
17124 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17125 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17126 if (&PHISrcInst == MI) {
17127 // Found a matching instruction.
17128 unsigned NewFMAOpc = 0;
17129 switch (MI->getOpcode()) {
17130 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17131 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17132 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17133 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17134 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17135 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17136 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17137 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17138 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17139 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17140 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17141 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17142 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17143 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17144 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17145 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17146 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17147 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17148 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17149 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17150 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17151 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17152 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17153 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17154 default: llvm_unreachable("Unrecognized FMA variant.");
17157 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17158 MachineInstrBuilder MIB =
17159 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17160 .addOperand(MI->getOperand(0))
17161 .addOperand(MI->getOperand(3))
17162 .addOperand(MI->getOperand(2))
17163 .addOperand(MI->getOperand(1));
17164 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17165 MI->eraseFromParent();
17172 MachineBasicBlock *
17173 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17174 MachineBasicBlock *BB) const {
17175 switch (MI->getOpcode()) {
17176 default: llvm_unreachable("Unexpected instr type to insert");
17177 case X86::TAILJMPd64:
17178 case X86::TAILJMPr64:
17179 case X86::TAILJMPm64:
17180 llvm_unreachable("TAILJMP64 would not be touched here.");
17181 case X86::TCRETURNdi64:
17182 case X86::TCRETURNri64:
17183 case X86::TCRETURNmi64:
17185 case X86::WIN_ALLOCA:
17186 return EmitLoweredWinAlloca(MI, BB);
17187 case X86::SEG_ALLOCA_32:
17188 return EmitLoweredSegAlloca(MI, BB, false);
17189 case X86::SEG_ALLOCA_64:
17190 return EmitLoweredSegAlloca(MI, BB, true);
17191 case X86::TLSCall_32:
17192 case X86::TLSCall_64:
17193 return EmitLoweredTLSCall(MI, BB);
17194 case X86::CMOV_GR8:
17195 case X86::CMOV_FR32:
17196 case X86::CMOV_FR64:
17197 case X86::CMOV_V4F32:
17198 case X86::CMOV_V2F64:
17199 case X86::CMOV_V2I64:
17200 case X86::CMOV_V8F32:
17201 case X86::CMOV_V4F64:
17202 case X86::CMOV_V4I64:
17203 case X86::CMOV_V16F32:
17204 case X86::CMOV_V8F64:
17205 case X86::CMOV_V8I64:
17206 case X86::CMOV_GR16:
17207 case X86::CMOV_GR32:
17208 case X86::CMOV_RFP32:
17209 case X86::CMOV_RFP64:
17210 case X86::CMOV_RFP80:
17211 return EmitLoweredSelect(MI, BB);
17213 case X86::FP32_TO_INT16_IN_MEM:
17214 case X86::FP32_TO_INT32_IN_MEM:
17215 case X86::FP32_TO_INT64_IN_MEM:
17216 case X86::FP64_TO_INT16_IN_MEM:
17217 case X86::FP64_TO_INT32_IN_MEM:
17218 case X86::FP64_TO_INT64_IN_MEM:
17219 case X86::FP80_TO_INT16_IN_MEM:
17220 case X86::FP80_TO_INT32_IN_MEM:
17221 case X86::FP80_TO_INT64_IN_MEM: {
17222 MachineFunction *F = BB->getParent();
17223 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17224 DebugLoc DL = MI->getDebugLoc();
17226 // Change the floating point control register to use "round towards zero"
17227 // mode when truncating to an integer value.
17228 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17229 addFrameReference(BuildMI(*BB, MI, DL,
17230 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17232 // Load the old value of the high byte of the control word...
17234 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17235 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17238 // Set the high part to be round to zero...
17239 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17242 // Reload the modified control word now...
17243 addFrameReference(BuildMI(*BB, MI, DL,
17244 TII->get(X86::FLDCW16m)), CWFrameIdx);
17246 // Restore the memory image of control word to original value
17247 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17250 // Get the X86 opcode to use.
17252 switch (MI->getOpcode()) {
17253 default: llvm_unreachable("illegal opcode!");
17254 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17255 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17256 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17257 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17258 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17259 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17260 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17261 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17262 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17266 MachineOperand &Op = MI->getOperand(0);
17268 AM.BaseType = X86AddressMode::RegBase;
17269 AM.Base.Reg = Op.getReg();
17271 AM.BaseType = X86AddressMode::FrameIndexBase;
17272 AM.Base.FrameIndex = Op.getIndex();
17274 Op = MI->getOperand(1);
17276 AM.Scale = Op.getImm();
17277 Op = MI->getOperand(2);
17279 AM.IndexReg = Op.getImm();
17280 Op = MI->getOperand(3);
17281 if (Op.isGlobal()) {
17282 AM.GV = Op.getGlobal();
17284 AM.Disp = Op.getImm();
17286 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17287 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17289 // Reload the original control word now.
17290 addFrameReference(BuildMI(*BB, MI, DL,
17291 TII->get(X86::FLDCW16m)), CWFrameIdx);
17293 MI->eraseFromParent(); // The pseudo instruction is gone now.
17296 // String/text processing lowering.
17297 case X86::PCMPISTRM128REG:
17298 case X86::VPCMPISTRM128REG:
17299 case X86::PCMPISTRM128MEM:
17300 case X86::VPCMPISTRM128MEM:
17301 case X86::PCMPESTRM128REG:
17302 case X86::VPCMPESTRM128REG:
17303 case X86::PCMPESTRM128MEM:
17304 case X86::VPCMPESTRM128MEM:
17305 assert(Subtarget->hasSSE42() &&
17306 "Target must have SSE4.2 or AVX features enabled");
17307 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17309 // String/text processing lowering.
17310 case X86::PCMPISTRIREG:
17311 case X86::VPCMPISTRIREG:
17312 case X86::PCMPISTRIMEM:
17313 case X86::VPCMPISTRIMEM:
17314 case X86::PCMPESTRIREG:
17315 case X86::VPCMPESTRIREG:
17316 case X86::PCMPESTRIMEM:
17317 case X86::VPCMPESTRIMEM:
17318 assert(Subtarget->hasSSE42() &&
17319 "Target must have SSE4.2 or AVX features enabled");
17320 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17322 // Thread synchronization.
17324 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17328 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17330 // Atomic Lowering.
17331 case X86::ATOMAND8:
17332 case X86::ATOMAND16:
17333 case X86::ATOMAND32:
17334 case X86::ATOMAND64:
17337 case X86::ATOMOR16:
17338 case X86::ATOMOR32:
17339 case X86::ATOMOR64:
17341 case X86::ATOMXOR16:
17342 case X86::ATOMXOR8:
17343 case X86::ATOMXOR32:
17344 case X86::ATOMXOR64:
17346 case X86::ATOMNAND8:
17347 case X86::ATOMNAND16:
17348 case X86::ATOMNAND32:
17349 case X86::ATOMNAND64:
17351 case X86::ATOMMAX8:
17352 case X86::ATOMMAX16:
17353 case X86::ATOMMAX32:
17354 case X86::ATOMMAX64:
17356 case X86::ATOMMIN8:
17357 case X86::ATOMMIN16:
17358 case X86::ATOMMIN32:
17359 case X86::ATOMMIN64:
17361 case X86::ATOMUMAX8:
17362 case X86::ATOMUMAX16:
17363 case X86::ATOMUMAX32:
17364 case X86::ATOMUMAX64:
17366 case X86::ATOMUMIN8:
17367 case X86::ATOMUMIN16:
17368 case X86::ATOMUMIN32:
17369 case X86::ATOMUMIN64:
17370 return EmitAtomicLoadArith(MI, BB);
17372 // This group does 64-bit operations on a 32-bit host.
17373 case X86::ATOMAND6432:
17374 case X86::ATOMOR6432:
17375 case X86::ATOMXOR6432:
17376 case X86::ATOMNAND6432:
17377 case X86::ATOMADD6432:
17378 case X86::ATOMSUB6432:
17379 case X86::ATOMMAX6432:
17380 case X86::ATOMMIN6432:
17381 case X86::ATOMUMAX6432:
17382 case X86::ATOMUMIN6432:
17383 case X86::ATOMSWAP6432:
17384 return EmitAtomicLoadArith6432(MI, BB);
17386 case X86::VASTART_SAVE_XMM_REGS:
17387 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17389 case X86::VAARG_64:
17390 return EmitVAARG64WithCustomInserter(MI, BB);
17392 case X86::EH_SjLj_SetJmp32:
17393 case X86::EH_SjLj_SetJmp64:
17394 return emitEHSjLjSetJmp(MI, BB);
17396 case X86::EH_SjLj_LongJmp32:
17397 case X86::EH_SjLj_LongJmp64:
17398 return emitEHSjLjLongJmp(MI, BB);
17400 case TargetOpcode::STACKMAP:
17401 case TargetOpcode::PATCHPOINT:
17402 return emitPatchPoint(MI, BB);
17404 case X86::VFMADDPDr213r:
17405 case X86::VFMADDPSr213r:
17406 case X86::VFMADDSDr213r:
17407 case X86::VFMADDSSr213r:
17408 case X86::VFMSUBPDr213r:
17409 case X86::VFMSUBPSr213r:
17410 case X86::VFMSUBSDr213r:
17411 case X86::VFMSUBSSr213r:
17412 case X86::VFNMADDPDr213r:
17413 case X86::VFNMADDPSr213r:
17414 case X86::VFNMADDSDr213r:
17415 case X86::VFNMADDSSr213r:
17416 case X86::VFNMSUBPDr213r:
17417 case X86::VFNMSUBPSr213r:
17418 case X86::VFNMSUBSDr213r:
17419 case X86::VFNMSUBSSr213r:
17420 case X86::VFMADDPDr213rY:
17421 case X86::VFMADDPSr213rY:
17422 case X86::VFMSUBPDr213rY:
17423 case X86::VFMSUBPSr213rY:
17424 case X86::VFNMADDPDr213rY:
17425 case X86::VFNMADDPSr213rY:
17426 case X86::VFNMSUBPDr213rY:
17427 case X86::VFNMSUBPSr213rY:
17428 return emitFMA3Instr(MI, BB);
17432 //===----------------------------------------------------------------------===//
17433 // X86 Optimization Hooks
17434 //===----------------------------------------------------------------------===//
17436 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17439 const SelectionDAG &DAG,
17440 unsigned Depth) const {
17441 unsigned BitWidth = KnownZero.getBitWidth();
17442 unsigned Opc = Op.getOpcode();
17443 assert((Opc >= ISD::BUILTIN_OP_END ||
17444 Opc == ISD::INTRINSIC_WO_CHAIN ||
17445 Opc == ISD::INTRINSIC_W_CHAIN ||
17446 Opc == ISD::INTRINSIC_VOID) &&
17447 "Should use MaskedValueIsZero if you don't know whether Op"
17448 " is a target node!");
17450 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17464 // These nodes' second result is a boolean.
17465 if (Op.getResNo() == 0)
17468 case X86ISD::SETCC:
17469 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17471 case ISD::INTRINSIC_WO_CHAIN: {
17472 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17473 unsigned NumLoBits = 0;
17476 case Intrinsic::x86_sse_movmsk_ps:
17477 case Intrinsic::x86_avx_movmsk_ps_256:
17478 case Intrinsic::x86_sse2_movmsk_pd:
17479 case Intrinsic::x86_avx_movmsk_pd_256:
17480 case Intrinsic::x86_mmx_pmovmskb:
17481 case Intrinsic::x86_sse2_pmovmskb_128:
17482 case Intrinsic::x86_avx2_pmovmskb: {
17483 // High bits of movmskp{s|d}, pmovmskb are known zero.
17485 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17486 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17487 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17488 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17489 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17490 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17491 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17492 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17494 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17503 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17505 const SelectionDAG &,
17506 unsigned Depth) const {
17507 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17508 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17509 return Op.getValueType().getScalarType().getSizeInBits();
17515 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17516 /// node is a GlobalAddress + offset.
17517 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17518 const GlobalValue* &GA,
17519 int64_t &Offset) const {
17520 if (N->getOpcode() == X86ISD::Wrapper) {
17521 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17522 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17523 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17527 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17530 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17531 /// same as extracting the high 128-bit part of 256-bit vector and then
17532 /// inserting the result into the low part of a new 256-bit vector
17533 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17534 EVT VT = SVOp->getValueType(0);
17535 unsigned NumElems = VT.getVectorNumElements();
17537 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17538 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17539 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17540 SVOp->getMaskElt(j) >= 0)
17546 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17547 /// same as extracting the low 128-bit part of 256-bit vector and then
17548 /// inserting the result into the high part of a new 256-bit vector
17549 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17550 EVT VT = SVOp->getValueType(0);
17551 unsigned NumElems = VT.getVectorNumElements();
17553 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17554 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17555 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17556 SVOp->getMaskElt(j) >= 0)
17562 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17563 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17564 TargetLowering::DAGCombinerInfo &DCI,
17565 const X86Subtarget* Subtarget) {
17567 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17568 SDValue V1 = SVOp->getOperand(0);
17569 SDValue V2 = SVOp->getOperand(1);
17570 EVT VT = SVOp->getValueType(0);
17571 unsigned NumElems = VT.getVectorNumElements();
17573 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17574 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17578 // V UNDEF BUILD_VECTOR UNDEF
17580 // CONCAT_VECTOR CONCAT_VECTOR
17583 // RESULT: V + zero extended
17585 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17586 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17587 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17590 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17593 // To match the shuffle mask, the first half of the mask should
17594 // be exactly the first vector, and all the rest a splat with the
17595 // first element of the second one.
17596 for (unsigned i = 0; i != NumElems/2; ++i)
17597 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17598 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17601 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17602 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17603 if (Ld->hasNUsesOfValue(1, 0)) {
17604 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17605 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17607 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17609 Ld->getPointerInfo(),
17610 Ld->getAlignment(),
17611 false/*isVolatile*/, true/*ReadMem*/,
17612 false/*WriteMem*/);
17614 // Make sure the newly-created LOAD is in the same position as Ld in
17615 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17616 // and update uses of Ld's output chain to use the TokenFactor.
17617 if (Ld->hasAnyUseOfValue(1)) {
17618 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17619 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17620 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17621 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17622 SDValue(ResNode.getNode(), 1));
17625 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17629 // Emit a zeroed vector and insert the desired subvector on its
17631 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17632 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17633 return DCI.CombineTo(N, InsV);
17636 //===--------------------------------------------------------------------===//
17637 // Combine some shuffles into subvector extracts and inserts:
17640 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17641 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17642 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17643 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17644 return DCI.CombineTo(N, InsV);
17647 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17648 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17649 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17650 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17651 return DCI.CombineTo(N, InsV);
17657 /// PerformShuffleCombine - Performs several different shuffle combines.
17658 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17659 TargetLowering::DAGCombinerInfo &DCI,
17660 const X86Subtarget *Subtarget) {
17662 SDValue N0 = N->getOperand(0);
17663 SDValue N1 = N->getOperand(1);
17664 EVT VT = N->getValueType(0);
17666 // Don't create instructions with illegal types after legalize types has run.
17667 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17668 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17671 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17672 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17673 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17674 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17676 // During Type Legalization, when promoting illegal vector types,
17677 // the backend might introduce new shuffle dag nodes and bitcasts.
17679 // This code performs the following transformation:
17680 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17681 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17683 // We do this only if both the bitcast and the BINOP dag nodes have
17684 // one use. Also, perform this transformation only if the new binary
17685 // operation is legal. This is to avoid introducing dag nodes that
17686 // potentially need to be further expanded (or custom lowered) into a
17687 // less optimal sequence of dag nodes.
17688 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17689 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17690 N0.getOpcode() == ISD::BITCAST) {
17691 SDValue BC0 = N0.getOperand(0);
17692 EVT SVT = BC0.getValueType();
17693 unsigned Opcode = BC0.getOpcode();
17694 unsigned NumElts = VT.getVectorNumElements();
17696 if (BC0.hasOneUse() && SVT.isVector() &&
17697 SVT.getVectorNumElements() * 2 == NumElts &&
17698 TLI.isOperationLegal(Opcode, VT)) {
17699 bool CanFold = false;
17711 unsigned SVTNumElts = SVT.getVectorNumElements();
17712 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17713 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17714 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17715 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17716 CanFold = SVOp->getMaskElt(i) < 0;
17719 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17720 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17721 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17722 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17727 // Only handle 128 wide vector from here on.
17728 if (!VT.is128BitVector())
17731 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17732 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17733 // consecutive, non-overlapping, and in the right order.
17734 SmallVector<SDValue, 16> Elts;
17735 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17736 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17738 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17741 /// PerformTruncateCombine - Converts truncate operation to
17742 /// a sequence of vector shuffle operations.
17743 /// It is possible when we truncate 256-bit vector to 128-bit vector
17744 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17745 TargetLowering::DAGCombinerInfo &DCI,
17746 const X86Subtarget *Subtarget) {
17750 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17751 /// specific shuffle of a load can be folded into a single element load.
17752 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17753 /// shuffles have been customed lowered so we need to handle those here.
17754 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17755 TargetLowering::DAGCombinerInfo &DCI) {
17756 if (DCI.isBeforeLegalizeOps())
17759 SDValue InVec = N->getOperand(0);
17760 SDValue EltNo = N->getOperand(1);
17762 if (!isa<ConstantSDNode>(EltNo))
17765 EVT VT = InVec.getValueType();
17767 bool HasShuffleIntoBitcast = false;
17768 if (InVec.getOpcode() == ISD::BITCAST) {
17769 // Don't duplicate a load with other uses.
17770 if (!InVec.hasOneUse())
17772 EVT BCVT = InVec.getOperand(0).getValueType();
17773 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17775 InVec = InVec.getOperand(0);
17776 HasShuffleIntoBitcast = true;
17779 if (!isTargetShuffle(InVec.getOpcode()))
17782 // Don't duplicate a load with other uses.
17783 if (!InVec.hasOneUse())
17786 SmallVector<int, 16> ShuffleMask;
17788 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17792 // Select the input vector, guarding against out of range extract vector.
17793 unsigned NumElems = VT.getVectorNumElements();
17794 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17795 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17796 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17797 : InVec.getOperand(1);
17799 // If inputs to shuffle are the same for both ops, then allow 2 uses
17800 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17802 if (LdNode.getOpcode() == ISD::BITCAST) {
17803 // Don't duplicate a load with other uses.
17804 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17807 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17808 LdNode = LdNode.getOperand(0);
17811 if (!ISD::isNormalLoad(LdNode.getNode()))
17814 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17816 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17819 if (HasShuffleIntoBitcast) {
17820 // If there's a bitcast before the shuffle, check if the load type and
17821 // alignment is valid.
17822 unsigned Align = LN0->getAlignment();
17823 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17824 unsigned NewAlign = TLI.getDataLayout()->
17825 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17827 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17831 // All checks match so transform back to vector_shuffle so that DAG combiner
17832 // can finish the job
17835 // Create shuffle node taking into account the case that its a unary shuffle
17836 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17837 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17838 InVec.getOperand(0), Shuffle,
17840 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17841 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17845 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17846 /// generation and convert it from being a bunch of shuffles and extracts
17847 /// to a simple store and scalar loads to extract the elements.
17848 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17849 TargetLowering::DAGCombinerInfo &DCI) {
17850 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17851 if (NewOp.getNode())
17854 SDValue InputVector = N->getOperand(0);
17856 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17857 // from mmx to v2i32 has a single usage.
17858 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17859 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17860 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17861 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17862 N->getValueType(0),
17863 InputVector.getNode()->getOperand(0));
17865 // Only operate on vectors of 4 elements, where the alternative shuffling
17866 // gets to be more expensive.
17867 if (InputVector.getValueType() != MVT::v4i32)
17870 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17871 // single use which is a sign-extend or zero-extend, and all elements are
17873 SmallVector<SDNode *, 4> Uses;
17874 unsigned ExtractedElements = 0;
17875 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17876 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17877 if (UI.getUse().getResNo() != InputVector.getResNo())
17880 SDNode *Extract = *UI;
17881 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17884 if (Extract->getValueType(0) != MVT::i32)
17886 if (!Extract->hasOneUse())
17888 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17889 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17891 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17894 // Record which element was extracted.
17895 ExtractedElements |=
17896 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17898 Uses.push_back(Extract);
17901 // If not all the elements were used, this may not be worthwhile.
17902 if (ExtractedElements != 15)
17905 // Ok, we've now decided to do the transformation.
17906 SDLoc dl(InputVector);
17908 // Store the value to a temporary stack slot.
17909 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17910 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17911 MachinePointerInfo(), false, false, 0);
17913 // Replace each use (extract) with a load of the appropriate element.
17914 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17915 UE = Uses.end(); UI != UE; ++UI) {
17916 SDNode *Extract = *UI;
17918 // cOMpute the element's address.
17919 SDValue Idx = Extract->getOperand(1);
17921 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17922 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17924 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17926 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17927 StackPtr, OffsetVal);
17929 // Load the scalar.
17930 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17931 ScalarAddr, MachinePointerInfo(),
17932 false, false, false, 0);
17934 // Replace the exact with the load.
17935 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17938 // The replacement was made in place; don't return anything.
17942 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17943 static std::pair<unsigned, bool>
17944 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17945 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17946 if (!VT.isVector())
17947 return std::make_pair(0, false);
17949 bool NeedSplit = false;
17950 switch (VT.getSimpleVT().SimpleTy) {
17951 default: return std::make_pair(0, false);
17955 if (!Subtarget->hasAVX2())
17957 if (!Subtarget->hasAVX())
17958 return std::make_pair(0, false);
17963 if (!Subtarget->hasSSE2())
17964 return std::make_pair(0, false);
17967 // SSE2 has only a small subset of the operations.
17968 bool hasUnsigned = Subtarget->hasSSE41() ||
17969 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17970 bool hasSigned = Subtarget->hasSSE41() ||
17971 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17973 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17976 // Check for x CC y ? x : y.
17977 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17978 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17983 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17986 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17989 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17992 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17994 // Check for x CC y ? y : x -- a min/max with reversed arms.
17995 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17996 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18001 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18004 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18007 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18010 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18014 return std::make_pair(Opc, NeedSplit);
18018 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18019 const X86Subtarget *Subtarget) {
18021 SDValue Cond = N->getOperand(0);
18022 SDValue LHS = N->getOperand(1);
18023 SDValue RHS = N->getOperand(2);
18025 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18026 SDValue CondSrc = Cond->getOperand(0);
18027 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18028 Cond = CondSrc->getOperand(0);
18031 MVT VT = N->getSimpleValueType(0);
18032 MVT EltVT = VT.getVectorElementType();
18033 unsigned NumElems = VT.getVectorNumElements();
18034 // There is no blend with immediate in AVX-512.
18035 if (VT.is512BitVector())
18038 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18040 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18043 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18046 unsigned MaskValue = 0;
18047 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18050 SmallVector<int, 8> ShuffleMask(NumElems, -1);
18051 for (unsigned i = 0; i < NumElems; ++i) {
18052 // Be sure we emit undef where we can.
18053 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18054 ShuffleMask[i] = -1;
18056 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18059 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18062 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18064 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18065 TargetLowering::DAGCombinerInfo &DCI,
18066 const X86Subtarget *Subtarget) {
18068 SDValue Cond = N->getOperand(0);
18069 // Get the LHS/RHS of the select.
18070 SDValue LHS = N->getOperand(1);
18071 SDValue RHS = N->getOperand(2);
18072 EVT VT = LHS.getValueType();
18073 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18075 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18076 // instructions match the semantics of the common C idiom x<y?x:y but not
18077 // x<=y?x:y, because of how they handle negative zero (which can be
18078 // ignored in unsafe-math mode).
18079 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18080 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18081 (Subtarget->hasSSE2() ||
18082 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18083 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18085 unsigned Opcode = 0;
18086 // Check for x CC y ? x : y.
18087 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18088 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18092 // Converting this to a min would handle NaNs incorrectly, and swapping
18093 // the operands would cause it to handle comparisons between positive
18094 // and negative zero incorrectly.
18095 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18096 if (!DAG.getTarget().Options.UnsafeFPMath &&
18097 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18099 std::swap(LHS, RHS);
18101 Opcode = X86ISD::FMIN;
18104 // Converting this to a min would handle comparisons between positive
18105 // and negative zero incorrectly.
18106 if (!DAG.getTarget().Options.UnsafeFPMath &&
18107 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18109 Opcode = X86ISD::FMIN;
18112 // Converting this to a min would handle both negative zeros and NaNs
18113 // incorrectly, but we can swap the operands to fix both.
18114 std::swap(LHS, RHS);
18118 Opcode = X86ISD::FMIN;
18122 // Converting this to a max would handle comparisons between positive
18123 // and negative zero incorrectly.
18124 if (!DAG.getTarget().Options.UnsafeFPMath &&
18125 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18127 Opcode = X86ISD::FMAX;
18130 // Converting this to a max would handle NaNs incorrectly, and swapping
18131 // the operands would cause it to handle comparisons between positive
18132 // and negative zero incorrectly.
18133 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18134 if (!DAG.getTarget().Options.UnsafeFPMath &&
18135 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18137 std::swap(LHS, RHS);
18139 Opcode = X86ISD::FMAX;
18142 // Converting this to a max would handle both negative zeros and NaNs
18143 // incorrectly, but we can swap the operands to fix both.
18144 std::swap(LHS, RHS);
18148 Opcode = X86ISD::FMAX;
18151 // Check for x CC y ? y : x -- a min/max with reversed arms.
18152 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18153 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18157 // Converting this to a min would handle comparisons between positive
18158 // and negative zero incorrectly, and swapping the operands would
18159 // cause it to handle NaNs incorrectly.
18160 if (!DAG.getTarget().Options.UnsafeFPMath &&
18161 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18162 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18164 std::swap(LHS, RHS);
18166 Opcode = X86ISD::FMIN;
18169 // Converting this to a min would handle NaNs incorrectly.
18170 if (!DAG.getTarget().Options.UnsafeFPMath &&
18171 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18173 Opcode = X86ISD::FMIN;
18176 // Converting this to a min would handle both negative zeros and NaNs
18177 // incorrectly, but we can swap the operands to fix both.
18178 std::swap(LHS, RHS);
18182 Opcode = X86ISD::FMIN;
18186 // Converting this to a max would handle NaNs incorrectly.
18187 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18189 Opcode = X86ISD::FMAX;
18192 // Converting this to a max would handle comparisons between positive
18193 // and negative zero incorrectly, and swapping the operands would
18194 // cause it to handle NaNs incorrectly.
18195 if (!DAG.getTarget().Options.UnsafeFPMath &&
18196 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18197 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18199 std::swap(LHS, RHS);
18201 Opcode = X86ISD::FMAX;
18204 // Converting this to a max would handle both negative zeros and NaNs
18205 // incorrectly, but we can swap the operands to fix both.
18206 std::swap(LHS, RHS);
18210 Opcode = X86ISD::FMAX;
18216 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18219 EVT CondVT = Cond.getValueType();
18220 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18221 CondVT.getVectorElementType() == MVT::i1) {
18222 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18223 // lowering on AVX-512. In this case we convert it to
18224 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18225 // The same situation for all 128 and 256-bit vectors of i8 and i16
18226 EVT OpVT = LHS.getValueType();
18227 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18228 (OpVT.getVectorElementType() == MVT::i8 ||
18229 OpVT.getVectorElementType() == MVT::i16)) {
18230 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18231 DCI.AddToWorklist(Cond.getNode());
18232 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18235 // If this is a select between two integer constants, try to do some
18237 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18238 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18239 // Don't do this for crazy integer types.
18240 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18241 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18242 // so that TrueC (the true value) is larger than FalseC.
18243 bool NeedsCondInvert = false;
18245 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18246 // Efficiently invertible.
18247 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18248 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18249 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18250 NeedsCondInvert = true;
18251 std::swap(TrueC, FalseC);
18254 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18255 if (FalseC->getAPIntValue() == 0 &&
18256 TrueC->getAPIntValue().isPowerOf2()) {
18257 if (NeedsCondInvert) // Invert the condition if needed.
18258 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18259 DAG.getConstant(1, Cond.getValueType()));
18261 // Zero extend the condition if needed.
18262 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18264 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18265 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18266 DAG.getConstant(ShAmt, MVT::i8));
18269 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18270 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18271 if (NeedsCondInvert) // Invert the condition if needed.
18272 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18273 DAG.getConstant(1, Cond.getValueType()));
18275 // Zero extend the condition if needed.
18276 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18277 FalseC->getValueType(0), Cond);
18278 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18279 SDValue(FalseC, 0));
18282 // Optimize cases that will turn into an LEA instruction. This requires
18283 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18284 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18285 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18286 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18288 bool isFastMultiplier = false;
18290 switch ((unsigned char)Diff) {
18292 case 1: // result = add base, cond
18293 case 2: // result = lea base( , cond*2)
18294 case 3: // result = lea base(cond, cond*2)
18295 case 4: // result = lea base( , cond*4)
18296 case 5: // result = lea base(cond, cond*4)
18297 case 8: // result = lea base( , cond*8)
18298 case 9: // result = lea base(cond, cond*8)
18299 isFastMultiplier = true;
18304 if (isFastMultiplier) {
18305 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18306 if (NeedsCondInvert) // Invert the condition if needed.
18307 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18308 DAG.getConstant(1, Cond.getValueType()));
18310 // Zero extend the condition if needed.
18311 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18313 // Scale the condition by the difference.
18315 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18316 DAG.getConstant(Diff, Cond.getValueType()));
18318 // Add the base if non-zero.
18319 if (FalseC->getAPIntValue() != 0)
18320 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18321 SDValue(FalseC, 0));
18328 // Canonicalize max and min:
18329 // (x > y) ? x : y -> (x >= y) ? x : y
18330 // (x < y) ? x : y -> (x <= y) ? x : y
18331 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18332 // the need for an extra compare
18333 // against zero. e.g.
18334 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18336 // testl %edi, %edi
18338 // cmovgl %edi, %eax
18342 // cmovsl %eax, %edi
18343 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18344 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18345 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18346 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18351 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18352 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18353 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18354 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18359 // Early exit check
18360 if (!TLI.isTypeLegal(VT))
18363 // Match VSELECTs into subs with unsigned saturation.
18364 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18365 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18366 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18367 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18368 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18370 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18371 // left side invert the predicate to simplify logic below.
18373 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18375 CC = ISD::getSetCCInverse(CC, true);
18376 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18380 if (Other.getNode() && Other->getNumOperands() == 2 &&
18381 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18382 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18383 SDValue CondRHS = Cond->getOperand(1);
18385 // Look for a general sub with unsigned saturation first.
18386 // x >= y ? x-y : 0 --> subus x, y
18387 // x > y ? x-y : 0 --> subus x, y
18388 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18389 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18390 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18392 // If the RHS is a constant we have to reverse the const canonicalization.
18393 // x > C-1 ? x+-C : 0 --> subus x, C
18394 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18395 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18396 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18397 if (CondRHS.getConstantOperandVal(0) == -A-1)
18398 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18399 DAG.getConstant(-A, VT));
18402 // Another special case: If C was a sign bit, the sub has been
18403 // canonicalized into a xor.
18404 // FIXME: Would it be better to use computeKnownBits to determine whether
18405 // it's safe to decanonicalize the xor?
18406 // x s< 0 ? x^C : 0 --> subus x, C
18407 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18408 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18409 isSplatVector(OpRHS.getNode())) {
18410 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18412 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18417 // Try to match a min/max vector operation.
18418 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18419 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18420 unsigned Opc = ret.first;
18421 bool NeedSplit = ret.second;
18423 if (Opc && NeedSplit) {
18424 unsigned NumElems = VT.getVectorNumElements();
18425 // Extract the LHS vectors
18426 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18427 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18429 // Extract the RHS vectors
18430 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18431 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18433 // Create min/max for each subvector
18434 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18435 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18437 // Merge the result
18438 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18440 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18443 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18444 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18445 // Check if SETCC has already been promoted
18446 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18447 // Check that condition value type matches vselect operand type
18450 assert(Cond.getValueType().isVector() &&
18451 "vector select expects a vector selector!");
18453 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18454 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18456 if (!TValIsAllOnes && !FValIsAllZeros) {
18457 // Try invert the condition if true value is not all 1s and false value
18459 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18460 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18462 if (TValIsAllZeros || FValIsAllOnes) {
18463 SDValue CC = Cond.getOperand(2);
18464 ISD::CondCode NewCC =
18465 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18466 Cond.getOperand(0).getValueType().isInteger());
18467 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18468 std::swap(LHS, RHS);
18469 TValIsAllOnes = FValIsAllOnes;
18470 FValIsAllZeros = TValIsAllZeros;
18474 if (TValIsAllOnes || FValIsAllZeros) {
18477 if (TValIsAllOnes && FValIsAllZeros)
18479 else if (TValIsAllOnes)
18480 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18481 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18482 else if (FValIsAllZeros)
18483 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18484 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18486 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18490 // Try to fold this VSELECT into a MOVSS/MOVSD
18491 if (N->getOpcode() == ISD::VSELECT &&
18492 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18493 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18494 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18495 bool CanFold = false;
18496 unsigned NumElems = Cond.getNumOperands();
18500 if (isZero(Cond.getOperand(0))) {
18503 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18504 // fold (vselect <0,-1> -> (movsd A, B)
18505 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18506 CanFold = isAllOnes(Cond.getOperand(i));
18507 } else if (isAllOnes(Cond.getOperand(0))) {
18511 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18512 // fold (vselect <-1,0> -> (movsd B, A)
18513 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18514 CanFold = isZero(Cond.getOperand(i));
18518 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18519 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18520 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18523 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18524 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18525 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18526 // (v2i64 (bitcast B)))))
18528 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18529 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18530 // (v2f64 (bitcast B)))))
18532 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18533 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18534 // (v2i64 (bitcast A)))))
18536 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18537 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18538 // (v2f64 (bitcast A)))))
18540 CanFold = (isZero(Cond.getOperand(0)) &&
18541 isZero(Cond.getOperand(1)) &&
18542 isAllOnes(Cond.getOperand(2)) &&
18543 isAllOnes(Cond.getOperand(3)));
18545 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18546 isAllOnes(Cond.getOperand(1)) &&
18547 isZero(Cond.getOperand(2)) &&
18548 isZero(Cond.getOperand(3))) {
18550 std::swap(LHS, RHS);
18554 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18555 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18556 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18557 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18559 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18565 // If we know that this node is legal then we know that it is going to be
18566 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18567 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18568 // to simplify previous instructions.
18569 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18570 !DCI.isBeforeLegalize() &&
18571 // We explicitly check against v8i16 and v16i16 because, although
18572 // they're marked as Custom, they might only be legal when Cond is a
18573 // build_vector of constants. This will be taken care in a later
18575 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18576 VT != MVT::v8i16)) {
18577 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18579 // Don't optimize vector selects that map to mask-registers.
18583 // Check all uses of that condition operand to check whether it will be
18584 // consumed by non-BLEND instructions, which may depend on all bits are set
18586 for (SDNode::use_iterator I = Cond->use_begin(),
18587 E = Cond->use_end(); I != E; ++I)
18588 if (I->getOpcode() != ISD::VSELECT)
18589 // TODO: Add other opcodes eventually lowered into BLEND.
18592 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18593 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18595 APInt KnownZero, KnownOne;
18596 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18597 DCI.isBeforeLegalizeOps());
18598 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18599 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18600 DCI.CommitTargetLoweringOpt(TLO);
18603 // We should generate an X86ISD::BLENDI from a vselect if its argument
18604 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18605 // constants. This specific pattern gets generated when we split a
18606 // selector for a 512 bit vector in a machine without AVX512 (but with
18607 // 256-bit vectors), during legalization:
18609 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18611 // Iff we find this pattern and the build_vectors are built from
18612 // constants, we translate the vselect into a shuffle_vector that we
18613 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18614 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18615 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18616 if (Shuffle.getNode())
18623 // Check whether a boolean test is testing a boolean value generated by
18624 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18627 // Simplify the following patterns:
18628 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18629 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18630 // to (Op EFLAGS Cond)
18632 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18633 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18634 // to (Op EFLAGS !Cond)
18636 // where Op could be BRCOND or CMOV.
18638 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18639 // Quit if not CMP and SUB with its value result used.
18640 if (Cmp.getOpcode() != X86ISD::CMP &&
18641 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18644 // Quit if not used as a boolean value.
18645 if (CC != X86::COND_E && CC != X86::COND_NE)
18648 // Check CMP operands. One of them should be 0 or 1 and the other should be
18649 // an SetCC or extended from it.
18650 SDValue Op1 = Cmp.getOperand(0);
18651 SDValue Op2 = Cmp.getOperand(1);
18654 const ConstantSDNode* C = nullptr;
18655 bool needOppositeCond = (CC == X86::COND_E);
18656 bool checkAgainstTrue = false; // Is it a comparison against 1?
18658 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18660 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18662 else // Quit if all operands are not constants.
18665 if (C->getZExtValue() == 1) {
18666 needOppositeCond = !needOppositeCond;
18667 checkAgainstTrue = true;
18668 } else if (C->getZExtValue() != 0)
18669 // Quit if the constant is neither 0 or 1.
18672 bool truncatedToBoolWithAnd = false;
18673 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18674 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18675 SetCC.getOpcode() == ISD::TRUNCATE ||
18676 SetCC.getOpcode() == ISD::AND) {
18677 if (SetCC.getOpcode() == ISD::AND) {
18679 ConstantSDNode *CS;
18680 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18681 CS->getZExtValue() == 1)
18683 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18684 CS->getZExtValue() == 1)
18688 SetCC = SetCC.getOperand(OpIdx);
18689 truncatedToBoolWithAnd = true;
18691 SetCC = SetCC.getOperand(0);
18694 switch (SetCC.getOpcode()) {
18695 case X86ISD::SETCC_CARRY:
18696 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18697 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18698 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18699 // truncated to i1 using 'and'.
18700 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18702 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18703 "Invalid use of SETCC_CARRY!");
18705 case X86ISD::SETCC:
18706 // Set the condition code or opposite one if necessary.
18707 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18708 if (needOppositeCond)
18709 CC = X86::GetOppositeBranchCondition(CC);
18710 return SetCC.getOperand(1);
18711 case X86ISD::CMOV: {
18712 // Check whether false/true value has canonical one, i.e. 0 or 1.
18713 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18714 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18715 // Quit if true value is not a constant.
18718 // Quit if false value is not a constant.
18720 SDValue Op = SetCC.getOperand(0);
18721 // Skip 'zext' or 'trunc' node.
18722 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18723 Op.getOpcode() == ISD::TRUNCATE)
18724 Op = Op.getOperand(0);
18725 // A special case for rdrand/rdseed, where 0 is set if false cond is
18727 if ((Op.getOpcode() != X86ISD::RDRAND &&
18728 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18731 // Quit if false value is not the constant 0 or 1.
18732 bool FValIsFalse = true;
18733 if (FVal && FVal->getZExtValue() != 0) {
18734 if (FVal->getZExtValue() != 1)
18736 // If FVal is 1, opposite cond is needed.
18737 needOppositeCond = !needOppositeCond;
18738 FValIsFalse = false;
18740 // Quit if TVal is not the constant opposite of FVal.
18741 if (FValIsFalse && TVal->getZExtValue() != 1)
18743 if (!FValIsFalse && TVal->getZExtValue() != 0)
18745 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18746 if (needOppositeCond)
18747 CC = X86::GetOppositeBranchCondition(CC);
18748 return SetCC.getOperand(3);
18755 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18756 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18757 TargetLowering::DAGCombinerInfo &DCI,
18758 const X86Subtarget *Subtarget) {
18761 // If the flag operand isn't dead, don't touch this CMOV.
18762 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18765 SDValue FalseOp = N->getOperand(0);
18766 SDValue TrueOp = N->getOperand(1);
18767 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18768 SDValue Cond = N->getOperand(3);
18770 if (CC == X86::COND_E || CC == X86::COND_NE) {
18771 switch (Cond.getOpcode()) {
18775 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18776 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18777 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18783 Flags = checkBoolTestSetCCCombine(Cond, CC);
18784 if (Flags.getNode() &&
18785 // Extra check as FCMOV only supports a subset of X86 cond.
18786 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18787 SDValue Ops[] = { FalseOp, TrueOp,
18788 DAG.getConstant(CC, MVT::i8), Flags };
18789 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18792 // If this is a select between two integer constants, try to do some
18793 // optimizations. Note that the operands are ordered the opposite of SELECT
18795 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18796 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18797 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18798 // larger than FalseC (the false value).
18799 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18800 CC = X86::GetOppositeBranchCondition(CC);
18801 std::swap(TrueC, FalseC);
18802 std::swap(TrueOp, FalseOp);
18805 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18806 // This is efficient for any integer data type (including i8/i16) and
18808 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18809 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18810 DAG.getConstant(CC, MVT::i8), Cond);
18812 // Zero extend the condition if needed.
18813 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18815 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18816 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18817 DAG.getConstant(ShAmt, MVT::i8));
18818 if (N->getNumValues() == 2) // Dead flag value?
18819 return DCI.CombineTo(N, Cond, SDValue());
18823 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18824 // for any integer data type, including i8/i16.
18825 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18826 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18827 DAG.getConstant(CC, MVT::i8), Cond);
18829 // Zero extend the condition if needed.
18830 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18831 FalseC->getValueType(0), Cond);
18832 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18833 SDValue(FalseC, 0));
18835 if (N->getNumValues() == 2) // Dead flag value?
18836 return DCI.CombineTo(N, Cond, SDValue());
18840 // Optimize cases that will turn into an LEA instruction. This requires
18841 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18842 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18843 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18844 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18846 bool isFastMultiplier = false;
18848 switch ((unsigned char)Diff) {
18850 case 1: // result = add base, cond
18851 case 2: // result = lea base( , cond*2)
18852 case 3: // result = lea base(cond, cond*2)
18853 case 4: // result = lea base( , cond*4)
18854 case 5: // result = lea base(cond, cond*4)
18855 case 8: // result = lea base( , cond*8)
18856 case 9: // result = lea base(cond, cond*8)
18857 isFastMultiplier = true;
18862 if (isFastMultiplier) {
18863 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18864 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18865 DAG.getConstant(CC, MVT::i8), Cond);
18866 // Zero extend the condition if needed.
18867 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18869 // Scale the condition by the difference.
18871 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18872 DAG.getConstant(Diff, Cond.getValueType()));
18874 // Add the base if non-zero.
18875 if (FalseC->getAPIntValue() != 0)
18876 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18877 SDValue(FalseC, 0));
18878 if (N->getNumValues() == 2) // Dead flag value?
18879 return DCI.CombineTo(N, Cond, SDValue());
18886 // Handle these cases:
18887 // (select (x != c), e, c) -> select (x != c), e, x),
18888 // (select (x == c), c, e) -> select (x == c), x, e)
18889 // where the c is an integer constant, and the "select" is the combination
18890 // of CMOV and CMP.
18892 // The rationale for this change is that the conditional-move from a constant
18893 // needs two instructions, however, conditional-move from a register needs
18894 // only one instruction.
18896 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18897 // some instruction-combining opportunities. This opt needs to be
18898 // postponed as late as possible.
18900 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18901 // the DCI.xxxx conditions are provided to postpone the optimization as
18902 // late as possible.
18904 ConstantSDNode *CmpAgainst = nullptr;
18905 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18906 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18907 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18909 if (CC == X86::COND_NE &&
18910 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18911 CC = X86::GetOppositeBranchCondition(CC);
18912 std::swap(TrueOp, FalseOp);
18915 if (CC == X86::COND_E &&
18916 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18917 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18918 DAG.getConstant(CC, MVT::i8), Cond };
18919 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18927 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18928 const X86Subtarget *Subtarget) {
18929 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18931 default: return SDValue();
18932 // SSE/AVX/AVX2 blend intrinsics.
18933 case Intrinsic::x86_avx2_pblendvb:
18934 case Intrinsic::x86_avx2_pblendw:
18935 case Intrinsic::x86_avx2_pblendd_128:
18936 case Intrinsic::x86_avx2_pblendd_256:
18937 // Don't try to simplify this intrinsic if we don't have AVX2.
18938 if (!Subtarget->hasAVX2())
18941 case Intrinsic::x86_avx_blend_pd_256:
18942 case Intrinsic::x86_avx_blend_ps_256:
18943 case Intrinsic::x86_avx_blendv_pd_256:
18944 case Intrinsic::x86_avx_blendv_ps_256:
18945 // Don't try to simplify this intrinsic if we don't have AVX.
18946 if (!Subtarget->hasAVX())
18949 case Intrinsic::x86_sse41_pblendw:
18950 case Intrinsic::x86_sse41_blendpd:
18951 case Intrinsic::x86_sse41_blendps:
18952 case Intrinsic::x86_sse41_blendvps:
18953 case Intrinsic::x86_sse41_blendvpd:
18954 case Intrinsic::x86_sse41_pblendvb: {
18955 SDValue Op0 = N->getOperand(1);
18956 SDValue Op1 = N->getOperand(2);
18957 SDValue Mask = N->getOperand(3);
18959 // Don't try to simplify this intrinsic if we don't have SSE4.1.
18960 if (!Subtarget->hasSSE41())
18963 // fold (blend A, A, Mask) -> A
18966 // fold (blend A, B, allZeros) -> A
18967 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18969 // fold (blend A, B, allOnes) -> B
18970 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18973 // Simplify the case where the mask is a constant i32 value.
18974 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18975 if (C->isNullValue())
18977 if (C->isAllOnesValue())
18982 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18983 case Intrinsic::x86_sse2_psrai_w:
18984 case Intrinsic::x86_sse2_psrai_d:
18985 case Intrinsic::x86_avx2_psrai_w:
18986 case Intrinsic::x86_avx2_psrai_d:
18987 case Intrinsic::x86_sse2_psra_w:
18988 case Intrinsic::x86_sse2_psra_d:
18989 case Intrinsic::x86_avx2_psra_w:
18990 case Intrinsic::x86_avx2_psra_d: {
18991 SDValue Op0 = N->getOperand(1);
18992 SDValue Op1 = N->getOperand(2);
18993 EVT VT = Op0.getValueType();
18994 assert(VT.isVector() && "Expected a vector type!");
18996 if (isa<BuildVectorSDNode>(Op1))
18997 Op1 = Op1.getOperand(0);
18999 if (!isa<ConstantSDNode>(Op1))
19002 EVT SVT = VT.getVectorElementType();
19003 unsigned SVTBits = SVT.getSizeInBits();
19005 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19006 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19007 uint64_t ShAmt = C.getZExtValue();
19009 // Don't try to convert this shift into a ISD::SRA if the shift
19010 // count is bigger than or equal to the element size.
19011 if (ShAmt >= SVTBits)
19014 // Trivial case: if the shift count is zero, then fold this
19015 // into the first operand.
19019 // Replace this packed shift intrinsic with a target independent
19021 SDValue Splat = DAG.getConstant(C, VT);
19022 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19027 /// PerformMulCombine - Optimize a single multiply with constant into two
19028 /// in order to implement it with two cheaper instructions, e.g.
19029 /// LEA + SHL, LEA + LEA.
19030 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19031 TargetLowering::DAGCombinerInfo &DCI) {
19032 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19035 EVT VT = N->getValueType(0);
19036 if (VT != MVT::i64)
19039 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19042 uint64_t MulAmt = C->getZExtValue();
19043 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19046 uint64_t MulAmt1 = 0;
19047 uint64_t MulAmt2 = 0;
19048 if ((MulAmt % 9) == 0) {
19050 MulAmt2 = MulAmt / 9;
19051 } else if ((MulAmt % 5) == 0) {
19053 MulAmt2 = MulAmt / 5;
19054 } else if ((MulAmt % 3) == 0) {
19056 MulAmt2 = MulAmt / 3;
19059 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19062 if (isPowerOf2_64(MulAmt2) &&
19063 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19064 // If second multiplifer is pow2, issue it first. We want the multiply by
19065 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19067 std::swap(MulAmt1, MulAmt2);
19070 if (isPowerOf2_64(MulAmt1))
19071 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19072 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19074 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19075 DAG.getConstant(MulAmt1, VT));
19077 if (isPowerOf2_64(MulAmt2))
19078 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19079 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19081 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19082 DAG.getConstant(MulAmt2, VT));
19084 // Do not add new nodes to DAG combiner worklist.
19085 DCI.CombineTo(N, NewMul, false);
19090 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19091 SDValue N0 = N->getOperand(0);
19092 SDValue N1 = N->getOperand(1);
19093 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19094 EVT VT = N0.getValueType();
19096 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19097 // since the result of setcc_c is all zero's or all ones.
19098 if (VT.isInteger() && !VT.isVector() &&
19099 N1C && N0.getOpcode() == ISD::AND &&
19100 N0.getOperand(1).getOpcode() == ISD::Constant) {
19101 SDValue N00 = N0.getOperand(0);
19102 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19103 ((N00.getOpcode() == ISD::ANY_EXTEND ||
19104 N00.getOpcode() == ISD::ZERO_EXTEND) &&
19105 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19106 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19107 APInt ShAmt = N1C->getAPIntValue();
19108 Mask = Mask.shl(ShAmt);
19110 return DAG.getNode(ISD::AND, SDLoc(N), VT,
19111 N00, DAG.getConstant(Mask, VT));
19115 // Hardware support for vector shifts is sparse which makes us scalarize the
19116 // vector operations in many cases. Also, on sandybridge ADD is faster than
19118 // (shl V, 1) -> add V,V
19119 if (isSplatVector(N1.getNode())) {
19120 assert(N0.getValueType().isVector() && "Invalid vector shift type");
19121 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19122 // We shift all of the values by one. In many cases we do not have
19123 // hardware support for this operation. This is better expressed as an ADD
19125 if (N1C && (1 == N1C->getZExtValue())) {
19126 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19133 /// \brief Returns a vector of 0s if the node in input is a vector logical
19134 /// shift by a constant amount which is known to be bigger than or equal
19135 /// to the vector element size in bits.
19136 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19137 const X86Subtarget *Subtarget) {
19138 EVT VT = N->getValueType(0);
19140 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19141 (!Subtarget->hasInt256() ||
19142 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19145 SDValue Amt = N->getOperand(1);
19147 if (isSplatVector(Amt.getNode())) {
19148 SDValue SclrAmt = Amt->getOperand(0);
19149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19150 APInt ShiftAmt = C->getAPIntValue();
19151 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19153 // SSE2/AVX2 logical shifts always return a vector of 0s
19154 // if the shift amount is bigger than or equal to
19155 // the element size. The constant shift amount will be
19156 // encoded as a 8-bit immediate.
19157 if (ShiftAmt.trunc(8).uge(MaxAmount))
19158 return getZeroVector(VT, Subtarget, DAG, DL);
19165 /// PerformShiftCombine - Combine shifts.
19166 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19167 TargetLowering::DAGCombinerInfo &DCI,
19168 const X86Subtarget *Subtarget) {
19169 if (N->getOpcode() == ISD::SHL) {
19170 SDValue V = PerformSHLCombine(N, DAG);
19171 if (V.getNode()) return V;
19174 if (N->getOpcode() != ISD::SRA) {
19175 // Try to fold this logical shift into a zero vector.
19176 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19177 if (V.getNode()) return V;
19183 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19184 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19185 // and friends. Likewise for OR -> CMPNEQSS.
19186 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19187 TargetLowering::DAGCombinerInfo &DCI,
19188 const X86Subtarget *Subtarget) {
19191 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19192 // we're requiring SSE2 for both.
19193 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19194 SDValue N0 = N->getOperand(0);
19195 SDValue N1 = N->getOperand(1);
19196 SDValue CMP0 = N0->getOperand(1);
19197 SDValue CMP1 = N1->getOperand(1);
19200 // The SETCCs should both refer to the same CMP.
19201 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19204 SDValue CMP00 = CMP0->getOperand(0);
19205 SDValue CMP01 = CMP0->getOperand(1);
19206 EVT VT = CMP00.getValueType();
19208 if (VT == MVT::f32 || VT == MVT::f64) {
19209 bool ExpectingFlags = false;
19210 // Check for any users that want flags:
19211 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19212 !ExpectingFlags && UI != UE; ++UI)
19213 switch (UI->getOpcode()) {
19218 ExpectingFlags = true;
19220 case ISD::CopyToReg:
19221 case ISD::SIGN_EXTEND:
19222 case ISD::ZERO_EXTEND:
19223 case ISD::ANY_EXTEND:
19227 if (!ExpectingFlags) {
19228 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19229 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19231 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19232 X86::CondCode tmp = cc0;
19237 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19238 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19239 // FIXME: need symbolic constants for these magic numbers.
19240 // See X86ATTInstPrinter.cpp:printSSECC().
19241 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19242 if (Subtarget->hasAVX512()) {
19243 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19244 CMP01, DAG.getConstant(x86cc, MVT::i8));
19245 if (N->getValueType(0) != MVT::i1)
19246 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19250 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19251 CMP00.getValueType(), CMP00, CMP01,
19252 DAG.getConstant(x86cc, MVT::i8));
19254 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19255 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19257 if (is64BitFP && !Subtarget->is64Bit()) {
19258 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19259 // 64-bit integer, since that's not a legal type. Since
19260 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19261 // bits, but can do this little dance to extract the lowest 32 bits
19262 // and work with those going forward.
19263 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19265 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19267 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19268 Vector32, DAG.getIntPtrConstant(0));
19272 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19273 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19274 DAG.getConstant(1, IntVT));
19275 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19276 return OneBitOfTruth;
19284 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19285 /// so it can be folded inside ANDNP.
19286 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19287 EVT VT = N->getValueType(0);
19289 // Match direct AllOnes for 128 and 256-bit vectors
19290 if (ISD::isBuildVectorAllOnes(N))
19293 // Look through a bit convert.
19294 if (N->getOpcode() == ISD::BITCAST)
19295 N = N->getOperand(0).getNode();
19297 // Sometimes the operand may come from a insert_subvector building a 256-bit
19299 if (VT.is256BitVector() &&
19300 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19301 SDValue V1 = N->getOperand(0);
19302 SDValue V2 = N->getOperand(1);
19304 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19305 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19306 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19307 ISD::isBuildVectorAllOnes(V2.getNode()))
19314 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19315 // register. In most cases we actually compare or select YMM-sized registers
19316 // and mixing the two types creates horrible code. This method optimizes
19317 // some of the transition sequences.
19318 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19319 TargetLowering::DAGCombinerInfo &DCI,
19320 const X86Subtarget *Subtarget) {
19321 EVT VT = N->getValueType(0);
19322 if (!VT.is256BitVector())
19325 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19326 N->getOpcode() == ISD::ZERO_EXTEND ||
19327 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19329 SDValue Narrow = N->getOperand(0);
19330 EVT NarrowVT = Narrow->getValueType(0);
19331 if (!NarrowVT.is128BitVector())
19334 if (Narrow->getOpcode() != ISD::XOR &&
19335 Narrow->getOpcode() != ISD::AND &&
19336 Narrow->getOpcode() != ISD::OR)
19339 SDValue N0 = Narrow->getOperand(0);
19340 SDValue N1 = Narrow->getOperand(1);
19343 // The Left side has to be a trunc.
19344 if (N0.getOpcode() != ISD::TRUNCATE)
19347 // The type of the truncated inputs.
19348 EVT WideVT = N0->getOperand(0)->getValueType(0);
19352 // The right side has to be a 'trunc' or a constant vector.
19353 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19354 bool RHSConst = (isSplatVector(N1.getNode()) &&
19355 isa<ConstantSDNode>(N1->getOperand(0)));
19356 if (!RHSTrunc && !RHSConst)
19359 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19361 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19364 // Set N0 and N1 to hold the inputs to the new wide operation.
19365 N0 = N0->getOperand(0);
19367 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19368 N1->getOperand(0));
19369 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19370 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19371 } else if (RHSTrunc) {
19372 N1 = N1->getOperand(0);
19375 // Generate the wide operation.
19376 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19377 unsigned Opcode = N->getOpcode();
19379 case ISD::ANY_EXTEND:
19381 case ISD::ZERO_EXTEND: {
19382 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19383 APInt Mask = APInt::getAllOnesValue(InBits);
19384 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19385 return DAG.getNode(ISD::AND, DL, VT,
19386 Op, DAG.getConstant(Mask, VT));
19388 case ISD::SIGN_EXTEND:
19389 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19390 Op, DAG.getValueType(NarrowVT));
19392 llvm_unreachable("Unexpected opcode");
19396 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19397 TargetLowering::DAGCombinerInfo &DCI,
19398 const X86Subtarget *Subtarget) {
19399 EVT VT = N->getValueType(0);
19400 if (DCI.isBeforeLegalizeOps())
19403 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19407 // Create BEXTR instructions
19408 // BEXTR is ((X >> imm) & (2**size-1))
19409 if (VT == MVT::i32 || VT == MVT::i64) {
19410 SDValue N0 = N->getOperand(0);
19411 SDValue N1 = N->getOperand(1);
19414 // Check for BEXTR.
19415 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19416 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19417 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19418 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19419 if (MaskNode && ShiftNode) {
19420 uint64_t Mask = MaskNode->getZExtValue();
19421 uint64_t Shift = ShiftNode->getZExtValue();
19422 if (isMask_64(Mask)) {
19423 uint64_t MaskSize = CountPopulation_64(Mask);
19424 if (Shift + MaskSize <= VT.getSizeInBits())
19425 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19426 DAG.getConstant(Shift | (MaskSize << 8), VT));
19434 // Want to form ANDNP nodes:
19435 // 1) In the hopes of then easily combining them with OR and AND nodes
19436 // to form PBLEND/PSIGN.
19437 // 2) To match ANDN packed intrinsics
19438 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19441 SDValue N0 = N->getOperand(0);
19442 SDValue N1 = N->getOperand(1);
19445 // Check LHS for vnot
19446 if (N0.getOpcode() == ISD::XOR &&
19447 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19448 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19449 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19451 // Check RHS for vnot
19452 if (N1.getOpcode() == ISD::XOR &&
19453 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19454 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19455 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19460 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19461 TargetLowering::DAGCombinerInfo &DCI,
19462 const X86Subtarget *Subtarget) {
19463 if (DCI.isBeforeLegalizeOps())
19466 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19470 SDValue N0 = N->getOperand(0);
19471 SDValue N1 = N->getOperand(1);
19472 EVT VT = N->getValueType(0);
19474 // look for psign/blend
19475 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19476 if (!Subtarget->hasSSSE3() ||
19477 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19480 // Canonicalize pandn to RHS
19481 if (N0.getOpcode() == X86ISD::ANDNP)
19483 // or (and (m, y), (pandn m, x))
19484 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19485 SDValue Mask = N1.getOperand(0);
19486 SDValue X = N1.getOperand(1);
19488 if (N0.getOperand(0) == Mask)
19489 Y = N0.getOperand(1);
19490 if (N0.getOperand(1) == Mask)
19491 Y = N0.getOperand(0);
19493 // Check to see if the mask appeared in both the AND and ANDNP and
19497 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19498 // Look through mask bitcast.
19499 if (Mask.getOpcode() == ISD::BITCAST)
19500 Mask = Mask.getOperand(0);
19501 if (X.getOpcode() == ISD::BITCAST)
19502 X = X.getOperand(0);
19503 if (Y.getOpcode() == ISD::BITCAST)
19504 Y = Y.getOperand(0);
19506 EVT MaskVT = Mask.getValueType();
19508 // Validate that the Mask operand is a vector sra node.
19509 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19510 // there is no psrai.b
19511 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19512 unsigned SraAmt = ~0;
19513 if (Mask.getOpcode() == ISD::SRA) {
19514 SDValue Amt = Mask.getOperand(1);
19515 if (isSplatVector(Amt.getNode())) {
19516 SDValue SclrAmt = Amt->getOperand(0);
19517 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19518 SraAmt = C->getZExtValue();
19520 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19521 SDValue SraC = Mask.getOperand(1);
19522 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19524 if ((SraAmt + 1) != EltBits)
19529 // Now we know we at least have a plendvb with the mask val. See if
19530 // we can form a psignb/w/d.
19531 // psign = x.type == y.type == mask.type && y = sub(0, x);
19532 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19533 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19534 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19535 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19536 "Unsupported VT for PSIGN");
19537 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19538 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19540 // PBLENDVB only available on SSE 4.1
19541 if (!Subtarget->hasSSE41())
19544 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19546 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19547 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19548 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19549 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19550 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19554 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19557 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19558 MachineFunction &MF = DAG.getMachineFunction();
19559 bool OptForSize = MF.getFunction()->getAttributes().
19560 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19562 // SHLD/SHRD instructions have lower register pressure, but on some
19563 // platforms they have higher latency than the equivalent
19564 // series of shifts/or that would otherwise be generated.
19565 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19566 // have higher latencies and we are not optimizing for size.
19567 if (!OptForSize && Subtarget->isSHLDSlow())
19570 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19572 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19574 if (!N0.hasOneUse() || !N1.hasOneUse())
19577 SDValue ShAmt0 = N0.getOperand(1);
19578 if (ShAmt0.getValueType() != MVT::i8)
19580 SDValue ShAmt1 = N1.getOperand(1);
19581 if (ShAmt1.getValueType() != MVT::i8)
19583 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19584 ShAmt0 = ShAmt0.getOperand(0);
19585 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19586 ShAmt1 = ShAmt1.getOperand(0);
19589 unsigned Opc = X86ISD::SHLD;
19590 SDValue Op0 = N0.getOperand(0);
19591 SDValue Op1 = N1.getOperand(0);
19592 if (ShAmt0.getOpcode() == ISD::SUB) {
19593 Opc = X86ISD::SHRD;
19594 std::swap(Op0, Op1);
19595 std::swap(ShAmt0, ShAmt1);
19598 unsigned Bits = VT.getSizeInBits();
19599 if (ShAmt1.getOpcode() == ISD::SUB) {
19600 SDValue Sum = ShAmt1.getOperand(0);
19601 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19602 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19603 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19604 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19605 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19606 return DAG.getNode(Opc, DL, VT,
19608 DAG.getNode(ISD::TRUNCATE, DL,
19611 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19612 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19614 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19615 return DAG.getNode(Opc, DL, VT,
19616 N0.getOperand(0), N1.getOperand(0),
19617 DAG.getNode(ISD::TRUNCATE, DL,
19624 // Generate NEG and CMOV for integer abs.
19625 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19626 EVT VT = N->getValueType(0);
19628 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19629 // 8-bit integer abs to NEG and CMOV.
19630 if (VT.isInteger() && VT.getSizeInBits() == 8)
19633 SDValue N0 = N->getOperand(0);
19634 SDValue N1 = N->getOperand(1);
19637 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19638 // and change it to SUB and CMOV.
19639 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19640 N0.getOpcode() == ISD::ADD &&
19641 N0.getOperand(1) == N1 &&
19642 N1.getOpcode() == ISD::SRA &&
19643 N1.getOperand(0) == N0.getOperand(0))
19644 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19645 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19646 // Generate SUB & CMOV.
19647 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19648 DAG.getConstant(0, VT), N0.getOperand(0));
19650 SDValue Ops[] = { N0.getOperand(0), Neg,
19651 DAG.getConstant(X86::COND_GE, MVT::i8),
19652 SDValue(Neg.getNode(), 1) };
19653 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19658 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19659 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19660 TargetLowering::DAGCombinerInfo &DCI,
19661 const X86Subtarget *Subtarget) {
19662 if (DCI.isBeforeLegalizeOps())
19665 if (Subtarget->hasCMov()) {
19666 SDValue RV = performIntegerAbsCombine(N, DAG);
19674 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19675 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19676 TargetLowering::DAGCombinerInfo &DCI,
19677 const X86Subtarget *Subtarget) {
19678 LoadSDNode *Ld = cast<LoadSDNode>(N);
19679 EVT RegVT = Ld->getValueType(0);
19680 EVT MemVT = Ld->getMemoryVT();
19682 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19683 unsigned RegSz = RegVT.getSizeInBits();
19685 // On Sandybridge unaligned 256bit loads are inefficient.
19686 ISD::LoadExtType Ext = Ld->getExtensionType();
19687 unsigned Alignment = Ld->getAlignment();
19688 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19689 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19690 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19691 unsigned NumElems = RegVT.getVectorNumElements();
19695 SDValue Ptr = Ld->getBasePtr();
19696 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19698 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19700 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19701 Ld->getPointerInfo(), Ld->isVolatile(),
19702 Ld->isNonTemporal(), Ld->isInvariant(),
19704 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19705 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19706 Ld->getPointerInfo(), Ld->isVolatile(),
19707 Ld->isNonTemporal(), Ld->isInvariant(),
19708 std::min(16U, Alignment));
19709 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19711 Load2.getValue(1));
19713 SDValue NewVec = DAG.getUNDEF(RegVT);
19714 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19715 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19716 return DCI.CombineTo(N, NewVec, TF, true);
19719 // If this is a vector EXT Load then attempt to optimize it using a
19720 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19721 // expansion is still better than scalar code.
19722 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19723 // emit a shuffle and a arithmetic shift.
19724 // TODO: It is possible to support ZExt by zeroing the undef values
19725 // during the shuffle phase or after the shuffle.
19726 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19727 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19728 assert(MemVT != RegVT && "Cannot extend to the same type");
19729 assert(MemVT.isVector() && "Must load a vector from memory");
19731 unsigned NumElems = RegVT.getVectorNumElements();
19732 unsigned MemSz = MemVT.getSizeInBits();
19733 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19735 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19738 // All sizes must be a power of two.
19739 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19742 // Attempt to load the original value using scalar loads.
19743 // Find the largest scalar type that divides the total loaded size.
19744 MVT SclrLoadTy = MVT::i8;
19745 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19746 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19747 MVT Tp = (MVT::SimpleValueType)tp;
19748 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19753 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19754 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19756 SclrLoadTy = MVT::f64;
19758 // Calculate the number of scalar loads that we need to perform
19759 // in order to load our vector from memory.
19760 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19761 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19764 unsigned loadRegZize = RegSz;
19765 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19768 // Represent our vector as a sequence of elements which are the
19769 // largest scalar that we can load.
19770 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19771 loadRegZize/SclrLoadTy.getSizeInBits());
19773 // Represent the data using the same element type that is stored in
19774 // memory. In practice, we ''widen'' MemVT.
19776 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19777 loadRegZize/MemVT.getScalarType().getSizeInBits());
19779 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19780 "Invalid vector type");
19782 // We can't shuffle using an illegal type.
19783 if (!TLI.isTypeLegal(WideVecVT))
19786 SmallVector<SDValue, 8> Chains;
19787 SDValue Ptr = Ld->getBasePtr();
19788 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19789 TLI.getPointerTy());
19790 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19792 for (unsigned i = 0; i < NumLoads; ++i) {
19793 // Perform a single load.
19794 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19795 Ptr, Ld->getPointerInfo(),
19796 Ld->isVolatile(), Ld->isNonTemporal(),
19797 Ld->isInvariant(), Ld->getAlignment());
19798 Chains.push_back(ScalarLoad.getValue(1));
19799 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19800 // another round of DAGCombining.
19802 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19804 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19805 ScalarLoad, DAG.getIntPtrConstant(i));
19807 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19810 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19812 // Bitcast the loaded value to a vector of the original element type, in
19813 // the size of the target vector type.
19814 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19815 unsigned SizeRatio = RegSz/MemSz;
19817 if (Ext == ISD::SEXTLOAD) {
19818 // If we have SSE4.1 we can directly emit a VSEXT node.
19819 if (Subtarget->hasSSE41()) {
19820 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19821 return DCI.CombineTo(N, Sext, TF, true);
19824 // Otherwise we'll shuffle the small elements in the high bits of the
19825 // larger type and perform an arithmetic shift. If the shift is not legal
19826 // it's better to scalarize.
19827 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19830 // Redistribute the loaded elements into the different locations.
19831 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19832 for (unsigned i = 0; i != NumElems; ++i)
19833 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19835 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19836 DAG.getUNDEF(WideVecVT),
19839 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19841 // Build the arithmetic shift.
19842 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19843 MemVT.getVectorElementType().getSizeInBits();
19844 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19845 DAG.getConstant(Amt, RegVT));
19847 return DCI.CombineTo(N, Shuff, TF, true);
19850 // Redistribute the loaded elements into the different locations.
19851 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19852 for (unsigned i = 0; i != NumElems; ++i)
19853 ShuffleVec[i*SizeRatio] = i;
19855 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19856 DAG.getUNDEF(WideVecVT),
19859 // Bitcast to the requested type.
19860 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19861 // Replace the original load with the new sequence
19862 // and return the new chain.
19863 return DCI.CombineTo(N, Shuff, TF, true);
19869 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19870 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19871 const X86Subtarget *Subtarget) {
19872 StoreSDNode *St = cast<StoreSDNode>(N);
19873 EVT VT = St->getValue().getValueType();
19874 EVT StVT = St->getMemoryVT();
19876 SDValue StoredVal = St->getOperand(1);
19877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19879 // If we are saving a concatenation of two XMM registers, perform two stores.
19880 // On Sandy Bridge, 256-bit memory operations are executed by two
19881 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19882 // memory operation.
19883 unsigned Alignment = St->getAlignment();
19884 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19885 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19886 StVT == VT && !IsAligned) {
19887 unsigned NumElems = VT.getVectorNumElements();
19891 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19892 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19894 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19895 SDValue Ptr0 = St->getBasePtr();
19896 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19898 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19899 St->getPointerInfo(), St->isVolatile(),
19900 St->isNonTemporal(), Alignment);
19901 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19902 St->getPointerInfo(), St->isVolatile(),
19903 St->isNonTemporal(),
19904 std::min(16U, Alignment));
19905 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19908 // Optimize trunc store (of multiple scalars) to shuffle and store.
19909 // First, pack all of the elements in one place. Next, store to memory
19910 // in fewer chunks.
19911 if (St->isTruncatingStore() && VT.isVector()) {
19912 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19913 unsigned NumElems = VT.getVectorNumElements();
19914 assert(StVT != VT && "Cannot truncate to the same type");
19915 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19916 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19918 // From, To sizes and ElemCount must be pow of two
19919 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19920 // We are going to use the original vector elt for storing.
19921 // Accumulated smaller vector elements must be a multiple of the store size.
19922 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19924 unsigned SizeRatio = FromSz / ToSz;
19926 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19928 // Create a type on which we perform the shuffle
19929 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19930 StVT.getScalarType(), NumElems*SizeRatio);
19932 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19934 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19935 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19936 for (unsigned i = 0; i != NumElems; ++i)
19937 ShuffleVec[i] = i * SizeRatio;
19939 // Can't shuffle using an illegal type.
19940 if (!TLI.isTypeLegal(WideVecVT))
19943 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19944 DAG.getUNDEF(WideVecVT),
19946 // At this point all of the data is stored at the bottom of the
19947 // register. We now need to save it to mem.
19949 // Find the largest store unit
19950 MVT StoreType = MVT::i8;
19951 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19952 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19953 MVT Tp = (MVT::SimpleValueType)tp;
19954 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19958 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19959 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19960 (64 <= NumElems * ToSz))
19961 StoreType = MVT::f64;
19963 // Bitcast the original vector into a vector of store-size units
19964 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19965 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19966 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19967 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19968 SmallVector<SDValue, 8> Chains;
19969 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19970 TLI.getPointerTy());
19971 SDValue Ptr = St->getBasePtr();
19973 // Perform one or more big stores into memory.
19974 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19975 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19976 StoreType, ShuffWide,
19977 DAG.getIntPtrConstant(i));
19978 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19979 St->getPointerInfo(), St->isVolatile(),
19980 St->isNonTemporal(), St->getAlignment());
19981 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19982 Chains.push_back(Ch);
19985 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19988 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19989 // the FP state in cases where an emms may be missing.
19990 // A preferable solution to the general problem is to figure out the right
19991 // places to insert EMMS. This qualifies as a quick hack.
19993 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19994 if (VT.getSizeInBits() != 64)
19997 const Function *F = DAG.getMachineFunction().getFunction();
19998 bool NoImplicitFloatOps = F->getAttributes().
19999 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20000 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20001 && Subtarget->hasSSE2();
20002 if ((VT.isVector() ||
20003 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20004 isa<LoadSDNode>(St->getValue()) &&
20005 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20006 St->getChain().hasOneUse() && !St->isVolatile()) {
20007 SDNode* LdVal = St->getValue().getNode();
20008 LoadSDNode *Ld = nullptr;
20009 int TokenFactorIndex = -1;
20010 SmallVector<SDValue, 8> Ops;
20011 SDNode* ChainVal = St->getChain().getNode();
20012 // Must be a store of a load. We currently handle two cases: the load
20013 // is a direct child, and it's under an intervening TokenFactor. It is
20014 // possible to dig deeper under nested TokenFactors.
20015 if (ChainVal == LdVal)
20016 Ld = cast<LoadSDNode>(St->getChain());
20017 else if (St->getValue().hasOneUse() &&
20018 ChainVal->getOpcode() == ISD::TokenFactor) {
20019 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20020 if (ChainVal->getOperand(i).getNode() == LdVal) {
20021 TokenFactorIndex = i;
20022 Ld = cast<LoadSDNode>(St->getValue());
20024 Ops.push_back(ChainVal->getOperand(i));
20028 if (!Ld || !ISD::isNormalLoad(Ld))
20031 // If this is not the MMX case, i.e. we are just turning i64 load/store
20032 // into f64 load/store, avoid the transformation if there are multiple
20033 // uses of the loaded value.
20034 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20039 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20040 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20042 if (Subtarget->is64Bit() || F64IsLegal) {
20043 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20044 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20045 Ld->getPointerInfo(), Ld->isVolatile(),
20046 Ld->isNonTemporal(), Ld->isInvariant(),
20047 Ld->getAlignment());
20048 SDValue NewChain = NewLd.getValue(1);
20049 if (TokenFactorIndex != -1) {
20050 Ops.push_back(NewChain);
20051 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20053 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20054 St->getPointerInfo(),
20055 St->isVolatile(), St->isNonTemporal(),
20056 St->getAlignment());
20059 // Otherwise, lower to two pairs of 32-bit loads / stores.
20060 SDValue LoAddr = Ld->getBasePtr();
20061 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20062 DAG.getConstant(4, MVT::i32));
20064 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20065 Ld->getPointerInfo(),
20066 Ld->isVolatile(), Ld->isNonTemporal(),
20067 Ld->isInvariant(), Ld->getAlignment());
20068 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20069 Ld->getPointerInfo().getWithOffset(4),
20070 Ld->isVolatile(), Ld->isNonTemporal(),
20072 MinAlign(Ld->getAlignment(), 4));
20074 SDValue NewChain = LoLd.getValue(1);
20075 if (TokenFactorIndex != -1) {
20076 Ops.push_back(LoLd);
20077 Ops.push_back(HiLd);
20078 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20081 LoAddr = St->getBasePtr();
20082 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20083 DAG.getConstant(4, MVT::i32));
20085 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20086 St->getPointerInfo(),
20087 St->isVolatile(), St->isNonTemporal(),
20088 St->getAlignment());
20089 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20090 St->getPointerInfo().getWithOffset(4),
20092 St->isNonTemporal(),
20093 MinAlign(St->getAlignment(), 4));
20094 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20099 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20100 /// and return the operands for the horizontal operation in LHS and RHS. A
20101 /// horizontal operation performs the binary operation on successive elements
20102 /// of its first operand, then on successive elements of its second operand,
20103 /// returning the resulting values in a vector. For example, if
20104 /// A = < float a0, float a1, float a2, float a3 >
20106 /// B = < float b0, float b1, float b2, float b3 >
20107 /// then the result of doing a horizontal operation on A and B is
20108 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20109 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20110 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20111 /// set to A, RHS to B, and the routine returns 'true'.
20112 /// Note that the binary operation should have the property that if one of the
20113 /// operands is UNDEF then the result is UNDEF.
20114 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20115 // Look for the following pattern: if
20116 // A = < float a0, float a1, float a2, float a3 >
20117 // B = < float b0, float b1, float b2, float b3 >
20119 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20120 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20121 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20122 // which is A horizontal-op B.
20124 // At least one of the operands should be a vector shuffle.
20125 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20126 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20129 MVT VT = LHS.getSimpleValueType();
20131 assert((VT.is128BitVector() || VT.is256BitVector()) &&
20132 "Unsupported vector type for horizontal add/sub");
20134 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20135 // operate independently on 128-bit lanes.
20136 unsigned NumElts = VT.getVectorNumElements();
20137 unsigned NumLanes = VT.getSizeInBits()/128;
20138 unsigned NumLaneElts = NumElts / NumLanes;
20139 assert((NumLaneElts % 2 == 0) &&
20140 "Vector type should have an even number of elements in each lane");
20141 unsigned HalfLaneElts = NumLaneElts/2;
20143 // View LHS in the form
20144 // LHS = VECTOR_SHUFFLE A, B, LMask
20145 // If LHS is not a shuffle then pretend it is the shuffle
20146 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20147 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20150 SmallVector<int, 16> LMask(NumElts);
20151 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20152 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20153 A = LHS.getOperand(0);
20154 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20155 B = LHS.getOperand(1);
20156 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20157 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20159 if (LHS.getOpcode() != ISD::UNDEF)
20161 for (unsigned i = 0; i != NumElts; ++i)
20165 // Likewise, view RHS in the form
20166 // RHS = VECTOR_SHUFFLE C, D, RMask
20168 SmallVector<int, 16> RMask(NumElts);
20169 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20170 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20171 C = RHS.getOperand(0);
20172 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20173 D = RHS.getOperand(1);
20174 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20175 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20177 if (RHS.getOpcode() != ISD::UNDEF)
20179 for (unsigned i = 0; i != NumElts; ++i)
20183 // Check that the shuffles are both shuffling the same vectors.
20184 if (!(A == C && B == D) && !(A == D && B == C))
20187 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20188 if (!A.getNode() && !B.getNode())
20191 // If A and B occur in reverse order in RHS, then "swap" them (which means
20192 // rewriting the mask).
20194 CommuteVectorShuffleMask(RMask, NumElts);
20196 // At this point LHS and RHS are equivalent to
20197 // LHS = VECTOR_SHUFFLE A, B, LMask
20198 // RHS = VECTOR_SHUFFLE A, B, RMask
20199 // Check that the masks correspond to performing a horizontal operation.
20200 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20201 for (unsigned i = 0; i != NumLaneElts; ++i) {
20202 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20204 // Ignore any UNDEF components.
20205 if (LIdx < 0 || RIdx < 0 ||
20206 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20207 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20210 // Check that successive elements are being operated on. If not, this is
20211 // not a horizontal operation.
20212 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20213 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20214 if (!(LIdx == Index && RIdx == Index + 1) &&
20215 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20220 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20221 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20225 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20226 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20227 const X86Subtarget *Subtarget) {
20228 EVT VT = N->getValueType(0);
20229 SDValue LHS = N->getOperand(0);
20230 SDValue RHS = N->getOperand(1);
20232 // Try to synthesize horizontal adds from adds of shuffles.
20233 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20234 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20235 isHorizontalBinOp(LHS, RHS, true))
20236 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20240 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20241 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20242 const X86Subtarget *Subtarget) {
20243 EVT VT = N->getValueType(0);
20244 SDValue LHS = N->getOperand(0);
20245 SDValue RHS = N->getOperand(1);
20247 // Try to synthesize horizontal subs from subs of shuffles.
20248 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20249 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20250 isHorizontalBinOp(LHS, RHS, false))
20251 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20255 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20256 /// X86ISD::FXOR nodes.
20257 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20258 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20259 // F[X]OR(0.0, x) -> x
20260 // F[X]OR(x, 0.0) -> x
20261 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20262 if (C->getValueAPF().isPosZero())
20263 return N->getOperand(1);
20264 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20265 if (C->getValueAPF().isPosZero())
20266 return N->getOperand(0);
20270 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20271 /// X86ISD::FMAX nodes.
20272 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20273 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20275 // Only perform optimizations if UnsafeMath is used.
20276 if (!DAG.getTarget().Options.UnsafeFPMath)
20279 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20280 // into FMINC and FMAXC, which are Commutative operations.
20281 unsigned NewOp = 0;
20282 switch (N->getOpcode()) {
20283 default: llvm_unreachable("unknown opcode");
20284 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20285 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20288 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20289 N->getOperand(0), N->getOperand(1));
20292 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20293 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20294 // FAND(0.0, x) -> 0.0
20295 // FAND(x, 0.0) -> 0.0
20296 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20297 if (C->getValueAPF().isPosZero())
20298 return N->getOperand(0);
20299 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20300 if (C->getValueAPF().isPosZero())
20301 return N->getOperand(1);
20305 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20306 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20307 // FANDN(x, 0.0) -> 0.0
20308 // FANDN(0.0, x) -> x
20309 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20310 if (C->getValueAPF().isPosZero())
20311 return N->getOperand(1);
20312 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20313 if (C->getValueAPF().isPosZero())
20314 return N->getOperand(1);
20318 static SDValue PerformBTCombine(SDNode *N,
20320 TargetLowering::DAGCombinerInfo &DCI) {
20321 // BT ignores high bits in the bit index operand.
20322 SDValue Op1 = N->getOperand(1);
20323 if (Op1.hasOneUse()) {
20324 unsigned BitWidth = Op1.getValueSizeInBits();
20325 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20326 APInt KnownZero, KnownOne;
20327 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20328 !DCI.isBeforeLegalizeOps());
20329 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20330 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20331 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20332 DCI.CommitTargetLoweringOpt(TLO);
20337 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20338 SDValue Op = N->getOperand(0);
20339 if (Op.getOpcode() == ISD::BITCAST)
20340 Op = Op.getOperand(0);
20341 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20342 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20343 VT.getVectorElementType().getSizeInBits() ==
20344 OpVT.getVectorElementType().getSizeInBits()) {
20345 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20350 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20351 const X86Subtarget *Subtarget) {
20352 EVT VT = N->getValueType(0);
20353 if (!VT.isVector())
20356 SDValue N0 = N->getOperand(0);
20357 SDValue N1 = N->getOperand(1);
20358 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20361 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20362 // both SSE and AVX2 since there is no sign-extended shift right
20363 // operation on a vector with 64-bit elements.
20364 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20365 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20366 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20367 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20368 SDValue N00 = N0.getOperand(0);
20370 // EXTLOAD has a better solution on AVX2,
20371 // it may be replaced with X86ISD::VSEXT node.
20372 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20373 if (!ISD::isNormalLoad(N00.getNode()))
20376 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20377 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20379 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20385 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20386 TargetLowering::DAGCombinerInfo &DCI,
20387 const X86Subtarget *Subtarget) {
20388 if (!DCI.isBeforeLegalizeOps())
20391 if (!Subtarget->hasFp256())
20394 EVT VT = N->getValueType(0);
20395 if (VT.isVector() && VT.getSizeInBits() == 256) {
20396 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20404 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20405 const X86Subtarget* Subtarget) {
20407 EVT VT = N->getValueType(0);
20409 // Let legalize expand this if it isn't a legal type yet.
20410 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20413 EVT ScalarVT = VT.getScalarType();
20414 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20415 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20418 SDValue A = N->getOperand(0);
20419 SDValue B = N->getOperand(1);
20420 SDValue C = N->getOperand(2);
20422 bool NegA = (A.getOpcode() == ISD::FNEG);
20423 bool NegB = (B.getOpcode() == ISD::FNEG);
20424 bool NegC = (C.getOpcode() == ISD::FNEG);
20426 // Negative multiplication when NegA xor NegB
20427 bool NegMul = (NegA != NegB);
20429 A = A.getOperand(0);
20431 B = B.getOperand(0);
20433 C = C.getOperand(0);
20437 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20439 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20441 return DAG.getNode(Opcode, dl, VT, A, B, C);
20444 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20445 TargetLowering::DAGCombinerInfo &DCI,
20446 const X86Subtarget *Subtarget) {
20447 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20448 // (and (i32 x86isd::setcc_carry), 1)
20449 // This eliminates the zext. This transformation is necessary because
20450 // ISD::SETCC is always legalized to i8.
20452 SDValue N0 = N->getOperand(0);
20453 EVT VT = N->getValueType(0);
20455 if (N0.getOpcode() == ISD::AND &&
20457 N0.getOperand(0).hasOneUse()) {
20458 SDValue N00 = N0.getOperand(0);
20459 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20460 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20461 if (!C || C->getZExtValue() != 1)
20463 return DAG.getNode(ISD::AND, dl, VT,
20464 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20465 N00.getOperand(0), N00.getOperand(1)),
20466 DAG.getConstant(1, VT));
20470 if (N0.getOpcode() == ISD::TRUNCATE &&
20472 N0.getOperand(0).hasOneUse()) {
20473 SDValue N00 = N0.getOperand(0);
20474 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20475 return DAG.getNode(ISD::AND, dl, VT,
20476 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20477 N00.getOperand(0), N00.getOperand(1)),
20478 DAG.getConstant(1, VT));
20481 if (VT.is256BitVector()) {
20482 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20490 // Optimize x == -y --> x+y == 0
20491 // x != -y --> x+y != 0
20492 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20493 const X86Subtarget* Subtarget) {
20494 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20495 SDValue LHS = N->getOperand(0);
20496 SDValue RHS = N->getOperand(1);
20497 EVT VT = N->getValueType(0);
20500 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20501 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20502 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20503 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20504 LHS.getValueType(), RHS, LHS.getOperand(1));
20505 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20506 addV, DAG.getConstant(0, addV.getValueType()), CC);
20508 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20510 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20511 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20512 RHS.getValueType(), LHS, RHS.getOperand(1));
20513 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20514 addV, DAG.getConstant(0, addV.getValueType()), CC);
20517 if (VT.getScalarType() == MVT::i1) {
20518 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20519 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20520 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20521 if (!IsSEXT0 && !IsVZero0)
20523 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20524 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20525 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20527 if (!IsSEXT1 && !IsVZero1)
20530 if (IsSEXT0 && IsVZero1) {
20531 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20532 if (CC == ISD::SETEQ)
20533 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20534 return LHS.getOperand(0);
20536 if (IsSEXT1 && IsVZero0) {
20537 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20538 if (CC == ISD::SETEQ)
20539 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20540 return RHS.getOperand(0);
20547 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20548 const X86Subtarget *Subtarget) {
20550 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20551 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20552 "X86insertps is only defined for v4x32");
20554 SDValue Ld = N->getOperand(1);
20555 if (MayFoldLoad(Ld)) {
20556 // Extract the countS bits from the immediate so we can get the proper
20557 // address when narrowing the vector load to a specific element.
20558 // When the second source op is a memory address, interps doesn't use
20559 // countS and just gets an f32 from that address.
20560 unsigned DestIndex =
20561 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20562 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20566 // Create this as a scalar to vector to match the instruction pattern.
20567 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20568 // countS bits are ignored when loading from memory on insertps, which
20569 // means we don't need to explicitly set them to 0.
20570 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20571 LoadScalarToVector, N->getOperand(2));
20574 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20575 // as "sbb reg,reg", since it can be extended without zext and produces
20576 // an all-ones bit which is more useful than 0/1 in some cases.
20577 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20580 return DAG.getNode(ISD::AND, DL, VT,
20581 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20582 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20583 DAG.getConstant(1, VT));
20584 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20585 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20586 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20587 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20590 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20591 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20592 TargetLowering::DAGCombinerInfo &DCI,
20593 const X86Subtarget *Subtarget) {
20595 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20596 SDValue EFLAGS = N->getOperand(1);
20598 if (CC == X86::COND_A) {
20599 // Try to convert COND_A into COND_B in an attempt to facilitate
20600 // materializing "setb reg".
20602 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20603 // cannot take an immediate as its first operand.
20605 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20606 EFLAGS.getValueType().isInteger() &&
20607 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20608 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20609 EFLAGS.getNode()->getVTList(),
20610 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20611 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20612 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20616 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20617 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20619 if (CC == X86::COND_B)
20620 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20624 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20625 if (Flags.getNode()) {
20626 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20627 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20633 // Optimize branch condition evaluation.
20635 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20636 TargetLowering::DAGCombinerInfo &DCI,
20637 const X86Subtarget *Subtarget) {
20639 SDValue Chain = N->getOperand(0);
20640 SDValue Dest = N->getOperand(1);
20641 SDValue EFLAGS = N->getOperand(3);
20642 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20646 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20647 if (Flags.getNode()) {
20648 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20649 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20656 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20657 const X86TargetLowering *XTLI) {
20658 SDValue Op0 = N->getOperand(0);
20659 EVT InVT = Op0->getValueType(0);
20661 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20662 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20664 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20665 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20666 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20669 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20670 // a 32-bit target where SSE doesn't support i64->FP operations.
20671 if (Op0.getOpcode() == ISD::LOAD) {
20672 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20673 EVT VT = Ld->getValueType(0);
20674 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20675 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20676 !XTLI->getSubtarget()->is64Bit() &&
20678 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20679 Ld->getChain(), Op0, DAG);
20680 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20687 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20688 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20689 X86TargetLowering::DAGCombinerInfo &DCI) {
20690 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20691 // the result is either zero or one (depending on the input carry bit).
20692 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20693 if (X86::isZeroNode(N->getOperand(0)) &&
20694 X86::isZeroNode(N->getOperand(1)) &&
20695 // We don't have a good way to replace an EFLAGS use, so only do this when
20697 SDValue(N, 1).use_empty()) {
20699 EVT VT = N->getValueType(0);
20700 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20701 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20702 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20703 DAG.getConstant(X86::COND_B,MVT::i8),
20705 DAG.getConstant(1, VT));
20706 return DCI.CombineTo(N, Res1, CarryOut);
20712 // fold (add Y, (sete X, 0)) -> adc 0, Y
20713 // (add Y, (setne X, 0)) -> sbb -1, Y
20714 // (sub (sete X, 0), Y) -> sbb 0, Y
20715 // (sub (setne X, 0), Y) -> adc -1, Y
20716 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20719 // Look through ZExts.
20720 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20721 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20724 SDValue SetCC = Ext.getOperand(0);
20725 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20728 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20729 if (CC != X86::COND_E && CC != X86::COND_NE)
20732 SDValue Cmp = SetCC.getOperand(1);
20733 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20734 !X86::isZeroNode(Cmp.getOperand(1)) ||
20735 !Cmp.getOperand(0).getValueType().isInteger())
20738 SDValue CmpOp0 = Cmp.getOperand(0);
20739 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20740 DAG.getConstant(1, CmpOp0.getValueType()));
20742 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20743 if (CC == X86::COND_NE)
20744 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20745 DL, OtherVal.getValueType(), OtherVal,
20746 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20747 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20748 DL, OtherVal.getValueType(), OtherVal,
20749 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20752 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20753 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20754 const X86Subtarget *Subtarget) {
20755 EVT VT = N->getValueType(0);
20756 SDValue Op0 = N->getOperand(0);
20757 SDValue Op1 = N->getOperand(1);
20759 // Try to synthesize horizontal adds from adds of shuffles.
20760 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20761 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20762 isHorizontalBinOp(Op0, Op1, true))
20763 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20765 return OptimizeConditionalInDecrement(N, DAG);
20768 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20769 const X86Subtarget *Subtarget) {
20770 SDValue Op0 = N->getOperand(0);
20771 SDValue Op1 = N->getOperand(1);
20773 // X86 can't encode an immediate LHS of a sub. See if we can push the
20774 // negation into a preceding instruction.
20775 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20776 // If the RHS of the sub is a XOR with one use and a constant, invert the
20777 // immediate. Then add one to the LHS of the sub so we can turn
20778 // X-Y -> X+~Y+1, saving one register.
20779 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20780 isa<ConstantSDNode>(Op1.getOperand(1))) {
20781 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20782 EVT VT = Op0.getValueType();
20783 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20785 DAG.getConstant(~XorC, VT));
20786 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20787 DAG.getConstant(C->getAPIntValue()+1, VT));
20791 // Try to synthesize horizontal adds from adds of shuffles.
20792 EVT VT = N->getValueType(0);
20793 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20794 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20795 isHorizontalBinOp(Op0, Op1, true))
20796 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20798 return OptimizeConditionalInDecrement(N, DAG);
20801 /// performVZEXTCombine - Performs build vector combines
20802 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20803 TargetLowering::DAGCombinerInfo &DCI,
20804 const X86Subtarget *Subtarget) {
20805 // (vzext (bitcast (vzext (x)) -> (vzext x)
20806 SDValue In = N->getOperand(0);
20807 while (In.getOpcode() == ISD::BITCAST)
20808 In = In.getOperand(0);
20810 if (In.getOpcode() != X86ISD::VZEXT)
20813 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20817 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20818 DAGCombinerInfo &DCI) const {
20819 SelectionDAG &DAG = DCI.DAG;
20820 switch (N->getOpcode()) {
20822 case ISD::EXTRACT_VECTOR_ELT:
20823 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20825 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20826 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20827 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20828 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20829 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20830 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20833 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20834 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20835 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20836 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20837 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20838 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20839 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20840 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20841 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20843 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20845 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20846 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20847 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20848 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20849 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20850 case ISD::ANY_EXTEND:
20851 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20852 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20853 case ISD::SIGN_EXTEND_INREG:
20854 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20855 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20856 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20857 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20858 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20859 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20860 case X86ISD::SHUFP: // Handle all target specific shuffles
20861 case X86ISD::PALIGNR:
20862 case X86ISD::UNPCKH:
20863 case X86ISD::UNPCKL:
20864 case X86ISD::MOVHLPS:
20865 case X86ISD::MOVLHPS:
20866 case X86ISD::PSHUFD:
20867 case X86ISD::PSHUFHW:
20868 case X86ISD::PSHUFLW:
20869 case X86ISD::MOVSS:
20870 case X86ISD::MOVSD:
20871 case X86ISD::VPERMILP:
20872 case X86ISD::VPERM2X128:
20873 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20874 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20875 case ISD::INTRINSIC_WO_CHAIN:
20876 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20877 case X86ISD::INSERTPS:
20878 return PerformINSERTPSCombine(N, DAG, Subtarget);
20879 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
20885 /// isTypeDesirableForOp - Return true if the target has native support for
20886 /// the specified value type and it is 'desirable' to use the type for the
20887 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20888 /// instruction encodings are longer and some i16 instructions are slow.
20889 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20890 if (!isTypeLegal(VT))
20892 if (VT != MVT::i16)
20899 case ISD::SIGN_EXTEND:
20900 case ISD::ZERO_EXTEND:
20901 case ISD::ANY_EXTEND:
20914 /// IsDesirableToPromoteOp - This method query the target whether it is
20915 /// beneficial for dag combiner to promote the specified node. If true, it
20916 /// should return the desired promotion type by reference.
20917 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20918 EVT VT = Op.getValueType();
20919 if (VT != MVT::i16)
20922 bool Promote = false;
20923 bool Commute = false;
20924 switch (Op.getOpcode()) {
20927 LoadSDNode *LD = cast<LoadSDNode>(Op);
20928 // If the non-extending load has a single use and it's not live out, then it
20929 // might be folded.
20930 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20931 Op.hasOneUse()*/) {
20932 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20933 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20934 // The only case where we'd want to promote LOAD (rather then it being
20935 // promoted as an operand is when it's only use is liveout.
20936 if (UI->getOpcode() != ISD::CopyToReg)
20943 case ISD::SIGN_EXTEND:
20944 case ISD::ZERO_EXTEND:
20945 case ISD::ANY_EXTEND:
20950 SDValue N0 = Op.getOperand(0);
20951 // Look out for (store (shl (load), x)).
20952 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20965 SDValue N0 = Op.getOperand(0);
20966 SDValue N1 = Op.getOperand(1);
20967 if (!Commute && MayFoldLoad(N1))
20969 // Avoid disabling potential load folding opportunities.
20970 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20972 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20982 //===----------------------------------------------------------------------===//
20983 // X86 Inline Assembly Support
20984 //===----------------------------------------------------------------------===//
20987 // Helper to match a string separated by whitespace.
20988 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20989 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20991 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20992 StringRef piece(*args[i]);
20993 if (!s.startswith(piece)) // Check if the piece matches.
20996 s = s.substr(piece.size());
20997 StringRef::size_type pos = s.find_first_not_of(" \t");
20998 if (pos == 0) // We matched a prefix.
21006 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21009 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21011 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21012 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21013 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21014 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21016 if (AsmPieces.size() == 3)
21018 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21025 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21026 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21028 std::string AsmStr = IA->getAsmString();
21030 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21031 if (!Ty || Ty->getBitWidth() % 16 != 0)
21034 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21035 SmallVector<StringRef, 4> AsmPieces;
21036 SplitString(AsmStr, AsmPieces, ";\n");
21038 switch (AsmPieces.size()) {
21039 default: return false;
21041 // FIXME: this should verify that we are targeting a 486 or better. If not,
21042 // we will turn this bswap into something that will be lowered to logical
21043 // ops instead of emitting the bswap asm. For now, we don't support 486 or
21044 // lower so don't worry about this.
21046 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21047 matchAsm(AsmPieces[0], "bswapl", "$0") ||
21048 matchAsm(AsmPieces[0], "bswapq", "$0") ||
21049 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21050 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21051 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21052 // No need to check constraints, nothing other than the equivalent of
21053 // "=r,0" would be valid here.
21054 return IntrinsicLowering::LowerToByteSwap(CI);
21057 // rorw $$8, ${0:w} --> llvm.bswap.i16
21058 if (CI->getType()->isIntegerTy(16) &&
21059 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21060 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21061 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21063 const std::string &ConstraintsStr = IA->getConstraintString();
21064 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21065 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21066 if (clobbersFlagRegisters(AsmPieces))
21067 return IntrinsicLowering::LowerToByteSwap(CI);
21071 if (CI->getType()->isIntegerTy(32) &&
21072 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21073 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21074 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21075 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21077 const std::string &ConstraintsStr = IA->getConstraintString();
21078 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21079 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21080 if (clobbersFlagRegisters(AsmPieces))
21081 return IntrinsicLowering::LowerToByteSwap(CI);
21084 if (CI->getType()->isIntegerTy(64)) {
21085 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21086 if (Constraints.size() >= 2 &&
21087 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21088 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21089 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
21090 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21091 matchAsm(AsmPieces[1], "bswap", "%edx") &&
21092 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21093 return IntrinsicLowering::LowerToByteSwap(CI);
21101 /// getConstraintType - Given a constraint letter, return the type of
21102 /// constraint it is for this target.
21103 X86TargetLowering::ConstraintType
21104 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21105 if (Constraint.size() == 1) {
21106 switch (Constraint[0]) {
21117 return C_RegisterClass;
21141 return TargetLowering::getConstraintType(Constraint);
21144 /// Examine constraint type and operand type and determine a weight value.
21145 /// This object must already have been set up with the operand type
21146 /// and the current alternative constraint selected.
21147 TargetLowering::ConstraintWeight
21148 X86TargetLowering::getSingleConstraintMatchWeight(
21149 AsmOperandInfo &info, const char *constraint) const {
21150 ConstraintWeight weight = CW_Invalid;
21151 Value *CallOperandVal = info.CallOperandVal;
21152 // If we don't have a value, we can't do a match,
21153 // but allow it at the lowest weight.
21154 if (!CallOperandVal)
21156 Type *type = CallOperandVal->getType();
21157 // Look at the constraint type.
21158 switch (*constraint) {
21160 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21171 if (CallOperandVal->getType()->isIntegerTy())
21172 weight = CW_SpecificReg;
21177 if (type->isFloatingPointTy())
21178 weight = CW_SpecificReg;
21181 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21182 weight = CW_SpecificReg;
21186 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21187 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21188 weight = CW_Register;
21191 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21192 if (C->getZExtValue() <= 31)
21193 weight = CW_Constant;
21197 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21198 if (C->getZExtValue() <= 63)
21199 weight = CW_Constant;
21203 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21204 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21205 weight = CW_Constant;
21209 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21210 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21211 weight = CW_Constant;
21215 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21216 if (C->getZExtValue() <= 3)
21217 weight = CW_Constant;
21221 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21222 if (C->getZExtValue() <= 0xff)
21223 weight = CW_Constant;
21228 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21229 weight = CW_Constant;
21233 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21234 if ((C->getSExtValue() >= -0x80000000LL) &&
21235 (C->getSExtValue() <= 0x7fffffffLL))
21236 weight = CW_Constant;
21240 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21241 if (C->getZExtValue() <= 0xffffffff)
21242 weight = CW_Constant;
21249 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21250 /// with another that has more specific requirements based on the type of the
21251 /// corresponding operand.
21252 const char *X86TargetLowering::
21253 LowerXConstraint(EVT ConstraintVT) const {
21254 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21255 // 'f' like normal targets.
21256 if (ConstraintVT.isFloatingPoint()) {
21257 if (Subtarget->hasSSE2())
21259 if (Subtarget->hasSSE1())
21263 return TargetLowering::LowerXConstraint(ConstraintVT);
21266 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21267 /// vector. If it is invalid, don't add anything to Ops.
21268 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21269 std::string &Constraint,
21270 std::vector<SDValue>&Ops,
21271 SelectionDAG &DAG) const {
21274 // Only support length 1 constraints for now.
21275 if (Constraint.length() > 1) return;
21277 char ConstraintLetter = Constraint[0];
21278 switch (ConstraintLetter) {
21281 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21282 if (C->getZExtValue() <= 31) {
21283 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21289 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21290 if (C->getZExtValue() <= 63) {
21291 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21297 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21298 if (isInt<8>(C->getSExtValue())) {
21299 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21305 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21306 if (C->getZExtValue() <= 255) {
21307 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21313 // 32-bit signed value
21314 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21315 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21316 C->getSExtValue())) {
21317 // Widen to 64 bits here to get it sign extended.
21318 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21321 // FIXME gcc accepts some relocatable values here too, but only in certain
21322 // memory models; it's complicated.
21327 // 32-bit unsigned value
21328 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21329 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21330 C->getZExtValue())) {
21331 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21335 // FIXME gcc accepts some relocatable values here too, but only in certain
21336 // memory models; it's complicated.
21340 // Literal immediates are always ok.
21341 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21342 // Widen to 64 bits here to get it sign extended.
21343 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21347 // In any sort of PIC mode addresses need to be computed at runtime by
21348 // adding in a register or some sort of table lookup. These can't
21349 // be used as immediates.
21350 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21353 // If we are in non-pic codegen mode, we allow the address of a global (with
21354 // an optional displacement) to be used with 'i'.
21355 GlobalAddressSDNode *GA = nullptr;
21356 int64_t Offset = 0;
21358 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21360 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21361 Offset += GA->getOffset();
21363 } else if (Op.getOpcode() == ISD::ADD) {
21364 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21365 Offset += C->getZExtValue();
21366 Op = Op.getOperand(0);
21369 } else if (Op.getOpcode() == ISD::SUB) {
21370 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21371 Offset += -C->getZExtValue();
21372 Op = Op.getOperand(0);
21377 // Otherwise, this isn't something we can handle, reject it.
21381 const GlobalValue *GV = GA->getGlobal();
21382 // If we require an extra load to get this address, as in PIC mode, we
21383 // can't accept it.
21384 if (isGlobalStubReference(
21385 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21388 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21389 GA->getValueType(0), Offset);
21394 if (Result.getNode()) {
21395 Ops.push_back(Result);
21398 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21401 std::pair<unsigned, const TargetRegisterClass*>
21402 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21404 // First, see if this is a constraint that directly corresponds to an LLVM
21406 if (Constraint.size() == 1) {
21407 // GCC Constraint Letters
21408 switch (Constraint[0]) {
21410 // TODO: Slight differences here in allocation order and leaving
21411 // RIP in the class. Do they matter any more here than they do
21412 // in the normal allocation?
21413 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21414 if (Subtarget->is64Bit()) {
21415 if (VT == MVT::i32 || VT == MVT::f32)
21416 return std::make_pair(0U, &X86::GR32RegClass);
21417 if (VT == MVT::i16)
21418 return std::make_pair(0U, &X86::GR16RegClass);
21419 if (VT == MVT::i8 || VT == MVT::i1)
21420 return std::make_pair(0U, &X86::GR8RegClass);
21421 if (VT == MVT::i64 || VT == MVT::f64)
21422 return std::make_pair(0U, &X86::GR64RegClass);
21425 // 32-bit fallthrough
21426 case 'Q': // Q_REGS
21427 if (VT == MVT::i32 || VT == MVT::f32)
21428 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21429 if (VT == MVT::i16)
21430 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21431 if (VT == MVT::i8 || VT == MVT::i1)
21432 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21433 if (VT == MVT::i64)
21434 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21436 case 'r': // GENERAL_REGS
21437 case 'l': // INDEX_REGS
21438 if (VT == MVT::i8 || VT == MVT::i1)
21439 return std::make_pair(0U, &X86::GR8RegClass);
21440 if (VT == MVT::i16)
21441 return std::make_pair(0U, &X86::GR16RegClass);
21442 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21443 return std::make_pair(0U, &X86::GR32RegClass);
21444 return std::make_pair(0U, &X86::GR64RegClass);
21445 case 'R': // LEGACY_REGS
21446 if (VT == MVT::i8 || VT == MVT::i1)
21447 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21448 if (VT == MVT::i16)
21449 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21450 if (VT == MVT::i32 || !Subtarget->is64Bit())
21451 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21452 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21453 case 'f': // FP Stack registers.
21454 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21455 // value to the correct fpstack register class.
21456 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21457 return std::make_pair(0U, &X86::RFP32RegClass);
21458 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21459 return std::make_pair(0U, &X86::RFP64RegClass);
21460 return std::make_pair(0U, &X86::RFP80RegClass);
21461 case 'y': // MMX_REGS if MMX allowed.
21462 if (!Subtarget->hasMMX()) break;
21463 return std::make_pair(0U, &X86::VR64RegClass);
21464 case 'Y': // SSE_REGS if SSE2 allowed
21465 if (!Subtarget->hasSSE2()) break;
21467 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21468 if (!Subtarget->hasSSE1()) break;
21470 switch (VT.SimpleTy) {
21472 // Scalar SSE types.
21475 return std::make_pair(0U, &X86::FR32RegClass);
21478 return std::make_pair(0U, &X86::FR64RegClass);
21486 return std::make_pair(0U, &X86::VR128RegClass);
21494 return std::make_pair(0U, &X86::VR256RegClass);
21499 return std::make_pair(0U, &X86::VR512RegClass);
21505 // Use the default implementation in TargetLowering to convert the register
21506 // constraint into a member of a register class.
21507 std::pair<unsigned, const TargetRegisterClass*> Res;
21508 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21510 // Not found as a standard register?
21512 // Map st(0) -> st(7) -> ST0
21513 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21514 tolower(Constraint[1]) == 's' &&
21515 tolower(Constraint[2]) == 't' &&
21516 Constraint[3] == '(' &&
21517 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21518 Constraint[5] == ')' &&
21519 Constraint[6] == '}') {
21521 Res.first = X86::ST0+Constraint[4]-'0';
21522 Res.second = &X86::RFP80RegClass;
21526 // GCC allows "st(0)" to be called just plain "st".
21527 if (StringRef("{st}").equals_lower(Constraint)) {
21528 Res.first = X86::ST0;
21529 Res.second = &X86::RFP80RegClass;
21534 if (StringRef("{flags}").equals_lower(Constraint)) {
21535 Res.first = X86::EFLAGS;
21536 Res.second = &X86::CCRRegClass;
21540 // 'A' means EAX + EDX.
21541 if (Constraint == "A") {
21542 Res.first = X86::EAX;
21543 Res.second = &X86::GR32_ADRegClass;
21549 // Otherwise, check to see if this is a register class of the wrong value
21550 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21551 // turn into {ax},{dx}.
21552 if (Res.second->hasType(VT))
21553 return Res; // Correct type already, nothing to do.
21555 // All of the single-register GCC register classes map their values onto
21556 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21557 // really want an 8-bit or 32-bit register, map to the appropriate register
21558 // class and return the appropriate register.
21559 if (Res.second == &X86::GR16RegClass) {
21560 if (VT == MVT::i8 || VT == MVT::i1) {
21561 unsigned DestReg = 0;
21562 switch (Res.first) {
21564 case X86::AX: DestReg = X86::AL; break;
21565 case X86::DX: DestReg = X86::DL; break;
21566 case X86::CX: DestReg = X86::CL; break;
21567 case X86::BX: DestReg = X86::BL; break;
21570 Res.first = DestReg;
21571 Res.second = &X86::GR8RegClass;
21573 } else if (VT == MVT::i32 || VT == MVT::f32) {
21574 unsigned DestReg = 0;
21575 switch (Res.first) {
21577 case X86::AX: DestReg = X86::EAX; break;
21578 case X86::DX: DestReg = X86::EDX; break;
21579 case X86::CX: DestReg = X86::ECX; break;
21580 case X86::BX: DestReg = X86::EBX; break;
21581 case X86::SI: DestReg = X86::ESI; break;
21582 case X86::DI: DestReg = X86::EDI; break;
21583 case X86::BP: DestReg = X86::EBP; break;
21584 case X86::SP: DestReg = X86::ESP; break;
21587 Res.first = DestReg;
21588 Res.second = &X86::GR32RegClass;
21590 } else if (VT == MVT::i64 || VT == MVT::f64) {
21591 unsigned DestReg = 0;
21592 switch (Res.first) {
21594 case X86::AX: DestReg = X86::RAX; break;
21595 case X86::DX: DestReg = X86::RDX; break;
21596 case X86::CX: DestReg = X86::RCX; break;
21597 case X86::BX: DestReg = X86::RBX; break;
21598 case X86::SI: DestReg = X86::RSI; break;
21599 case X86::DI: DestReg = X86::RDI; break;
21600 case X86::BP: DestReg = X86::RBP; break;
21601 case X86::SP: DestReg = X86::RSP; break;
21604 Res.first = DestReg;
21605 Res.second = &X86::GR64RegClass;
21608 } else if (Res.second == &X86::FR32RegClass ||
21609 Res.second == &X86::FR64RegClass ||
21610 Res.second == &X86::VR128RegClass ||
21611 Res.second == &X86::VR256RegClass ||
21612 Res.second == &X86::FR32XRegClass ||
21613 Res.second == &X86::FR64XRegClass ||
21614 Res.second == &X86::VR128XRegClass ||
21615 Res.second == &X86::VR256XRegClass ||
21616 Res.second == &X86::VR512RegClass) {
21617 // Handle references to XMM physical registers that got mapped into the
21618 // wrong class. This can happen with constraints like {xmm0} where the
21619 // target independent register mapper will just pick the first match it can
21620 // find, ignoring the required type.
21622 if (VT == MVT::f32 || VT == MVT::i32)
21623 Res.second = &X86::FR32RegClass;
21624 else if (VT == MVT::f64 || VT == MVT::i64)
21625 Res.second = &X86::FR64RegClass;
21626 else if (X86::VR128RegClass.hasType(VT))
21627 Res.second = &X86::VR128RegClass;
21628 else if (X86::VR256RegClass.hasType(VT))
21629 Res.second = &X86::VR256RegClass;
21630 else if (X86::VR512RegClass.hasType(VT))
21631 Res.second = &X86::VR512RegClass;
21637 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21639 // Scaling factors are not free at all.
21640 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21641 // will take 2 allocations in the out of order engine instead of 1
21642 // for plain addressing mode, i.e. inst (reg1).
21644 // vaddps (%rsi,%drx), %ymm0, %ymm1
21645 // Requires two allocations (one for the load, one for the computation)
21647 // vaddps (%rsi), %ymm0, %ymm1
21648 // Requires just 1 allocation, i.e., freeing allocations for other operations
21649 // and having less micro operations to execute.
21651 // For some X86 architectures, this is even worse because for instance for
21652 // stores, the complex addressing mode forces the instruction to use the
21653 // "load" ports instead of the dedicated "store" port.
21654 // E.g., on Haswell:
21655 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21656 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21657 if (isLegalAddressingMode(AM, Ty))
21658 // Scale represents reg2 * scale, thus account for 1
21659 // as soon as we use a second register.
21660 return AM.Scale != 0;
21664 bool X86TargetLowering::isTargetFTOL() const {
21665 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();