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 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6061 const X86Subtarget *Subtarget) {
6062 EVT VT = N->getValueType(0);
6064 // Try to match a horizontal ADD or SUB.
6065 if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) ||
6066 ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) ||
6067 ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6068 VT == MVT::v16i16) && Subtarget->hasAVX())) {
6069 unsigned NumOperands = N->getNumOperands();
6070 unsigned Opcode = N->getOperand(0)->getOpcode();
6071 bool isCommutable = false;
6072 bool CanFold = false;
6077 isCommutable = true;
6084 // Verify that operands have the same opcode; also, the opcode can only
6085 // be either of: ADD, FADD, SUB, FSUB.
6086 SDValue InVec0, InVec1;
6087 for (unsigned i = 0, e = NumOperands; i != e && CanFold; ++i) {
6088 SDValue Op = N->getOperand(i);
6089 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6094 SDValue Op0 = Op.getOperand(0);
6095 SDValue Op1 = Op.getOperand(1);
6097 // Try to match the following pattern:
6098 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6099 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6100 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6101 Op0.getOperand(0) == Op1.getOperand(0) &&
6102 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6103 isa<ConstantSDNode>(Op1.getOperand(1)));
6107 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6108 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6109 unsigned ExpectedIndex = (i * 2) % NumOperands;
6112 InVec0 = Op0.getOperand(0);
6113 else if (i * 2 == NumOperands)
6114 InVec1 = Op0.getOperand(0);
6116 SDValue Expected = (i * 2 < NumOperands) ? InVec0 : InVec1;
6117 if (I0 == ExpectedIndex)
6118 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6119 else if (isCommutable && I1 == ExpectedIndex) {
6120 // Try to see if we can match the following dag sequence:
6121 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6122 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6129 default : llvm_unreachable("Unexpected opcode found!");
6130 case ISD::ADD : NewOpcode = X86ISD::HADD; break;
6131 case ISD::FADD : NewOpcode = X86ISD::FHADD; break;
6132 case ISD::SUB : NewOpcode = X86ISD::HSUB; break;
6133 case ISD::FSUB : NewOpcode = X86ISD::FHSUB; break;
6136 if (VT.is256BitVector()) {
6139 // Convert this sequence into two horizontal add/sub followed
6140 // by a concat vector.
6141 SDValue InVec0_LO = Extract128BitVector(InVec0, 0, DAG, dl);
6143 Extract128BitVector(InVec0, NumOperands/2, DAG, dl);
6144 SDValue InVec1_LO = Extract128BitVector(InVec1, 0, DAG, dl);
6146 Extract128BitVector(InVec1, NumOperands/2, DAG, dl);
6147 EVT NewVT = InVec0_LO.getValueType();
6149 SDValue LO = DAG.getNode(NewOpcode, dl, NewVT, InVec0_LO, InVec0_HI);
6150 SDValue HI = DAG.getNode(NewOpcode, dl, NewVT, InVec1_LO, InVec1_HI);
6151 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LO, HI);
6154 return DAG.getNode(NewOpcode, SDLoc(N), VT, InVec0, InVec1);
6162 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6165 MVT VT = Op.getSimpleValueType();
6166 MVT ExtVT = VT.getVectorElementType();
6167 unsigned NumElems = Op.getNumOperands();
6169 // Generate vectors for predicate vectors.
6170 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6171 return LowerBUILD_VECTORvXi1(Op, DAG);
6173 // Vectors containing all zeros can be matched by pxor and xorps later
6174 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6175 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6176 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6177 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6180 return getZeroVector(VT, Subtarget, DAG, dl);
6183 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6184 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6185 // vpcmpeqd on 256-bit vectors.
6186 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6187 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6190 if (!VT.is512BitVector())
6191 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6194 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6195 if (Broadcast.getNode())
6198 unsigned EVTBits = ExtVT.getSizeInBits();
6200 unsigned NumZero = 0;
6201 unsigned NumNonZero = 0;
6202 unsigned NonZeros = 0;
6203 bool IsAllConstants = true;
6204 SmallSet<SDValue, 8> Values;
6205 for (unsigned i = 0; i < NumElems; ++i) {
6206 SDValue Elt = Op.getOperand(i);
6207 if (Elt.getOpcode() == ISD::UNDEF)
6210 if (Elt.getOpcode() != ISD::Constant &&
6211 Elt.getOpcode() != ISD::ConstantFP)
6212 IsAllConstants = false;
6213 if (X86::isZeroNode(Elt))
6216 NonZeros |= (1 << i);
6221 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6222 if (NumNonZero == 0)
6223 return DAG.getUNDEF(VT);
6225 // Special case for single non-zero, non-undef, element.
6226 if (NumNonZero == 1) {
6227 unsigned Idx = countTrailingZeros(NonZeros);
6228 SDValue Item = Op.getOperand(Idx);
6230 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6231 // the value are obviously zero, truncate the value to i32 and do the
6232 // insertion that way. Only do this if the value is non-constant or if the
6233 // value is a constant being inserted into element 0. It is cheaper to do
6234 // a constant pool load than it is to do a movd + shuffle.
6235 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6236 (!IsAllConstants || Idx == 0)) {
6237 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6239 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6240 EVT VecVT = MVT::v4i32;
6241 unsigned VecElts = 4;
6243 // Truncate the value (which may itself be a constant) to i32, and
6244 // convert it to a vector with movd (S2V+shuffle to zero extend).
6245 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6246 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6247 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6249 // Now we have our 32-bit value zero extended in the low element of
6250 // a vector. If Idx != 0, swizzle it into place.
6252 SmallVector<int, 4> Mask;
6253 Mask.push_back(Idx);
6254 for (unsigned i = 1; i != VecElts; ++i)
6256 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6259 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6263 // If we have a constant or non-constant insertion into the low element of
6264 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6265 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6266 // depending on what the source datatype is.
6269 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6271 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6272 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6273 if (VT.is256BitVector() || VT.is512BitVector()) {
6274 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6275 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6276 Item, DAG.getIntPtrConstant(0));
6278 assert(VT.is128BitVector() && "Expected an SSE value type!");
6279 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6280 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6281 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6284 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6285 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6286 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6287 if (VT.is256BitVector()) {
6288 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6289 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6291 assert(VT.is128BitVector() && "Expected an SSE value type!");
6292 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6294 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6298 // Is it a vector logical left shift?
6299 if (NumElems == 2 && Idx == 1 &&
6300 X86::isZeroNode(Op.getOperand(0)) &&
6301 !X86::isZeroNode(Op.getOperand(1))) {
6302 unsigned NumBits = VT.getSizeInBits();
6303 return getVShift(true, VT,
6304 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6305 VT, Op.getOperand(1)),
6306 NumBits/2, DAG, *this, dl);
6309 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6312 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6313 // is a non-constant being inserted into an element other than the low one,
6314 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6315 // movd/movss) to move this into the low element, then shuffle it into
6317 if (EVTBits == 32) {
6318 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6320 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6321 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6322 SmallVector<int, 8> MaskVec;
6323 for (unsigned i = 0; i != NumElems; ++i)
6324 MaskVec.push_back(i == Idx ? 0 : 1);
6325 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6329 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6330 if (Values.size() == 1) {
6331 if (EVTBits == 32) {
6332 // Instead of a shuffle like this:
6333 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6334 // Check if it's possible to issue this instead.
6335 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6336 unsigned Idx = countTrailingZeros(NonZeros);
6337 SDValue Item = Op.getOperand(Idx);
6338 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6339 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6344 // A vector full of immediates; various special cases are already
6345 // handled, so this is best done with a single constant-pool load.
6349 // For AVX-length vectors, build the individual 128-bit pieces and use
6350 // shuffles to put them in place.
6351 if (VT.is256BitVector() || VT.is512BitVector()) {
6352 SmallVector<SDValue, 64> V;
6353 for (unsigned i = 0; i != NumElems; ++i)
6354 V.push_back(Op.getOperand(i));
6356 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6358 // Build both the lower and upper subvector.
6359 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6360 makeArrayRef(&V[0], NumElems/2));
6361 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6362 makeArrayRef(&V[NumElems / 2], NumElems/2));
6364 // Recreate the wider vector with the lower and upper part.
6365 if (VT.is256BitVector())
6366 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6367 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6370 // Let legalizer expand 2-wide build_vectors.
6371 if (EVTBits == 64) {
6372 if (NumNonZero == 1) {
6373 // One half is zero or undef.
6374 unsigned Idx = countTrailingZeros(NonZeros);
6375 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6376 Op.getOperand(Idx));
6377 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6382 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6383 if (EVTBits == 8 && NumElems == 16) {
6384 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6386 if (V.getNode()) return V;
6389 if (EVTBits == 16 && NumElems == 8) {
6390 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6392 if (V.getNode()) return V;
6395 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6396 if (EVTBits == 32 && NumElems == 4) {
6397 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6398 NumZero, DAG, Subtarget, *this);
6403 // If element VT is == 32 bits, turn it into a number of shuffles.
6404 SmallVector<SDValue, 8> V(NumElems);
6405 if (NumElems == 4 && NumZero > 0) {
6406 for (unsigned i = 0; i < 4; ++i) {
6407 bool isZero = !(NonZeros & (1 << i));
6409 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6411 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6414 for (unsigned i = 0; i < 2; ++i) {
6415 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6418 V[i] = V[i*2]; // Must be a zero vector.
6421 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6424 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6427 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6432 bool Reverse1 = (NonZeros & 0x3) == 2;
6433 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6437 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6438 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6440 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6443 if (Values.size() > 1 && VT.is128BitVector()) {
6444 // Check for a build vector of consecutive loads.
6445 for (unsigned i = 0; i < NumElems; ++i)
6446 V[i] = Op.getOperand(i);
6448 // Check for elements which are consecutive loads.
6449 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6453 // Check for a build vector from mostly shuffle plus few inserting.
6454 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6458 // For SSE 4.1, use insertps to put the high elements into the low element.
6459 if (getSubtarget()->hasSSE41()) {
6461 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6462 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6464 Result = DAG.getUNDEF(VT);
6466 for (unsigned i = 1; i < NumElems; ++i) {
6467 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6468 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6469 Op.getOperand(i), DAG.getIntPtrConstant(i));
6474 // Otherwise, expand into a number of unpckl*, start by extending each of
6475 // our (non-undef) elements to the full vector width with the element in the
6476 // bottom slot of the vector (which generates no code for SSE).
6477 for (unsigned i = 0; i < NumElems; ++i) {
6478 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6479 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6481 V[i] = DAG.getUNDEF(VT);
6484 // Next, we iteratively mix elements, e.g. for v4f32:
6485 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6486 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6487 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6488 unsigned EltStride = NumElems >> 1;
6489 while (EltStride != 0) {
6490 for (unsigned i = 0; i < EltStride; ++i) {
6491 // If V[i+EltStride] is undef and this is the first round of mixing,
6492 // then it is safe to just drop this shuffle: V[i] is already in the
6493 // right place, the one element (since it's the first round) being
6494 // inserted as undef can be dropped. This isn't safe for successive
6495 // rounds because they will permute elements within both vectors.
6496 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6497 EltStride == NumElems/2)
6500 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6509 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6510 // to create 256-bit vectors from two other 128-bit ones.
6511 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6513 MVT ResVT = Op.getSimpleValueType();
6515 assert((ResVT.is256BitVector() ||
6516 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6518 SDValue V1 = Op.getOperand(0);
6519 SDValue V2 = Op.getOperand(1);
6520 unsigned NumElems = ResVT.getVectorNumElements();
6521 if(ResVT.is256BitVector())
6522 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6524 if (Op.getNumOperands() == 4) {
6525 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6526 ResVT.getVectorNumElements()/2);
6527 SDValue V3 = Op.getOperand(2);
6528 SDValue V4 = Op.getOperand(3);
6529 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6530 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6532 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6535 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6536 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6537 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6538 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6539 Op.getNumOperands() == 4)));
6541 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6542 // from two other 128-bit ones.
6544 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6545 return LowerAVXCONCAT_VECTORS(Op, DAG);
6548 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6549 bool hasInt256, unsigned *MaskOut = nullptr) {
6550 MVT EltVT = VT.getVectorElementType();
6552 // There is no blend with immediate in AVX-512.
6553 if (VT.is512BitVector())
6556 if (!hasSSE41 || EltVT == MVT::i8)
6558 if (!hasInt256 && VT == MVT::v16i16)
6561 unsigned MaskValue = 0;
6562 unsigned NumElems = VT.getVectorNumElements();
6563 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6564 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6565 unsigned NumElemsInLane = NumElems / NumLanes;
6567 // Blend for v16i16 should be symetric for the both lanes.
6568 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6570 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6571 int EltIdx = MaskVals[i];
6573 if ((EltIdx < 0 || EltIdx == (int)i) &&
6574 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6577 if (((unsigned)EltIdx == (i + NumElems)) &&
6578 (SndLaneEltIdx < 0 ||
6579 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6580 MaskValue |= (1 << i);
6586 *MaskOut = MaskValue;
6590 // Try to lower a shuffle node into a simple blend instruction.
6591 // This function assumes isBlendMask returns true for this
6592 // SuffleVectorSDNode
6593 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6595 const X86Subtarget *Subtarget,
6596 SelectionDAG &DAG) {
6597 MVT VT = SVOp->getSimpleValueType(0);
6598 MVT EltVT = VT.getVectorElementType();
6599 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6600 Subtarget->hasInt256() && "Trying to lower a "
6601 "VECTOR_SHUFFLE to a Blend but "
6602 "with the wrong mask"));
6603 SDValue V1 = SVOp->getOperand(0);
6604 SDValue V2 = SVOp->getOperand(1);
6606 unsigned NumElems = VT.getVectorNumElements();
6608 // Convert i32 vectors to floating point if it is not AVX2.
6609 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6611 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6612 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6614 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6615 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6618 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6619 DAG.getConstant(MaskValue, MVT::i32));
6620 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6623 /// In vector type \p VT, return true if the element at index \p InputIdx
6624 /// falls on a different 128-bit lane than \p OutputIdx.
6625 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6626 unsigned OutputIdx) {
6627 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6628 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6631 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6632 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6633 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6634 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6636 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6637 SelectionDAG &DAG) {
6638 MVT VT = V1.getSimpleValueType();
6639 assert(VT.is128BitVector() || VT.is256BitVector());
6641 MVT EltVT = VT.getVectorElementType();
6642 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6643 unsigned NumElts = VT.getVectorNumElements();
6645 SmallVector<SDValue, 32> PshufbMask;
6646 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6647 int InputIdx = MaskVals[OutputIdx];
6648 unsigned InputByteIdx;
6650 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6651 InputByteIdx = 0x80;
6653 // Cross lane is not allowed.
6654 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6656 InputByteIdx = InputIdx * EltSizeInBytes;
6657 // Index is an byte offset within the 128-bit lane.
6658 InputByteIdx &= 0xf;
6661 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6662 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6663 if (InputByteIdx != 0x80)
6668 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6670 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6671 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6672 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6675 // v8i16 shuffles - Prefer shuffles in the following order:
6676 // 1. [all] pshuflw, pshufhw, optional move
6677 // 2. [ssse3] 1 x pshufb
6678 // 3. [ssse3] 2 x pshufb + 1 x por
6679 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6681 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6682 SelectionDAG &DAG) {
6683 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6684 SDValue V1 = SVOp->getOperand(0);
6685 SDValue V2 = SVOp->getOperand(1);
6687 SmallVector<int, 8> MaskVals;
6689 // Determine if more than 1 of the words in each of the low and high quadwords
6690 // of the result come from the same quadword of one of the two inputs. Undef
6691 // mask values count as coming from any quadword, for better codegen.
6693 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6694 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6695 unsigned LoQuad[] = { 0, 0, 0, 0 };
6696 unsigned HiQuad[] = { 0, 0, 0, 0 };
6697 // Indices of quads used.
6698 std::bitset<4> InputQuads;
6699 for (unsigned i = 0; i < 8; ++i) {
6700 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6701 int EltIdx = SVOp->getMaskElt(i);
6702 MaskVals.push_back(EltIdx);
6711 InputQuads.set(EltIdx / 4);
6714 int BestLoQuad = -1;
6715 unsigned MaxQuad = 1;
6716 for (unsigned i = 0; i < 4; ++i) {
6717 if (LoQuad[i] > MaxQuad) {
6719 MaxQuad = LoQuad[i];
6723 int BestHiQuad = -1;
6725 for (unsigned i = 0; i < 4; ++i) {
6726 if (HiQuad[i] > MaxQuad) {
6728 MaxQuad = HiQuad[i];
6732 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6733 // of the two input vectors, shuffle them into one input vector so only a
6734 // single pshufb instruction is necessary. If there are more than 2 input
6735 // quads, disable the next transformation since it does not help SSSE3.
6736 bool V1Used = InputQuads[0] || InputQuads[1];
6737 bool V2Used = InputQuads[2] || InputQuads[3];
6738 if (Subtarget->hasSSSE3()) {
6739 if (InputQuads.count() == 2 && V1Used && V2Used) {
6740 BestLoQuad = InputQuads[0] ? 0 : 1;
6741 BestHiQuad = InputQuads[2] ? 2 : 3;
6743 if (InputQuads.count() > 2) {
6749 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6750 // the shuffle mask. If a quad is scored as -1, that means that it contains
6751 // words from all 4 input quadwords.
6753 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6755 BestLoQuad < 0 ? 0 : BestLoQuad,
6756 BestHiQuad < 0 ? 1 : BestHiQuad
6758 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6759 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6760 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6761 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6763 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6764 // source words for the shuffle, to aid later transformations.
6765 bool AllWordsInNewV = true;
6766 bool InOrder[2] = { true, true };
6767 for (unsigned i = 0; i != 8; ++i) {
6768 int idx = MaskVals[i];
6770 InOrder[i/4] = false;
6771 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6773 AllWordsInNewV = false;
6777 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6778 if (AllWordsInNewV) {
6779 for (int i = 0; i != 8; ++i) {
6780 int idx = MaskVals[i];
6783 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6784 if ((idx != i) && idx < 4)
6786 if ((idx != i) && idx > 3)
6795 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6796 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6797 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6798 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6799 unsigned TargetMask = 0;
6800 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6801 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6802 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6803 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6804 getShufflePSHUFLWImmediate(SVOp);
6805 V1 = NewV.getOperand(0);
6806 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6810 // Promote splats to a larger type which usually leads to more efficient code.
6811 // FIXME: Is this true if pshufb is available?
6812 if (SVOp->isSplat())
6813 return PromoteSplat(SVOp, DAG);
6815 // If we have SSSE3, and all words of the result are from 1 input vector,
6816 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6817 // is present, fall back to case 4.
6818 if (Subtarget->hasSSSE3()) {
6819 SmallVector<SDValue,16> pshufbMask;
6821 // If we have elements from both input vectors, set the high bit of the
6822 // shuffle mask element to zero out elements that come from V2 in the V1
6823 // mask, and elements that come from V1 in the V2 mask, so that the two
6824 // results can be OR'd together.
6825 bool TwoInputs = V1Used && V2Used;
6826 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6828 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6830 // Calculate the shuffle mask for the second input, shuffle it, and
6831 // OR it with the first shuffled input.
6832 CommuteVectorShuffleMask(MaskVals, 8);
6833 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6834 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6835 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6838 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6839 // and update MaskVals with new element order.
6840 std::bitset<8> InOrder;
6841 if (BestLoQuad >= 0) {
6842 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6843 for (int i = 0; i != 4; ++i) {
6844 int idx = MaskVals[i];
6847 } else if ((idx / 4) == BestLoQuad) {
6852 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6855 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6856 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6857 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6859 getShufflePSHUFLWImmediate(SVOp), DAG);
6863 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6864 // and update MaskVals with the new element order.
6865 if (BestHiQuad >= 0) {
6866 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6867 for (unsigned i = 4; i != 8; ++i) {
6868 int idx = MaskVals[i];
6871 } else if ((idx / 4) == BestHiQuad) {
6872 MaskV[i] = (idx & 3) + 4;
6876 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6879 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6880 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6881 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6883 getShufflePSHUFHWImmediate(SVOp), DAG);
6887 // In case BestHi & BestLo were both -1, which means each quadword has a word
6888 // from each of the four input quadwords, calculate the InOrder bitvector now
6889 // before falling through to the insert/extract cleanup.
6890 if (BestLoQuad == -1 && BestHiQuad == -1) {
6892 for (int i = 0; i != 8; ++i)
6893 if (MaskVals[i] < 0 || MaskVals[i] == i)
6897 // The other elements are put in the right place using pextrw and pinsrw.
6898 for (unsigned i = 0; i != 8; ++i) {
6901 int EltIdx = MaskVals[i];
6904 SDValue ExtOp = (EltIdx < 8) ?
6905 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6906 DAG.getIntPtrConstant(EltIdx)) :
6907 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6908 DAG.getIntPtrConstant(EltIdx - 8));
6909 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6910 DAG.getIntPtrConstant(i));
6915 /// \brief v16i16 shuffles
6917 /// FIXME: We only support generation of a single pshufb currently. We can
6918 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6919 /// well (e.g 2 x pshufb + 1 x por).
6921 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6922 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6923 SDValue V1 = SVOp->getOperand(0);
6924 SDValue V2 = SVOp->getOperand(1);
6927 if (V2.getOpcode() != ISD::UNDEF)
6930 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6931 return getPSHUFB(MaskVals, V1, dl, DAG);
6934 // v16i8 shuffles - Prefer shuffles in the following order:
6935 // 1. [ssse3] 1 x pshufb
6936 // 2. [ssse3] 2 x pshufb + 1 x por
6937 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6938 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6939 const X86Subtarget* Subtarget,
6940 SelectionDAG &DAG) {
6941 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6942 SDValue V1 = SVOp->getOperand(0);
6943 SDValue V2 = SVOp->getOperand(1);
6945 ArrayRef<int> MaskVals = SVOp->getMask();
6947 // Promote splats to a larger type which usually leads to more efficient code.
6948 // FIXME: Is this true if pshufb is available?
6949 if (SVOp->isSplat())
6950 return PromoteSplat(SVOp, DAG);
6952 // If we have SSSE3, case 1 is generated when all result bytes come from
6953 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6954 // present, fall back to case 3.
6956 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6957 if (Subtarget->hasSSSE3()) {
6958 SmallVector<SDValue,16> pshufbMask;
6960 // If all result elements are from one input vector, then only translate
6961 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6963 // Otherwise, we have elements from both input vectors, and must zero out
6964 // elements that come from V2 in the first mask, and V1 in the second mask
6965 // so that we can OR them together.
6966 for (unsigned i = 0; i != 16; ++i) {
6967 int EltIdx = MaskVals[i];
6968 if (EltIdx < 0 || EltIdx >= 16)
6970 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6972 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6973 DAG.getNode(ISD::BUILD_VECTOR, dl,
6974 MVT::v16i8, pshufbMask));
6976 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6977 // the 2nd operand if it's undefined or zero.
6978 if (V2.getOpcode() == ISD::UNDEF ||
6979 ISD::isBuildVectorAllZeros(V2.getNode()))
6982 // Calculate the shuffle mask for the second input, shuffle it, and
6983 // OR it with the first shuffled input.
6985 for (unsigned i = 0; i != 16; ++i) {
6986 int EltIdx = MaskVals[i];
6987 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6988 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6990 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6991 DAG.getNode(ISD::BUILD_VECTOR, dl,
6992 MVT::v16i8, pshufbMask));
6993 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6996 // No SSSE3 - Calculate in place words and then fix all out of place words
6997 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6998 // the 16 different words that comprise the two doublequadword input vectors.
6999 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7000 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7002 for (int i = 0; i != 8; ++i) {
7003 int Elt0 = MaskVals[i*2];
7004 int Elt1 = MaskVals[i*2+1];
7006 // This word of the result is all undef, skip it.
7007 if (Elt0 < 0 && Elt1 < 0)
7010 // This word of the result is already in the correct place, skip it.
7011 if ((Elt0 == i*2) && (Elt1 == i*2+1))
7014 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7015 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7018 // If Elt0 and Elt1 are defined, are consecutive, and can be load
7019 // using a single extract together, load it and store it.
7020 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7021 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7022 DAG.getIntPtrConstant(Elt1 / 2));
7023 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7024 DAG.getIntPtrConstant(i));
7028 // If Elt1 is defined, extract it from the appropriate source. If the
7029 // source byte is not also odd, shift the extracted word left 8 bits
7030 // otherwise clear the bottom 8 bits if we need to do an or.
7032 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7033 DAG.getIntPtrConstant(Elt1 / 2));
7034 if ((Elt1 & 1) == 0)
7035 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7037 TLI.getShiftAmountTy(InsElt.getValueType())));
7039 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7040 DAG.getConstant(0xFF00, MVT::i16));
7042 // If Elt0 is defined, extract it from the appropriate source. If the
7043 // source byte is not also even, shift the extracted word right 8 bits. If
7044 // Elt1 was also defined, OR the extracted values together before
7045 // inserting them in the result.
7047 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7048 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7049 if ((Elt0 & 1) != 0)
7050 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7052 TLI.getShiftAmountTy(InsElt0.getValueType())));
7054 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7055 DAG.getConstant(0x00FF, MVT::i16));
7056 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7059 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7060 DAG.getIntPtrConstant(i));
7062 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7065 // v32i8 shuffles - Translate to VPSHUFB if possible.
7067 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7068 const X86Subtarget *Subtarget,
7069 SelectionDAG &DAG) {
7070 MVT VT = SVOp->getSimpleValueType(0);
7071 SDValue V1 = SVOp->getOperand(0);
7072 SDValue V2 = SVOp->getOperand(1);
7074 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7076 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7077 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7078 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7080 // VPSHUFB may be generated if
7081 // (1) one of input vector is undefined or zeroinitializer.
7082 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7083 // And (2) the mask indexes don't cross the 128-bit lane.
7084 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7085 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7088 if (V1IsAllZero && !V2IsAllZero) {
7089 CommuteVectorShuffleMask(MaskVals, 32);
7092 return getPSHUFB(MaskVals, V1, dl, DAG);
7095 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7096 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7097 /// done when every pair / quad of shuffle mask elements point to elements in
7098 /// the right sequence. e.g.
7099 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7101 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7102 SelectionDAG &DAG) {
7103 MVT VT = SVOp->getSimpleValueType(0);
7105 unsigned NumElems = VT.getVectorNumElements();
7108 switch (VT.SimpleTy) {
7109 default: llvm_unreachable("Unexpected!");
7112 return SDValue(SVOp, 0);
7113 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
7114 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
7115 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7116 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7117 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7118 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7121 SmallVector<int, 8> MaskVec;
7122 for (unsigned i = 0; i != NumElems; i += Scale) {
7124 for (unsigned j = 0; j != Scale; ++j) {
7125 int EltIdx = SVOp->getMaskElt(i+j);
7129 StartIdx = (EltIdx / Scale);
7130 if (EltIdx != (int)(StartIdx*Scale + j))
7133 MaskVec.push_back(StartIdx);
7136 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7137 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7138 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7141 /// getVZextMovL - Return a zero-extending vector move low node.
7143 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7144 SDValue SrcOp, SelectionDAG &DAG,
7145 const X86Subtarget *Subtarget, SDLoc dl) {
7146 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7147 LoadSDNode *LD = nullptr;
7148 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7149 LD = dyn_cast<LoadSDNode>(SrcOp);
7151 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7153 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7154 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7155 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7156 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7157 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7159 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7160 return DAG.getNode(ISD::BITCAST, dl, VT,
7161 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7162 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7170 return DAG.getNode(ISD::BITCAST, dl, VT,
7171 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7172 DAG.getNode(ISD::BITCAST, dl,
7176 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7177 /// which could not be matched by any known target speficic shuffle
7179 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7181 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7182 if (NewOp.getNode())
7185 MVT VT = SVOp->getSimpleValueType(0);
7187 unsigned NumElems = VT.getVectorNumElements();
7188 unsigned NumLaneElems = NumElems / 2;
7191 MVT EltVT = VT.getVectorElementType();
7192 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7195 SmallVector<int, 16> Mask;
7196 for (unsigned l = 0; l < 2; ++l) {
7197 // Build a shuffle mask for the output, discovering on the fly which
7198 // input vectors to use as shuffle operands (recorded in InputUsed).
7199 // If building a suitable shuffle vector proves too hard, then bail
7200 // out with UseBuildVector set.
7201 bool UseBuildVector = false;
7202 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7203 unsigned LaneStart = l * NumLaneElems;
7204 for (unsigned i = 0; i != NumLaneElems; ++i) {
7205 // The mask element. This indexes into the input.
7206 int Idx = SVOp->getMaskElt(i+LaneStart);
7208 // the mask element does not index into any input vector.
7213 // The input vector this mask element indexes into.
7214 int Input = Idx / NumLaneElems;
7216 // Turn the index into an offset from the start of the input vector.
7217 Idx -= Input * NumLaneElems;
7219 // Find or create a shuffle vector operand to hold this input.
7221 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7222 if (InputUsed[OpNo] == Input)
7223 // This input vector is already an operand.
7225 if (InputUsed[OpNo] < 0) {
7226 // Create a new operand for this input vector.
7227 InputUsed[OpNo] = Input;
7232 if (OpNo >= array_lengthof(InputUsed)) {
7233 // More than two input vectors used! Give up on trying to create a
7234 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7235 UseBuildVector = true;
7239 // Add the mask index for the new shuffle vector.
7240 Mask.push_back(Idx + OpNo * NumLaneElems);
7243 if (UseBuildVector) {
7244 SmallVector<SDValue, 16> SVOps;
7245 for (unsigned i = 0; i != NumLaneElems; ++i) {
7246 // The mask element. This indexes into the input.
7247 int Idx = SVOp->getMaskElt(i+LaneStart);
7249 SVOps.push_back(DAG.getUNDEF(EltVT));
7253 // The input vector this mask element indexes into.
7254 int Input = Idx / NumElems;
7256 // Turn the index into an offset from the start of the input vector.
7257 Idx -= Input * NumElems;
7259 // Extract the vector element by hand.
7260 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7261 SVOp->getOperand(Input),
7262 DAG.getIntPtrConstant(Idx)));
7265 // Construct the output using a BUILD_VECTOR.
7266 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7267 } else if (InputUsed[0] < 0) {
7268 // No input vectors were used! The result is undefined.
7269 Output[l] = DAG.getUNDEF(NVT);
7271 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7272 (InputUsed[0] % 2) * NumLaneElems,
7274 // If only one input was used, use an undefined vector for the other.
7275 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7276 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7277 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7278 // At least one input vector was used. Create a new shuffle vector.
7279 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7285 // Concatenate the result back
7286 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7289 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7290 /// 4 elements, and match them with several different shuffle types.
7292 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7293 SDValue V1 = SVOp->getOperand(0);
7294 SDValue V2 = SVOp->getOperand(1);
7296 MVT VT = SVOp->getSimpleValueType(0);
7298 assert(VT.is128BitVector() && "Unsupported vector size");
7300 std::pair<int, int> Locs[4];
7301 int Mask1[] = { -1, -1, -1, -1 };
7302 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7306 for (unsigned i = 0; i != 4; ++i) {
7307 int Idx = PermMask[i];
7309 Locs[i] = std::make_pair(-1, -1);
7311 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7313 Locs[i] = std::make_pair(0, NumLo);
7317 Locs[i] = std::make_pair(1, NumHi);
7319 Mask1[2+NumHi] = Idx;
7325 if (NumLo <= 2 && NumHi <= 2) {
7326 // If no more than two elements come from either vector. This can be
7327 // implemented with two shuffles. First shuffle gather the elements.
7328 // The second shuffle, which takes the first shuffle as both of its
7329 // vector operands, put the elements into the right order.
7330 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7332 int Mask2[] = { -1, -1, -1, -1 };
7334 for (unsigned i = 0; i != 4; ++i)
7335 if (Locs[i].first != -1) {
7336 unsigned Idx = (i < 2) ? 0 : 4;
7337 Idx += Locs[i].first * 2 + Locs[i].second;
7341 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7344 if (NumLo == 3 || NumHi == 3) {
7345 // Otherwise, we must have three elements from one vector, call it X, and
7346 // one element from the other, call it Y. First, use a shufps to build an
7347 // intermediate vector with the one element from Y and the element from X
7348 // that will be in the same half in the final destination (the indexes don't
7349 // matter). Then, use a shufps to build the final vector, taking the half
7350 // containing the element from Y from the intermediate, and the other half
7353 // Normalize it so the 3 elements come from V1.
7354 CommuteVectorShuffleMask(PermMask, 4);
7358 // Find the element from V2.
7360 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7361 int Val = PermMask[HiIndex];
7368 Mask1[0] = PermMask[HiIndex];
7370 Mask1[2] = PermMask[HiIndex^1];
7372 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7375 Mask1[0] = PermMask[0];
7376 Mask1[1] = PermMask[1];
7377 Mask1[2] = HiIndex & 1 ? 6 : 4;
7378 Mask1[3] = HiIndex & 1 ? 4 : 6;
7379 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7382 Mask1[0] = HiIndex & 1 ? 2 : 0;
7383 Mask1[1] = HiIndex & 1 ? 0 : 2;
7384 Mask1[2] = PermMask[2];
7385 Mask1[3] = PermMask[3];
7390 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7393 // Break it into (shuffle shuffle_hi, shuffle_lo).
7394 int LoMask[] = { -1, -1, -1, -1 };
7395 int HiMask[] = { -1, -1, -1, -1 };
7397 int *MaskPtr = LoMask;
7398 unsigned MaskIdx = 0;
7401 for (unsigned i = 0; i != 4; ++i) {
7408 int Idx = PermMask[i];
7410 Locs[i] = std::make_pair(-1, -1);
7411 } else if (Idx < 4) {
7412 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7413 MaskPtr[LoIdx] = Idx;
7416 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7417 MaskPtr[HiIdx] = Idx;
7422 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7423 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7424 int MaskOps[] = { -1, -1, -1, -1 };
7425 for (unsigned i = 0; i != 4; ++i)
7426 if (Locs[i].first != -1)
7427 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7428 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7431 static bool MayFoldVectorLoad(SDValue V) {
7432 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7433 V = V.getOperand(0);
7435 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7436 V = V.getOperand(0);
7437 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7438 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7439 // BUILD_VECTOR (load), undef
7440 V = V.getOperand(0);
7442 return MayFoldLoad(V);
7446 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7447 MVT VT = Op.getSimpleValueType();
7449 // Canonizalize to v2f64.
7450 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7451 return DAG.getNode(ISD::BITCAST, dl, VT,
7452 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7457 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7459 SDValue V1 = Op.getOperand(0);
7460 SDValue V2 = Op.getOperand(1);
7461 MVT VT = Op.getSimpleValueType();
7463 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7465 if (HasSSE2 && VT == MVT::v2f64)
7466 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7468 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7469 return DAG.getNode(ISD::BITCAST, dl, VT,
7470 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7471 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7472 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7476 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7477 SDValue V1 = Op.getOperand(0);
7478 SDValue V2 = Op.getOperand(1);
7479 MVT VT = Op.getSimpleValueType();
7481 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7482 "unsupported shuffle type");
7484 if (V2.getOpcode() == ISD::UNDEF)
7488 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7492 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7493 SDValue V1 = Op.getOperand(0);
7494 SDValue V2 = Op.getOperand(1);
7495 MVT VT = Op.getSimpleValueType();
7496 unsigned NumElems = VT.getVectorNumElements();
7498 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7499 // operand of these instructions is only memory, so check if there's a
7500 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7502 bool CanFoldLoad = false;
7504 // Trivial case, when V2 comes from a load.
7505 if (MayFoldVectorLoad(V2))
7508 // When V1 is a load, it can be folded later into a store in isel, example:
7509 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7511 // (MOVLPSmr addr:$src1, VR128:$src2)
7512 // So, recognize this potential and also use MOVLPS or MOVLPD
7513 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7516 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7518 if (HasSSE2 && NumElems == 2)
7519 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7522 // If we don't care about the second element, proceed to use movss.
7523 if (SVOp->getMaskElt(1) != -1)
7524 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7527 // movl and movlp will both match v2i64, but v2i64 is never matched by
7528 // movl earlier because we make it strict to avoid messing with the movlp load
7529 // folding logic (see the code above getMOVLP call). Match it here then,
7530 // this is horrible, but will stay like this until we move all shuffle
7531 // matching to x86 specific nodes. Note that for the 1st condition all
7532 // types are matched with movsd.
7534 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7535 // as to remove this logic from here, as much as possible
7536 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7537 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7538 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7541 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7543 // Invert the operand order and use SHUFPS to match it.
7544 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7545 getShuffleSHUFImmediate(SVOp), DAG);
7548 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7549 SelectionDAG &DAG) {
7551 MVT VT = Load->getSimpleValueType(0);
7552 MVT EVT = VT.getVectorElementType();
7553 SDValue Addr = Load->getOperand(1);
7554 SDValue NewAddr = DAG.getNode(
7555 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7556 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7559 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7560 DAG.getMachineFunction().getMachineMemOperand(
7561 Load->getMemOperand(), 0, EVT.getStoreSize()));
7565 // It is only safe to call this function if isINSERTPSMask is true for
7566 // this shufflevector mask.
7567 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7568 SelectionDAG &DAG) {
7569 // Generate an insertps instruction when inserting an f32 from memory onto a
7570 // v4f32 or when copying a member from one v4f32 to another.
7571 // We also use it for transferring i32 from one register to another,
7572 // since it simply copies the same bits.
7573 // If we're transferring an i32 from memory to a specific element in a
7574 // register, we output a generic DAG that will match the PINSRD
7576 MVT VT = SVOp->getSimpleValueType(0);
7577 MVT EVT = VT.getVectorElementType();
7578 SDValue V1 = SVOp->getOperand(0);
7579 SDValue V2 = SVOp->getOperand(1);
7580 auto Mask = SVOp->getMask();
7581 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7582 "unsupported vector type for insertps/pinsrd");
7584 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7585 auto FromV2Predicate = [](const int &i) { return i >= 4; };
7586 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7594 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7597 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7598 "More than one element from V1 and from V2, or no elements from one "
7599 "of the vectors. This case should not have returned true from "
7604 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7607 if (MayFoldLoad(From)) {
7608 // Trivial case, when From comes from a load and is only used by the
7609 // shuffle. Make it use insertps from the vector that we need from that
7612 NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7613 if (!NewLoad.getNode())
7616 if (EVT == MVT::f32) {
7617 // Create this as a scalar to vector to match the instruction pattern.
7618 SDValue LoadScalarToVector =
7619 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7620 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7621 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7623 } else { // EVT == MVT::i32
7624 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7625 // instruction, to match the PINSRD instruction, which loads an i32 to a
7626 // certain vector element.
7627 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7628 DAG.getConstant(DestIndex, MVT::i32));
7632 // Vector-element-to-vector
7633 unsigned SrcIndex = Mask[DestIndex] % 4;
7634 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7635 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7638 // Reduce a vector shuffle to zext.
7639 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7640 SelectionDAG &DAG) {
7641 // PMOVZX is only available from SSE41.
7642 if (!Subtarget->hasSSE41())
7645 MVT VT = Op.getSimpleValueType();
7647 // Only AVX2 support 256-bit vector integer extending.
7648 if (!Subtarget->hasInt256() && VT.is256BitVector())
7651 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7653 SDValue V1 = Op.getOperand(0);
7654 SDValue V2 = Op.getOperand(1);
7655 unsigned NumElems = VT.getVectorNumElements();
7657 // Extending is an unary operation and the element type of the source vector
7658 // won't be equal to or larger than i64.
7659 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7660 VT.getVectorElementType() == MVT::i64)
7663 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7664 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7665 while ((1U << Shift) < NumElems) {
7666 if (SVOp->getMaskElt(1U << Shift) == 1)
7669 // The maximal ratio is 8, i.e. from i8 to i64.
7674 // Check the shuffle mask.
7675 unsigned Mask = (1U << Shift) - 1;
7676 for (unsigned i = 0; i != NumElems; ++i) {
7677 int EltIdx = SVOp->getMaskElt(i);
7678 if ((i & Mask) != 0 && EltIdx != -1)
7680 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7684 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7685 MVT NeVT = MVT::getIntegerVT(NBits);
7686 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7688 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7691 // Simplify the operand as it's prepared to be fed into shuffle.
7692 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7693 if (V1.getOpcode() == ISD::BITCAST &&
7694 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7695 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7696 V1.getOperand(0).getOperand(0)
7697 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7698 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7699 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7700 ConstantSDNode *CIdx =
7701 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7702 // If it's foldable, i.e. normal load with single use, we will let code
7703 // selection to fold it. Otherwise, we will short the conversion sequence.
7704 if (CIdx && CIdx->getZExtValue() == 0 &&
7705 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7706 MVT FullVT = V.getSimpleValueType();
7707 MVT V1VT = V1.getSimpleValueType();
7708 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7709 // The "ext_vec_elt" node is wider than the result node.
7710 // In this case we should extract subvector from V.
7711 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7712 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7713 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7714 FullVT.getVectorNumElements()/Ratio);
7715 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7716 DAG.getIntPtrConstant(0));
7718 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7722 return DAG.getNode(ISD::BITCAST, DL, VT,
7723 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7726 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7727 SelectionDAG &DAG) {
7728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7729 MVT VT = Op.getSimpleValueType();
7731 SDValue V1 = Op.getOperand(0);
7732 SDValue V2 = Op.getOperand(1);
7734 if (isZeroShuffle(SVOp))
7735 return getZeroVector(VT, Subtarget, DAG, dl);
7737 // Handle splat operations
7738 if (SVOp->isSplat()) {
7739 // Use vbroadcast whenever the splat comes from a foldable load
7740 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7741 if (Broadcast.getNode())
7745 // Check integer expanding shuffles.
7746 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7747 if (NewOp.getNode())
7750 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7752 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7754 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7755 if (NewOp.getNode())
7756 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7757 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7758 // FIXME: Figure out a cleaner way to do this.
7759 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7760 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7761 if (NewOp.getNode()) {
7762 MVT NewVT = NewOp.getSimpleValueType();
7763 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7764 NewVT, true, false))
7765 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7768 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7769 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7770 if (NewOp.getNode()) {
7771 MVT NewVT = NewOp.getSimpleValueType();
7772 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7773 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7782 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7783 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7784 SDValue V1 = Op.getOperand(0);
7785 SDValue V2 = Op.getOperand(1);
7786 MVT VT = Op.getSimpleValueType();
7788 unsigned NumElems = VT.getVectorNumElements();
7789 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7790 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7791 bool V1IsSplat = false;
7792 bool V2IsSplat = false;
7793 bool HasSSE2 = Subtarget->hasSSE2();
7794 bool HasFp256 = Subtarget->hasFp256();
7795 bool HasInt256 = Subtarget->hasInt256();
7796 MachineFunction &MF = DAG.getMachineFunction();
7797 bool OptForSize = MF.getFunction()->getAttributes().
7798 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7800 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7802 if (V1IsUndef && V2IsUndef)
7803 return DAG.getUNDEF(VT);
7805 // When we create a shuffle node we put the UNDEF node to second operand,
7806 // but in some cases the first operand may be transformed to UNDEF.
7807 // In this case we should just commute the node.
7809 return CommuteVectorShuffle(SVOp, DAG);
7811 // Vector shuffle lowering takes 3 steps:
7813 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7814 // narrowing and commutation of operands should be handled.
7815 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7817 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7818 // so the shuffle can be broken into other shuffles and the legalizer can
7819 // try the lowering again.
7821 // The general idea is that no vector_shuffle operation should be left to
7822 // be matched during isel, all of them must be converted to a target specific
7825 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7826 // narrowing and commutation of operands should be handled. The actual code
7827 // doesn't include all of those, work in progress...
7828 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7829 if (NewOp.getNode())
7832 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7834 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7835 // unpckh_undef). Only use pshufd if speed is more important than size.
7836 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7837 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7838 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7839 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7841 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7842 V2IsUndef && MayFoldVectorLoad(V1))
7843 return getMOVDDup(Op, dl, V1, DAG);
7845 if (isMOVHLPS_v_undef_Mask(M, VT))
7846 return getMOVHighToLow(Op, dl, DAG);
7848 // Use to match splats
7849 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7850 (VT == MVT::v2f64 || VT == MVT::v2i64))
7851 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7853 if (isPSHUFDMask(M, VT)) {
7854 // The actual implementation will match the mask in the if above and then
7855 // during isel it can match several different instructions, not only pshufd
7856 // as its name says, sad but true, emulate the behavior for now...
7857 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7858 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7860 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7862 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7863 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7865 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7866 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7869 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7873 if (isPALIGNRMask(M, VT, Subtarget))
7874 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7875 getShufflePALIGNRImmediate(SVOp),
7878 // Check if this can be converted into a logical shift.
7879 bool isLeft = false;
7882 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7883 if (isShift && ShVal.hasOneUse()) {
7884 // If the shifted value has multiple uses, it may be cheaper to use
7885 // v_set0 + movlhps or movhlps, etc.
7886 MVT EltVT = VT.getVectorElementType();
7887 ShAmt *= EltVT.getSizeInBits();
7888 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7891 if (isMOVLMask(M, VT)) {
7892 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7893 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7894 if (!isMOVLPMask(M, VT)) {
7895 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7896 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7898 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7899 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7903 // FIXME: fold these into legal mask.
7904 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7905 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7907 if (isMOVHLPSMask(M, VT))
7908 return getMOVHighToLow(Op, dl, DAG);
7910 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7911 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7913 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7914 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7916 if (isMOVLPMask(M, VT))
7917 return getMOVLP(Op, dl, DAG, HasSSE2);
7919 if (ShouldXformToMOVHLPS(M, VT) ||
7920 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7921 return CommuteVectorShuffle(SVOp, DAG);
7924 // No better options. Use a vshldq / vsrldq.
7925 MVT EltVT = VT.getVectorElementType();
7926 ShAmt *= EltVT.getSizeInBits();
7927 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7930 bool Commuted = false;
7931 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7932 // 1,1,1,1 -> v8i16 though.
7933 V1IsSplat = isSplatVector(V1.getNode());
7934 V2IsSplat = isSplatVector(V2.getNode());
7936 // Canonicalize the splat or undef, if present, to be on the RHS.
7937 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7938 CommuteVectorShuffleMask(M, NumElems);
7940 std::swap(V1IsSplat, V2IsSplat);
7944 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7945 // Shuffling low element of v1 into undef, just return v1.
7948 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7949 // the instruction selector will not match, so get a canonical MOVL with
7950 // swapped operands to undo the commute.
7951 return getMOVL(DAG, dl, VT, V2, V1);
7954 if (isUNPCKLMask(M, VT, HasInt256))
7955 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7957 if (isUNPCKHMask(M, VT, HasInt256))
7958 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7961 // Normalize mask so all entries that point to V2 points to its first
7962 // element then try to match unpck{h|l} again. If match, return a
7963 // new vector_shuffle with the corrected mask.p
7964 SmallVector<int, 8> NewMask(M.begin(), M.end());
7965 NormalizeMask(NewMask, NumElems);
7966 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7967 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7968 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7969 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7973 // Commute is back and try unpck* again.
7974 // FIXME: this seems wrong.
7975 CommuteVectorShuffleMask(M, NumElems);
7977 std::swap(V1IsSplat, V2IsSplat);
7979 if (isUNPCKLMask(M, VT, HasInt256))
7980 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7982 if (isUNPCKHMask(M, VT, HasInt256))
7983 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7986 // Normalize the node to match x86 shuffle ops if needed
7987 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7988 return CommuteVectorShuffle(SVOp, DAG);
7990 // The checks below are all present in isShuffleMaskLegal, but they are
7991 // inlined here right now to enable us to directly emit target specific
7992 // nodes, and remove one by one until they don't return Op anymore.
7994 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7995 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7996 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7997 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8000 if (isPSHUFHWMask(M, VT, HasInt256))
8001 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8002 getShufflePSHUFHWImmediate(SVOp),
8005 if (isPSHUFLWMask(M, VT, HasInt256))
8006 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8007 getShufflePSHUFLWImmediate(SVOp),
8010 if (isSHUFPMask(M, VT))
8011 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8012 getShuffleSHUFImmediate(SVOp), DAG);
8014 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8015 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8016 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8017 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8019 //===--------------------------------------------------------------------===//
8020 // Generate target specific nodes for 128 or 256-bit shuffles only
8021 // supported in the AVX instruction set.
8024 // Handle VMOVDDUPY permutations
8025 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8026 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8028 // Handle VPERMILPS/D* permutations
8029 if (isVPERMILPMask(M, VT)) {
8030 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8031 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8032 getShuffleSHUFImmediate(SVOp), DAG);
8033 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8034 getShuffleSHUFImmediate(SVOp), DAG);
8038 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8039 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8040 Idx*(NumElems/2), DAG, dl);
8042 // Handle VPERM2F128/VPERM2I128 permutations
8043 if (isVPERM2X128Mask(M, VT, HasFp256))
8044 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8045 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8048 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8050 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8052 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8053 return getINSERTPS(SVOp, dl, DAG);
8056 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8057 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8059 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8060 VT.is512BitVector()) {
8061 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8062 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8063 SmallVector<SDValue, 16> permclMask;
8064 for (unsigned i = 0; i != NumElems; ++i) {
8065 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8068 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8070 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8071 return DAG.getNode(X86ISD::VPERMV, dl, VT,
8072 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8073 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8074 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8077 //===--------------------------------------------------------------------===//
8078 // Since no target specific shuffle was selected for this generic one,
8079 // lower it into other known shuffles. FIXME: this isn't true yet, but
8080 // this is the plan.
8083 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8084 if (VT == MVT::v8i16) {
8085 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8086 if (NewOp.getNode())
8090 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8091 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8092 if (NewOp.getNode())
8096 if (VT == MVT::v16i8) {
8097 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8098 if (NewOp.getNode())
8102 if (VT == MVT::v32i8) {
8103 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8104 if (NewOp.getNode())
8108 // Handle all 128-bit wide vectors with 4 elements, and match them with
8109 // several different shuffle types.
8110 if (NumElems == 4 && VT.is128BitVector())
8111 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8113 // Handle general 256-bit shuffles
8114 if (VT.is256BitVector())
8115 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8120 // This function assumes its argument is a BUILD_VECTOR of constants or
8121 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8123 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8124 unsigned &MaskValue) {
8126 unsigned NumElems = BuildVector->getNumOperands();
8127 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8128 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8129 unsigned NumElemsInLane = NumElems / NumLanes;
8131 // Blend for v16i16 should be symetric for the both lanes.
8132 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8133 SDValue EltCond = BuildVector->getOperand(i);
8134 SDValue SndLaneEltCond =
8135 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8137 int Lane1Cond = -1, Lane2Cond = -1;
8138 if (isa<ConstantSDNode>(EltCond))
8139 Lane1Cond = !isZero(EltCond);
8140 if (isa<ConstantSDNode>(SndLaneEltCond))
8141 Lane2Cond = !isZero(SndLaneEltCond);
8143 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8144 // Lane1Cond != 0, means we want the first argument.
8145 // Lane1Cond == 0, means we want the second argument.
8146 // The encoding of this argument is 0 for the first argument, 1
8147 // for the second. Therefore, invert the condition.
8148 MaskValue |= !Lane1Cond << i;
8149 else if (Lane1Cond < 0)
8150 MaskValue |= !Lane2Cond << i;
8157 // Try to lower a vselect node into a simple blend instruction.
8158 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8159 SelectionDAG &DAG) {
8160 SDValue Cond = Op.getOperand(0);
8161 SDValue LHS = Op.getOperand(1);
8162 SDValue RHS = Op.getOperand(2);
8164 MVT VT = Op.getSimpleValueType();
8165 MVT EltVT = VT.getVectorElementType();
8166 unsigned NumElems = VT.getVectorNumElements();
8168 // There is no blend with immediate in AVX-512.
8169 if (VT.is512BitVector())
8172 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8174 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8177 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8180 // Check the mask for BLEND and build the value.
8181 unsigned MaskValue = 0;
8182 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8185 // Convert i32 vectors to floating point if it is not AVX2.
8186 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8188 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8189 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8191 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8192 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8195 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8196 DAG.getConstant(MaskValue, MVT::i32));
8197 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8200 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8201 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8202 if (BlendOp.getNode())
8205 // Some types for vselect were previously set to Expand, not Legal or
8206 // Custom. Return an empty SDValue so we fall-through to Expand, after
8207 // the Custom lowering phase.
8208 MVT VT = Op.getSimpleValueType();
8209 switch (VT.SimpleTy) {
8217 // We couldn't create a "Blend with immediate" node.
8218 // This node should still be legal, but we'll have to emit a blendv*
8223 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8224 MVT VT = Op.getSimpleValueType();
8227 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8230 if (VT.getSizeInBits() == 8) {
8231 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8232 Op.getOperand(0), Op.getOperand(1));
8233 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8234 DAG.getValueType(VT));
8235 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8238 if (VT.getSizeInBits() == 16) {
8239 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8240 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8242 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8243 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8244 DAG.getNode(ISD::BITCAST, dl,
8248 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8249 Op.getOperand(0), Op.getOperand(1));
8250 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8251 DAG.getValueType(VT));
8252 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8255 if (VT == MVT::f32) {
8256 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8257 // the result back to FR32 register. It's only worth matching if the
8258 // result has a single use which is a store or a bitcast to i32. And in
8259 // the case of a store, it's not worth it if the index is a constant 0,
8260 // because a MOVSSmr can be used instead, which is smaller and faster.
8261 if (!Op.hasOneUse())
8263 SDNode *User = *Op.getNode()->use_begin();
8264 if ((User->getOpcode() != ISD::STORE ||
8265 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8266 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8267 (User->getOpcode() != ISD::BITCAST ||
8268 User->getValueType(0) != MVT::i32))
8270 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8271 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8274 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8277 if (VT == MVT::i32 || VT == MVT::i64) {
8278 // ExtractPS/pextrq works with constant index.
8279 if (isa<ConstantSDNode>(Op.getOperand(1)))
8285 /// Extract one bit from mask vector, like v16i1 or v8i1.
8286 /// AVX-512 feature.
8288 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8289 SDValue Vec = Op.getOperand(0);
8291 MVT VecVT = Vec.getSimpleValueType();
8292 SDValue Idx = Op.getOperand(1);
8293 MVT EltVT = Op.getSimpleValueType();
8295 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8297 // variable index can't be handled in mask registers,
8298 // extend vector to VR512
8299 if (!isa<ConstantSDNode>(Idx)) {
8300 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8301 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8302 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8303 ExtVT.getVectorElementType(), Ext, Idx);
8304 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8307 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8308 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8309 unsigned MaxSift = rc->getSize()*8 - 1;
8310 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8311 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8312 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8313 DAG.getConstant(MaxSift, MVT::i8));
8314 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8315 DAG.getIntPtrConstant(0));
8319 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8320 SelectionDAG &DAG) const {
8322 SDValue Vec = Op.getOperand(0);
8323 MVT VecVT = Vec.getSimpleValueType();
8324 SDValue Idx = Op.getOperand(1);
8326 if (Op.getSimpleValueType() == MVT::i1)
8327 return ExtractBitFromMaskVector(Op, DAG);
8329 if (!isa<ConstantSDNode>(Idx)) {
8330 if (VecVT.is512BitVector() ||
8331 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8332 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8335 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8336 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8337 MaskEltVT.getSizeInBits());
8339 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8340 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8341 getZeroVector(MaskVT, Subtarget, DAG, dl),
8342 Idx, DAG.getConstant(0, getPointerTy()));
8343 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8344 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8345 Perm, DAG.getConstant(0, getPointerTy()));
8350 // If this is a 256-bit vector result, first extract the 128-bit vector and
8351 // then extract the element from the 128-bit vector.
8352 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8354 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8355 // Get the 128-bit vector.
8356 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8357 MVT EltVT = VecVT.getVectorElementType();
8359 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8361 //if (IdxVal >= NumElems/2)
8362 // IdxVal -= NumElems/2;
8363 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8364 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8365 DAG.getConstant(IdxVal, MVT::i32));
8368 assert(VecVT.is128BitVector() && "Unexpected vector length");
8370 if (Subtarget->hasSSE41()) {
8371 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8376 MVT VT = Op.getSimpleValueType();
8377 // TODO: handle v16i8.
8378 if (VT.getSizeInBits() == 16) {
8379 SDValue Vec = Op.getOperand(0);
8380 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8382 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8383 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8384 DAG.getNode(ISD::BITCAST, dl,
8387 // Transform it so it match pextrw which produces a 32-bit result.
8388 MVT EltVT = MVT::i32;
8389 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8390 Op.getOperand(0), Op.getOperand(1));
8391 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8392 DAG.getValueType(VT));
8393 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8396 if (VT.getSizeInBits() == 32) {
8397 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8401 // SHUFPS the element to the lowest double word, then movss.
8402 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8403 MVT VVT = Op.getOperand(0).getSimpleValueType();
8404 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8405 DAG.getUNDEF(VVT), Mask);
8406 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8407 DAG.getIntPtrConstant(0));
8410 if (VT.getSizeInBits() == 64) {
8411 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8412 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8413 // to match extract_elt for f64.
8414 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8418 // UNPCKHPD the element to the lowest double word, then movsd.
8419 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8420 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8421 int Mask[2] = { 1, -1 };
8422 MVT VVT = Op.getOperand(0).getSimpleValueType();
8423 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8424 DAG.getUNDEF(VVT), Mask);
8425 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8426 DAG.getIntPtrConstant(0));
8432 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8433 MVT VT = Op.getSimpleValueType();
8434 MVT EltVT = VT.getVectorElementType();
8437 SDValue N0 = Op.getOperand(0);
8438 SDValue N1 = Op.getOperand(1);
8439 SDValue N2 = Op.getOperand(2);
8441 if (!VT.is128BitVector())
8444 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8445 isa<ConstantSDNode>(N2)) {
8447 if (VT == MVT::v8i16)
8448 Opc = X86ISD::PINSRW;
8449 else if (VT == MVT::v16i8)
8450 Opc = X86ISD::PINSRB;
8452 Opc = X86ISD::PINSRB;
8454 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8456 if (N1.getValueType() != MVT::i32)
8457 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8458 if (N2.getValueType() != MVT::i32)
8459 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8460 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8463 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8464 // Bits [7:6] of the constant are the source select. This will always be
8465 // zero here. The DAG Combiner may combine an extract_elt index into these
8466 // bits. For example (insert (extract, 3), 2) could be matched by putting
8467 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8468 // Bits [5:4] of the constant are the destination select. This is the
8469 // value of the incoming immediate.
8470 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8471 // combine either bitwise AND or insert of float 0.0 to set these bits.
8472 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8473 // Create this as a scalar to vector..
8474 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8475 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8478 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8479 // PINSR* works with constant index.
8485 /// Insert one bit to mask vector, like v16i1 or v8i1.
8486 /// AVX-512 feature.
8488 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8490 SDValue Vec = Op.getOperand(0);
8491 SDValue Elt = Op.getOperand(1);
8492 SDValue Idx = Op.getOperand(2);
8493 MVT VecVT = Vec.getSimpleValueType();
8495 if (!isa<ConstantSDNode>(Idx)) {
8496 // Non constant index. Extend source and destination,
8497 // insert element and then truncate the result.
8498 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8499 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8500 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8501 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8502 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8503 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8506 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8507 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8508 if (Vec.getOpcode() == ISD::UNDEF)
8509 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8510 DAG.getConstant(IdxVal, MVT::i8));
8511 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8512 unsigned MaxSift = rc->getSize()*8 - 1;
8513 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8514 DAG.getConstant(MaxSift, MVT::i8));
8515 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8516 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8517 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8520 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8521 MVT VT = Op.getSimpleValueType();
8522 MVT EltVT = VT.getVectorElementType();
8524 if (EltVT == MVT::i1)
8525 return InsertBitToMaskVector(Op, DAG);
8528 SDValue N0 = Op.getOperand(0);
8529 SDValue N1 = Op.getOperand(1);
8530 SDValue N2 = Op.getOperand(2);
8532 // If this is a 256-bit vector result, first extract the 128-bit vector,
8533 // insert the element into the extracted half and then place it back.
8534 if (VT.is256BitVector() || VT.is512BitVector()) {
8535 if (!isa<ConstantSDNode>(N2))
8538 // Get the desired 128-bit vector half.
8539 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8540 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8542 // Insert the element into the desired half.
8543 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8544 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8546 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8547 DAG.getConstant(IdxIn128, MVT::i32));
8549 // Insert the changed part back to the 256-bit vector
8550 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8553 if (Subtarget->hasSSE41())
8554 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8556 if (EltVT == MVT::i8)
8559 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8560 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8561 // as its second argument.
8562 if (N1.getValueType() != MVT::i32)
8563 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8564 if (N2.getValueType() != MVT::i32)
8565 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8566 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8571 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8573 MVT OpVT = Op.getSimpleValueType();
8575 // If this is a 256-bit vector result, first insert into a 128-bit
8576 // vector and then insert into the 256-bit vector.
8577 if (!OpVT.is128BitVector()) {
8578 // Insert into a 128-bit vector.
8579 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8580 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8581 OpVT.getVectorNumElements() / SizeFactor);
8583 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8585 // Insert the 128-bit vector.
8586 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8589 if (OpVT == MVT::v1i64 &&
8590 Op.getOperand(0).getValueType() == MVT::i64)
8591 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8593 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8594 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8595 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8596 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8599 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8600 // a simple subregister reference or explicit instructions to grab
8601 // upper bits of a vector.
8602 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8603 SelectionDAG &DAG) {
8605 SDValue In = Op.getOperand(0);
8606 SDValue Idx = Op.getOperand(1);
8607 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8608 MVT ResVT = Op.getSimpleValueType();
8609 MVT InVT = In.getSimpleValueType();
8611 if (Subtarget->hasFp256()) {
8612 if (ResVT.is128BitVector() &&
8613 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8614 isa<ConstantSDNode>(Idx)) {
8615 return Extract128BitVector(In, IdxVal, DAG, dl);
8617 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8618 isa<ConstantSDNode>(Idx)) {
8619 return Extract256BitVector(In, IdxVal, DAG, dl);
8625 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8626 // simple superregister reference or explicit instructions to insert
8627 // the upper bits of a vector.
8628 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8629 SelectionDAG &DAG) {
8630 if (Subtarget->hasFp256()) {
8631 SDLoc dl(Op.getNode());
8632 SDValue Vec = Op.getNode()->getOperand(0);
8633 SDValue SubVec = Op.getNode()->getOperand(1);
8634 SDValue Idx = Op.getNode()->getOperand(2);
8636 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8637 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8638 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8639 isa<ConstantSDNode>(Idx)) {
8640 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8641 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8644 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8645 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8646 isa<ConstantSDNode>(Idx)) {
8647 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8648 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8654 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8655 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8656 // one of the above mentioned nodes. It has to be wrapped because otherwise
8657 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8658 // be used to form addressing mode. These wrapped nodes will be selected
8661 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8662 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8664 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8666 unsigned char OpFlag = 0;
8667 unsigned WrapperKind = X86ISD::Wrapper;
8668 CodeModel::Model M = DAG.getTarget().getCodeModel();
8670 if (Subtarget->isPICStyleRIPRel() &&
8671 (M == CodeModel::Small || M == CodeModel::Kernel))
8672 WrapperKind = X86ISD::WrapperRIP;
8673 else if (Subtarget->isPICStyleGOT())
8674 OpFlag = X86II::MO_GOTOFF;
8675 else if (Subtarget->isPICStyleStubPIC())
8676 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8678 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8680 CP->getOffset(), OpFlag);
8682 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8683 // With PIC, the address is actually $g + Offset.
8685 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8686 DAG.getNode(X86ISD::GlobalBaseReg,
8687 SDLoc(), getPointerTy()),
8694 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8695 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8697 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8699 unsigned char OpFlag = 0;
8700 unsigned WrapperKind = X86ISD::Wrapper;
8701 CodeModel::Model M = DAG.getTarget().getCodeModel();
8703 if (Subtarget->isPICStyleRIPRel() &&
8704 (M == CodeModel::Small || M == CodeModel::Kernel))
8705 WrapperKind = X86ISD::WrapperRIP;
8706 else if (Subtarget->isPICStyleGOT())
8707 OpFlag = X86II::MO_GOTOFF;
8708 else if (Subtarget->isPICStyleStubPIC())
8709 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8711 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8714 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8716 // With PIC, the address is actually $g + Offset.
8718 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8719 DAG.getNode(X86ISD::GlobalBaseReg,
8720 SDLoc(), getPointerTy()),
8727 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8728 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8730 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8732 unsigned char OpFlag = 0;
8733 unsigned WrapperKind = X86ISD::Wrapper;
8734 CodeModel::Model M = DAG.getTarget().getCodeModel();
8736 if (Subtarget->isPICStyleRIPRel() &&
8737 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8738 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8739 OpFlag = X86II::MO_GOTPCREL;
8740 WrapperKind = X86ISD::WrapperRIP;
8741 } else if (Subtarget->isPICStyleGOT()) {
8742 OpFlag = X86II::MO_GOT;
8743 } else if (Subtarget->isPICStyleStubPIC()) {
8744 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8745 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8746 OpFlag = X86II::MO_DARWIN_NONLAZY;
8749 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8752 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8754 // With PIC, the address is actually $g + Offset.
8755 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
8756 !Subtarget->is64Bit()) {
8757 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8758 DAG.getNode(X86ISD::GlobalBaseReg,
8759 SDLoc(), getPointerTy()),
8763 // For symbols that require a load from a stub to get the address, emit the
8765 if (isGlobalStubReference(OpFlag))
8766 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8767 MachinePointerInfo::getGOT(), false, false, false, 0);
8773 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8774 // Create the TargetBlockAddressAddress node.
8775 unsigned char OpFlags =
8776 Subtarget->ClassifyBlockAddressReference();
8777 CodeModel::Model M = DAG.getTarget().getCodeModel();
8778 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8779 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8781 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8784 if (Subtarget->isPICStyleRIPRel() &&
8785 (M == CodeModel::Small || M == CodeModel::Kernel))
8786 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8788 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8790 // With PIC, the address is actually $g + Offset.
8791 if (isGlobalRelativeToPICBase(OpFlags)) {
8792 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8793 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8801 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8802 int64_t Offset, SelectionDAG &DAG) const {
8803 // Create the TargetGlobalAddress node, folding in the constant
8804 // offset if it is legal.
8805 unsigned char OpFlags =
8806 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
8807 CodeModel::Model M = DAG.getTarget().getCodeModel();
8809 if (OpFlags == X86II::MO_NO_FLAG &&
8810 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8811 // A direct static reference to a global.
8812 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8815 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8818 if (Subtarget->isPICStyleRIPRel() &&
8819 (M == CodeModel::Small || M == CodeModel::Kernel))
8820 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8822 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8824 // With PIC, the address is actually $g + Offset.
8825 if (isGlobalRelativeToPICBase(OpFlags)) {
8826 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8827 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8831 // For globals that require a load from a stub to get the address, emit the
8833 if (isGlobalStubReference(OpFlags))
8834 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8835 MachinePointerInfo::getGOT(), false, false, false, 0);
8837 // If there was a non-zero offset that we didn't fold, create an explicit
8840 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8841 DAG.getConstant(Offset, getPointerTy()));
8847 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8848 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8849 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8850 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8854 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8855 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8856 unsigned char OperandFlags, bool LocalDynamic = false) {
8857 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8858 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8860 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8861 GA->getValueType(0),
8865 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8869 SDValue Ops[] = { Chain, TGA, *InFlag };
8870 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8872 SDValue Ops[] = { Chain, TGA };
8873 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8876 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8877 MFI->setAdjustsStack(true);
8879 SDValue Flag = Chain.getValue(1);
8880 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8883 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8885 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8888 SDLoc dl(GA); // ? function entry point might be better
8889 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8890 DAG.getNode(X86ISD::GlobalBaseReg,
8891 SDLoc(), PtrVT), InFlag);
8892 InFlag = Chain.getValue(1);
8894 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8897 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8899 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8901 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8902 X86::RAX, X86II::MO_TLSGD);
8905 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8911 // Get the start address of the TLS block for this module.
8912 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8913 .getInfo<X86MachineFunctionInfo>();
8914 MFI->incNumLocalDynamicTLSAccesses();
8918 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8919 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8922 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8923 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8924 InFlag = Chain.getValue(1);
8925 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8926 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8929 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8933 unsigned char OperandFlags = X86II::MO_DTPOFF;
8934 unsigned WrapperKind = X86ISD::Wrapper;
8935 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8936 GA->getValueType(0),
8937 GA->getOffset(), OperandFlags);
8938 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8940 // Add x@dtpoff with the base.
8941 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8944 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8945 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8946 const EVT PtrVT, TLSModel::Model model,
8947 bool is64Bit, bool isPIC) {
8950 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8951 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8952 is64Bit ? 257 : 256));
8954 SDValue ThreadPointer =
8955 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8956 MachinePointerInfo(Ptr), false, false, false, 0);
8958 unsigned char OperandFlags = 0;
8959 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8961 unsigned WrapperKind = X86ISD::Wrapper;
8962 if (model == TLSModel::LocalExec) {
8963 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8964 } else if (model == TLSModel::InitialExec) {
8966 OperandFlags = X86II::MO_GOTTPOFF;
8967 WrapperKind = X86ISD::WrapperRIP;
8969 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8972 llvm_unreachable("Unexpected model");
8975 // emit "addl x@ntpoff,%eax" (local exec)
8976 // or "addl x@indntpoff,%eax" (initial exec)
8977 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8979 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8980 GA->getOffset(), OperandFlags);
8981 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8983 if (model == TLSModel::InitialExec) {
8984 if (isPIC && !is64Bit) {
8985 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8986 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8990 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8991 MachinePointerInfo::getGOT(), false, false, false, 0);
8994 // The address of the thread local variable is the add of the thread
8995 // pointer with the offset of the variable.
8996 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9000 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9002 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9003 const GlobalValue *GV = GA->getGlobal();
9005 if (Subtarget->isTargetELF()) {
9006 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9009 case TLSModel::GeneralDynamic:
9010 if (Subtarget->is64Bit())
9011 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9012 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9013 case TLSModel::LocalDynamic:
9014 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9015 Subtarget->is64Bit());
9016 case TLSModel::InitialExec:
9017 case TLSModel::LocalExec:
9018 return LowerToTLSExecModel(
9019 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9020 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9022 llvm_unreachable("Unknown TLS model.");
9025 if (Subtarget->isTargetDarwin()) {
9026 // Darwin only has one model of TLS. Lower to that.
9027 unsigned char OpFlag = 0;
9028 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9029 X86ISD::WrapperRIP : X86ISD::Wrapper;
9031 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9033 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9034 !Subtarget->is64Bit();
9036 OpFlag = X86II::MO_TLVP_PIC_BASE;
9038 OpFlag = X86II::MO_TLVP;
9040 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9041 GA->getValueType(0),
9042 GA->getOffset(), OpFlag);
9043 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9045 // With PIC32, the address is actually $g + Offset.
9047 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9048 DAG.getNode(X86ISD::GlobalBaseReg,
9049 SDLoc(), getPointerTy()),
9052 // Lowering the machine isd will make sure everything is in the right
9054 SDValue Chain = DAG.getEntryNode();
9055 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9056 SDValue Args[] = { Chain, Offset };
9057 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9059 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9060 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9061 MFI->setAdjustsStack(true);
9063 // And our return value (tls address) is in the standard call return value
9065 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9066 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9070 if (Subtarget->isTargetKnownWindowsMSVC() ||
9071 Subtarget->isTargetWindowsGNU()) {
9072 // Just use the implicit TLS architecture
9073 // Need to generate someting similar to:
9074 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9076 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
9077 // mov rcx, qword [rdx+rcx*8]
9078 // mov eax, .tls$:tlsvar
9079 // [rax+rcx] contains the address
9080 // Windows 64bit: gs:0x58
9081 // Windows 32bit: fs:__tls_array
9084 SDValue Chain = DAG.getEntryNode();
9086 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9087 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9088 // use its literal value of 0x2C.
9089 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9090 ? Type::getInt8PtrTy(*DAG.getContext(),
9092 : Type::getInt32PtrTy(*DAG.getContext(),
9096 Subtarget->is64Bit()
9097 ? DAG.getIntPtrConstant(0x58)
9098 : (Subtarget->isTargetWindowsGNU()
9099 ? DAG.getIntPtrConstant(0x2C)
9100 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9102 SDValue ThreadPointer =
9103 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9104 MachinePointerInfo(Ptr), false, false, false, 0);
9106 // Load the _tls_index variable
9107 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9108 if (Subtarget->is64Bit())
9109 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9110 IDX, MachinePointerInfo(), MVT::i32,
9113 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9114 false, false, false, 0);
9116 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9118 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9120 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9121 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9122 false, false, false, 0);
9124 // Get the offset of start of .tls section
9125 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9126 GA->getValueType(0),
9127 GA->getOffset(), X86II::MO_SECREL);
9128 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9130 // The address of the thread local variable is the add of the thread
9131 // pointer with the offset of the variable.
9132 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9135 llvm_unreachable("TLS not implemented for this target.");
9138 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9139 /// and take a 2 x i32 value to shift plus a shift amount.
9140 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9141 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9142 MVT VT = Op.getSimpleValueType();
9143 unsigned VTBits = VT.getSizeInBits();
9145 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9146 SDValue ShOpLo = Op.getOperand(0);
9147 SDValue ShOpHi = Op.getOperand(1);
9148 SDValue ShAmt = Op.getOperand(2);
9149 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9150 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9152 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9153 DAG.getConstant(VTBits - 1, MVT::i8));
9154 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9155 DAG.getConstant(VTBits - 1, MVT::i8))
9156 : DAG.getConstant(0, VT);
9159 if (Op.getOpcode() == ISD::SHL_PARTS) {
9160 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9161 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9163 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9164 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9167 // If the shift amount is larger or equal than the width of a part we can't
9168 // rely on the results of shld/shrd. Insert a test and select the appropriate
9169 // values for large shift amounts.
9170 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9171 DAG.getConstant(VTBits, MVT::i8));
9172 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9173 AndNode, DAG.getConstant(0, MVT::i8));
9176 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9177 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9178 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9180 if (Op.getOpcode() == ISD::SHL_PARTS) {
9181 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9182 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9184 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9185 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9188 SDValue Ops[2] = { Lo, Hi };
9189 return DAG.getMergeValues(Ops, dl);
9192 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9193 SelectionDAG &DAG) const {
9194 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9196 if (SrcVT.isVector())
9199 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9200 "Unknown SINT_TO_FP to lower!");
9202 // These are really Legal; return the operand so the caller accepts it as
9204 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9206 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9207 Subtarget->is64Bit()) {
9212 unsigned Size = SrcVT.getSizeInBits()/8;
9213 MachineFunction &MF = DAG.getMachineFunction();
9214 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9215 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9216 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9218 MachinePointerInfo::getFixedStack(SSFI),
9220 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9223 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9225 SelectionDAG &DAG) const {
9229 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9231 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9233 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9235 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9237 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9238 MachineMemOperand *MMO;
9240 int SSFI = FI->getIndex();
9242 DAG.getMachineFunction()
9243 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9244 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9246 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9247 StackSlot = StackSlot.getOperand(1);
9249 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9250 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9252 Tys, Ops, SrcVT, MMO);
9255 Chain = Result.getValue(1);
9256 SDValue InFlag = Result.getValue(2);
9258 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9259 // shouldn't be necessary except that RFP cannot be live across
9260 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9261 MachineFunction &MF = DAG.getMachineFunction();
9262 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9263 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9264 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9265 Tys = DAG.getVTList(MVT::Other);
9267 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9269 MachineMemOperand *MMO =
9270 DAG.getMachineFunction()
9271 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9272 MachineMemOperand::MOStore, SSFISize, SSFISize);
9274 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9275 Ops, Op.getValueType(), MMO);
9276 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9277 MachinePointerInfo::getFixedStack(SSFI),
9278 false, false, false, 0);
9284 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9285 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9286 SelectionDAG &DAG) const {
9287 // This algorithm is not obvious. Here it is what we're trying to output:
9290 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9291 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9295 pshufd $0x4e, %xmm0, %xmm1
9301 LLVMContext *Context = DAG.getContext();
9303 // Build some magic constants.
9304 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9305 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9306 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9308 SmallVector<Constant*,2> CV1;
9310 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9311 APInt(64, 0x4330000000000000ULL))));
9313 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9314 APInt(64, 0x4530000000000000ULL))));
9315 Constant *C1 = ConstantVector::get(CV1);
9316 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9318 // Load the 64-bit value into an XMM register.
9319 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9321 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9322 MachinePointerInfo::getConstantPool(),
9323 false, false, false, 16);
9324 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9325 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9328 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9329 MachinePointerInfo::getConstantPool(),
9330 false, false, false, 16);
9331 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9332 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9335 if (Subtarget->hasSSE3()) {
9336 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9337 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9339 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9340 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9342 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9343 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9347 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9348 DAG.getIntPtrConstant(0));
9351 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9352 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9353 SelectionDAG &DAG) const {
9355 // FP constant to bias correct the final result.
9356 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9359 // Load the 32-bit value into an XMM register.
9360 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9363 // Zero out the upper parts of the register.
9364 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9366 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9367 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9368 DAG.getIntPtrConstant(0));
9370 // Or the load with the bias.
9371 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9372 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9373 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9375 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9376 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9377 MVT::v2f64, Bias)));
9378 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9379 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9380 DAG.getIntPtrConstant(0));
9382 // Subtract the bias.
9383 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9385 // Handle final rounding.
9386 EVT DestVT = Op.getValueType();
9388 if (DestVT.bitsLT(MVT::f64))
9389 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9390 DAG.getIntPtrConstant(0));
9391 if (DestVT.bitsGT(MVT::f64))
9392 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9394 // Handle final rounding.
9398 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9399 SelectionDAG &DAG) const {
9400 SDValue N0 = Op.getOperand(0);
9401 MVT SVT = N0.getSimpleValueType();
9404 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9405 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9406 "Custom UINT_TO_FP is not supported!");
9408 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9409 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9410 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9413 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9414 SelectionDAG &DAG) const {
9415 SDValue N0 = Op.getOperand(0);
9418 if (Op.getValueType().isVector())
9419 return lowerUINT_TO_FP_vec(Op, DAG);
9421 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9422 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9423 // the optimization here.
9424 if (DAG.SignBitIsZero(N0))
9425 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9427 MVT SrcVT = N0.getSimpleValueType();
9428 MVT DstVT = Op.getSimpleValueType();
9429 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9430 return LowerUINT_TO_FP_i64(Op, DAG);
9431 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9432 return LowerUINT_TO_FP_i32(Op, DAG);
9433 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9436 // Make a 64-bit buffer, and use it to build an FILD.
9437 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9438 if (SrcVT == MVT::i32) {
9439 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9440 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9441 getPointerTy(), StackSlot, WordOff);
9442 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9443 StackSlot, MachinePointerInfo(),
9445 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9446 OffsetSlot, MachinePointerInfo(),
9448 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9452 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9453 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9454 StackSlot, MachinePointerInfo(),
9456 // For i64 source, we need to add the appropriate power of 2 if the input
9457 // was negative. This is the same as the optimization in
9458 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9459 // we must be careful to do the computation in x87 extended precision, not
9460 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9461 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9462 MachineMemOperand *MMO =
9463 DAG.getMachineFunction()
9464 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9465 MachineMemOperand::MOLoad, 8, 8);
9467 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9468 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9469 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9472 APInt FF(32, 0x5F800000ULL);
9474 // Check whether the sign bit is set.
9475 SDValue SignSet = DAG.getSetCC(dl,
9476 getSetCCResultType(*DAG.getContext(), MVT::i64),
9477 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9480 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9481 SDValue FudgePtr = DAG.getConstantPool(
9482 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9485 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9486 SDValue Zero = DAG.getIntPtrConstant(0);
9487 SDValue Four = DAG.getIntPtrConstant(4);
9488 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9490 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9492 // Load the value out, extending it from f32 to f80.
9493 // FIXME: Avoid the extend by constructing the right constant pool?
9494 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9495 FudgePtr, MachinePointerInfo::getConstantPool(),
9496 MVT::f32, false, false, 4);
9497 // Extend everything to 80 bits to force it to be done on x87.
9498 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9499 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9502 std::pair<SDValue,SDValue>
9503 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9504 bool IsSigned, bool IsReplace) const {
9507 EVT DstTy = Op.getValueType();
9509 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9510 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9514 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9515 DstTy.getSimpleVT() >= MVT::i16 &&
9516 "Unknown FP_TO_INT to lower!");
9518 // These are really Legal.
9519 if (DstTy == MVT::i32 &&
9520 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9521 return std::make_pair(SDValue(), SDValue());
9522 if (Subtarget->is64Bit() &&
9523 DstTy == MVT::i64 &&
9524 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9525 return std::make_pair(SDValue(), SDValue());
9527 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9528 // stack slot, or into the FTOL runtime function.
9529 MachineFunction &MF = DAG.getMachineFunction();
9530 unsigned MemSize = DstTy.getSizeInBits()/8;
9531 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9532 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9535 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9536 Opc = X86ISD::WIN_FTOL;
9538 switch (DstTy.getSimpleVT().SimpleTy) {
9539 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9540 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9541 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9542 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9545 SDValue Chain = DAG.getEntryNode();
9546 SDValue Value = Op.getOperand(0);
9547 EVT TheVT = Op.getOperand(0).getValueType();
9548 // FIXME This causes a redundant load/store if the SSE-class value is already
9549 // in memory, such as if it is on the callstack.
9550 if (isScalarFPTypeInSSEReg(TheVT)) {
9551 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9552 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9553 MachinePointerInfo::getFixedStack(SSFI),
9555 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9557 Chain, StackSlot, DAG.getValueType(TheVT)
9560 MachineMemOperand *MMO =
9561 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9562 MachineMemOperand::MOLoad, MemSize, MemSize);
9563 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9564 Chain = Value.getValue(1);
9565 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9566 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9569 MachineMemOperand *MMO =
9570 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9571 MachineMemOperand::MOStore, MemSize, MemSize);
9573 if (Opc != X86ISD::WIN_FTOL) {
9574 // Build the FP_TO_INT*_IN_MEM
9575 SDValue Ops[] = { Chain, Value, StackSlot };
9576 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9578 return std::make_pair(FIST, StackSlot);
9580 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9581 DAG.getVTList(MVT::Other, MVT::Glue),
9583 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9584 MVT::i32, ftol.getValue(1));
9585 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9586 MVT::i32, eax.getValue(2));
9587 SDValue Ops[] = { eax, edx };
9588 SDValue pair = IsReplace
9589 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9590 : DAG.getMergeValues(Ops, DL);
9591 return std::make_pair(pair, SDValue());
9595 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9596 const X86Subtarget *Subtarget) {
9597 MVT VT = Op->getSimpleValueType(0);
9598 SDValue In = Op->getOperand(0);
9599 MVT InVT = In.getSimpleValueType();
9602 // Optimize vectors in AVX mode:
9605 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9606 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9607 // Concat upper and lower parts.
9610 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9611 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9612 // Concat upper and lower parts.
9615 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9616 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9617 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9620 if (Subtarget->hasInt256())
9621 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9623 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9624 SDValue Undef = DAG.getUNDEF(InVT);
9625 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9626 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9627 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9629 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9630 VT.getVectorNumElements()/2);
9632 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9633 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9635 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9638 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9639 SelectionDAG &DAG) {
9640 MVT VT = Op->getSimpleValueType(0);
9641 SDValue In = Op->getOperand(0);
9642 MVT InVT = In.getSimpleValueType();
9644 unsigned int NumElts = VT.getVectorNumElements();
9645 if (NumElts != 8 && NumElts != 16)
9648 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9649 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9651 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9652 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9653 // Now we have only mask extension
9654 assert(InVT.getVectorElementType() == MVT::i1);
9655 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9656 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9657 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9658 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9659 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9660 MachinePointerInfo::getConstantPool(),
9661 false, false, false, Alignment);
9663 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9664 if (VT.is512BitVector())
9666 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9669 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9670 SelectionDAG &DAG) {
9671 if (Subtarget->hasFp256()) {
9672 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9680 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9681 SelectionDAG &DAG) {
9683 MVT VT = Op.getSimpleValueType();
9684 SDValue In = Op.getOperand(0);
9685 MVT SVT = In.getSimpleValueType();
9687 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9688 return LowerZERO_EXTEND_AVX512(Op, DAG);
9690 if (Subtarget->hasFp256()) {
9691 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9696 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9697 VT.getVectorNumElements() != SVT.getVectorNumElements());
9701 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9703 MVT VT = Op.getSimpleValueType();
9704 SDValue In = Op.getOperand(0);
9705 MVT InVT = In.getSimpleValueType();
9707 if (VT == MVT::i1) {
9708 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9709 "Invalid scalar TRUNCATE operation");
9710 if (InVT == MVT::i32)
9712 if (InVT.getSizeInBits() == 64)
9713 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9714 else if (InVT.getSizeInBits() < 32)
9715 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9716 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9718 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9719 "Invalid TRUNCATE operation");
9721 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9722 if (VT.getVectorElementType().getSizeInBits() >=8)
9723 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9725 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9726 unsigned NumElts = InVT.getVectorNumElements();
9727 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9728 if (InVT.getSizeInBits() < 512) {
9729 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9730 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9734 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9735 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9736 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9737 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9738 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9739 MachinePointerInfo::getConstantPool(),
9740 false, false, false, Alignment);
9741 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9742 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9743 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9746 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9747 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9748 if (Subtarget->hasInt256()) {
9749 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9750 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9751 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9753 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9754 DAG.getIntPtrConstant(0));
9757 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9758 DAG.getIntPtrConstant(0));
9759 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9760 DAG.getIntPtrConstant(2));
9761 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9762 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9763 static const int ShufMask[] = {0, 2, 4, 6};
9764 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9767 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9768 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9769 if (Subtarget->hasInt256()) {
9770 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9772 SmallVector<SDValue,32> pshufbMask;
9773 for (unsigned i = 0; i < 2; ++i) {
9774 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9775 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9776 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9777 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9778 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9779 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9780 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9781 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9782 for (unsigned j = 0; j < 8; ++j)
9783 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9785 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9786 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9787 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9789 static const int ShufMask[] = {0, 2, -1, -1};
9790 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9792 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9793 DAG.getIntPtrConstant(0));
9794 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9797 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9798 DAG.getIntPtrConstant(0));
9800 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9801 DAG.getIntPtrConstant(4));
9803 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9804 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9807 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9808 -1, -1, -1, -1, -1, -1, -1, -1};
9810 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9811 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9812 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9814 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9815 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9817 // The MOVLHPS Mask:
9818 static const int ShufMask2[] = {0, 1, 4, 5};
9819 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9820 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9823 // Handle truncation of V256 to V128 using shuffles.
9824 if (!VT.is128BitVector() || !InVT.is256BitVector())
9827 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9829 unsigned NumElems = VT.getVectorNumElements();
9830 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9832 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9833 // Prepare truncation shuffle mask
9834 for (unsigned i = 0; i != NumElems; ++i)
9836 SDValue V = DAG.getVectorShuffle(NVT, DL,
9837 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9838 DAG.getUNDEF(NVT), &MaskVec[0]);
9839 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9840 DAG.getIntPtrConstant(0));
9843 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9844 SelectionDAG &DAG) const {
9845 assert(!Op.getSimpleValueType().isVector());
9847 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9848 /*IsSigned=*/ true, /*IsReplace=*/ false);
9849 SDValue FIST = Vals.first, StackSlot = Vals.second;
9850 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9851 if (!FIST.getNode()) return Op;
9853 if (StackSlot.getNode())
9855 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9856 FIST, StackSlot, MachinePointerInfo(),
9857 false, false, false, 0);
9859 // The node is the result.
9863 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9864 SelectionDAG &DAG) const {
9865 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9866 /*IsSigned=*/ false, /*IsReplace=*/ false);
9867 SDValue FIST = Vals.first, StackSlot = Vals.second;
9868 assert(FIST.getNode() && "Unexpected failure");
9870 if (StackSlot.getNode())
9872 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9873 FIST, StackSlot, MachinePointerInfo(),
9874 false, false, false, 0);
9876 // The node is the result.
9880 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9882 MVT VT = Op.getSimpleValueType();
9883 SDValue In = Op.getOperand(0);
9884 MVT SVT = In.getSimpleValueType();
9886 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9888 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9889 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9890 In, DAG.getUNDEF(SVT)));
9893 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9894 LLVMContext *Context = DAG.getContext();
9896 MVT VT = Op.getSimpleValueType();
9898 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9899 if (VT.isVector()) {
9900 EltVT = VT.getVectorElementType();
9901 NumElts = VT.getVectorNumElements();
9904 if (EltVT == MVT::f64)
9905 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9906 APInt(64, ~(1ULL << 63))));
9908 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9909 APInt(32, ~(1U << 31))));
9910 C = ConstantVector::getSplat(NumElts, C);
9911 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9912 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9913 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9914 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9915 MachinePointerInfo::getConstantPool(),
9916 false, false, false, Alignment);
9917 if (VT.isVector()) {
9918 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9919 return DAG.getNode(ISD::BITCAST, dl, VT,
9920 DAG.getNode(ISD::AND, dl, ANDVT,
9921 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9923 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9925 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9928 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9929 LLVMContext *Context = DAG.getContext();
9931 MVT VT = Op.getSimpleValueType();
9933 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9934 if (VT.isVector()) {
9935 EltVT = VT.getVectorElementType();
9936 NumElts = VT.getVectorNumElements();
9939 if (EltVT == MVT::f64)
9940 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9941 APInt(64, 1ULL << 63)));
9943 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9944 APInt(32, 1U << 31)));
9945 C = ConstantVector::getSplat(NumElts, C);
9946 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9947 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9948 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9949 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9950 MachinePointerInfo::getConstantPool(),
9951 false, false, false, Alignment);
9952 if (VT.isVector()) {
9953 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9954 return DAG.getNode(ISD::BITCAST, dl, VT,
9955 DAG.getNode(ISD::XOR, dl, XORVT,
9956 DAG.getNode(ISD::BITCAST, dl, XORVT,
9958 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9961 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9964 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9965 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9966 LLVMContext *Context = DAG.getContext();
9967 SDValue Op0 = Op.getOperand(0);
9968 SDValue Op1 = Op.getOperand(1);
9970 MVT VT = Op.getSimpleValueType();
9971 MVT SrcVT = Op1.getSimpleValueType();
9973 // If second operand is smaller, extend it first.
9974 if (SrcVT.bitsLT(VT)) {
9975 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9978 // And if it is bigger, shrink it first.
9979 if (SrcVT.bitsGT(VT)) {
9980 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9984 // At this point the operands and the result should have the same
9985 // type, and that won't be f80 since that is not custom lowered.
9987 // First get the sign bit of second operand.
9988 SmallVector<Constant*,4> CV;
9989 if (SrcVT == MVT::f64) {
9990 const fltSemantics &Sem = APFloat::IEEEdouble;
9991 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9992 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9994 const fltSemantics &Sem = APFloat::IEEEsingle;
9995 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9996 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9997 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9998 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10000 Constant *C = ConstantVector::get(CV);
10001 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10002 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10003 MachinePointerInfo::getConstantPool(),
10004 false, false, false, 16);
10005 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10007 // Shift sign bit right or left if the two operands have different types.
10008 if (SrcVT.bitsGT(VT)) {
10009 // Op0 is MVT::f32, Op1 is MVT::f64.
10010 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10011 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10012 DAG.getConstant(32, MVT::i32));
10013 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10014 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10015 DAG.getIntPtrConstant(0));
10018 // Clear first operand sign bit.
10020 if (VT == MVT::f64) {
10021 const fltSemantics &Sem = APFloat::IEEEdouble;
10022 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10023 APInt(64, ~(1ULL << 63)))));
10024 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10026 const fltSemantics &Sem = APFloat::IEEEsingle;
10027 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10028 APInt(32, ~(1U << 31)))));
10029 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10030 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10031 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10033 C = ConstantVector::get(CV);
10034 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10035 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10036 MachinePointerInfo::getConstantPool(),
10037 false, false, false, 16);
10038 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10040 // Or the value with the sign bit.
10041 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10044 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10045 SDValue N0 = Op.getOperand(0);
10047 MVT VT = Op.getSimpleValueType();
10049 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10050 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10051 DAG.getConstant(1, VT));
10052 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10055 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10057 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10058 SelectionDAG &DAG) {
10059 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10061 if (!Subtarget->hasSSE41())
10064 if (!Op->hasOneUse())
10067 SDNode *N = Op.getNode();
10070 SmallVector<SDValue, 8> Opnds;
10071 DenseMap<SDValue, unsigned> VecInMap;
10072 SmallVector<SDValue, 8> VecIns;
10073 EVT VT = MVT::Other;
10075 // Recognize a special case where a vector is casted into wide integer to
10077 Opnds.push_back(N->getOperand(0));
10078 Opnds.push_back(N->getOperand(1));
10080 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10081 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10082 // BFS traverse all OR'd operands.
10083 if (I->getOpcode() == ISD::OR) {
10084 Opnds.push_back(I->getOperand(0));
10085 Opnds.push_back(I->getOperand(1));
10086 // Re-evaluate the number of nodes to be traversed.
10087 e += 2; // 2 more nodes (LHS and RHS) are pushed.
10091 // Quit if a non-EXTRACT_VECTOR_ELT
10092 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10095 // Quit if without a constant index.
10096 SDValue Idx = I->getOperand(1);
10097 if (!isa<ConstantSDNode>(Idx))
10100 SDValue ExtractedFromVec = I->getOperand(0);
10101 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10102 if (M == VecInMap.end()) {
10103 VT = ExtractedFromVec.getValueType();
10104 // Quit if not 128/256-bit vector.
10105 if (!VT.is128BitVector() && !VT.is256BitVector())
10107 // Quit if not the same type.
10108 if (VecInMap.begin() != VecInMap.end() &&
10109 VT != VecInMap.begin()->first.getValueType())
10111 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10112 VecIns.push_back(ExtractedFromVec);
10114 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10117 assert((VT.is128BitVector() || VT.is256BitVector()) &&
10118 "Not extracted from 128-/256-bit vector.");
10120 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10122 for (DenseMap<SDValue, unsigned>::const_iterator
10123 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10124 // Quit if not all elements are used.
10125 if (I->second != FullMask)
10129 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10131 // Cast all vectors into TestVT for PTEST.
10132 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10133 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10135 // If more than one full vectors are evaluated, OR them first before PTEST.
10136 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10137 // Each iteration will OR 2 nodes and append the result until there is only
10138 // 1 node left, i.e. the final OR'd value of all vectors.
10139 SDValue LHS = VecIns[Slot];
10140 SDValue RHS = VecIns[Slot + 1];
10141 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10144 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10145 VecIns.back(), VecIns.back());
10148 /// \brief return true if \c Op has a use that doesn't just read flags.
10149 static bool hasNonFlagsUse(SDValue Op) {
10150 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10152 SDNode *User = *UI;
10153 unsigned UOpNo = UI.getOperandNo();
10154 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10155 // Look pass truncate.
10156 UOpNo = User->use_begin().getOperandNo();
10157 User = *User->use_begin();
10160 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10161 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10167 /// Emit nodes that will be selected as "test Op0,Op0", or something
10169 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10170 SelectionDAG &DAG) const {
10171 if (Op.getValueType() == MVT::i1)
10172 // KORTEST instruction should be selected
10173 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10174 DAG.getConstant(0, Op.getValueType()));
10176 // CF and OF aren't always set the way we want. Determine which
10177 // of these we need.
10178 bool NeedCF = false;
10179 bool NeedOF = false;
10182 case X86::COND_A: case X86::COND_AE:
10183 case X86::COND_B: case X86::COND_BE:
10186 case X86::COND_G: case X86::COND_GE:
10187 case X86::COND_L: case X86::COND_LE:
10188 case X86::COND_O: case X86::COND_NO: {
10189 // Check if we really need to set the
10190 // Overflow flag. If NoSignedWrap is present
10191 // that is not actually needed.
10192 switch (Op->getOpcode()) {
10197 const BinaryWithFlagsSDNode *BinNode =
10198 cast<BinaryWithFlagsSDNode>(Op.getNode());
10199 if (BinNode->hasNoSignedWrap())
10209 // See if we can use the EFLAGS value from the operand instead of
10210 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10211 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10212 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10213 // Emit a CMP with 0, which is the TEST pattern.
10214 //if (Op.getValueType() == MVT::i1)
10215 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10216 // DAG.getConstant(0, MVT::i1));
10217 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10218 DAG.getConstant(0, Op.getValueType()));
10220 unsigned Opcode = 0;
10221 unsigned NumOperands = 0;
10223 // Truncate operations may prevent the merge of the SETCC instruction
10224 // and the arithmetic instruction before it. Attempt to truncate the operands
10225 // of the arithmetic instruction and use a reduced bit-width instruction.
10226 bool NeedTruncation = false;
10227 SDValue ArithOp = Op;
10228 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10229 SDValue Arith = Op->getOperand(0);
10230 // Both the trunc and the arithmetic op need to have one user each.
10231 if (Arith->hasOneUse())
10232 switch (Arith.getOpcode()) {
10239 NeedTruncation = true;
10245 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10246 // which may be the result of a CAST. We use the variable 'Op', which is the
10247 // non-casted variable when we check for possible users.
10248 switch (ArithOp.getOpcode()) {
10250 // Due to an isel shortcoming, be conservative if this add is likely to be
10251 // selected as part of a load-modify-store instruction. When the root node
10252 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10253 // uses of other nodes in the match, such as the ADD in this case. This
10254 // leads to the ADD being left around and reselected, with the result being
10255 // two adds in the output. Alas, even if none our users are stores, that
10256 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10257 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10258 // climbing the DAG back to the root, and it doesn't seem to be worth the
10260 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10261 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10262 if (UI->getOpcode() != ISD::CopyToReg &&
10263 UI->getOpcode() != ISD::SETCC &&
10264 UI->getOpcode() != ISD::STORE)
10267 if (ConstantSDNode *C =
10268 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10269 // An add of one will be selected as an INC.
10270 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10271 Opcode = X86ISD::INC;
10276 // An add of negative one (subtract of one) will be selected as a DEC.
10277 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10278 Opcode = X86ISD::DEC;
10284 // Otherwise use a regular EFLAGS-setting add.
10285 Opcode = X86ISD::ADD;
10290 // If we have a constant logical shift that's only used in a comparison
10291 // against zero turn it into an equivalent AND. This allows turning it into
10292 // a TEST instruction later.
10293 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10294 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10295 EVT VT = Op.getValueType();
10296 unsigned BitWidth = VT.getSizeInBits();
10297 unsigned ShAmt = Op->getConstantOperandVal(1);
10298 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10300 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10301 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10302 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10303 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10305 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10306 DAG.getConstant(Mask, VT));
10307 DAG.ReplaceAllUsesWith(Op, New);
10313 // If the primary and result isn't used, don't bother using X86ISD::AND,
10314 // because a TEST instruction will be better.
10315 if (!hasNonFlagsUse(Op))
10321 // Due to the ISEL shortcoming noted above, be conservative if this op is
10322 // likely to be selected as part of a load-modify-store instruction.
10323 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10324 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10325 if (UI->getOpcode() == ISD::STORE)
10328 // Otherwise use a regular EFLAGS-setting instruction.
10329 switch (ArithOp.getOpcode()) {
10330 default: llvm_unreachable("unexpected operator!");
10331 case ISD::SUB: Opcode = X86ISD::SUB; break;
10332 case ISD::XOR: Opcode = X86ISD::XOR; break;
10333 case ISD::AND: Opcode = X86ISD::AND; break;
10335 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10336 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10337 if (EFLAGS.getNode())
10340 Opcode = X86ISD::OR;
10354 return SDValue(Op.getNode(), 1);
10360 // If we found that truncation is beneficial, perform the truncation and
10362 if (NeedTruncation) {
10363 EVT VT = Op.getValueType();
10364 SDValue WideVal = Op->getOperand(0);
10365 EVT WideVT = WideVal.getValueType();
10366 unsigned ConvertedOp = 0;
10367 // Use a target machine opcode to prevent further DAGCombine
10368 // optimizations that may separate the arithmetic operations
10369 // from the setcc node.
10370 switch (WideVal.getOpcode()) {
10372 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10373 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10374 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10375 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10376 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10380 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10381 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10382 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10383 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10384 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10390 // Emit a CMP with 0, which is the TEST pattern.
10391 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10392 DAG.getConstant(0, Op.getValueType()));
10394 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10395 SmallVector<SDValue, 4> Ops;
10396 for (unsigned i = 0; i != NumOperands; ++i)
10397 Ops.push_back(Op.getOperand(i));
10399 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10400 DAG.ReplaceAllUsesWith(Op, New);
10401 return SDValue(New.getNode(), 1);
10404 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10406 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10407 SDLoc dl, SelectionDAG &DAG) const {
10408 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10409 if (C->getAPIntValue() == 0)
10410 return EmitTest(Op0, X86CC, dl, DAG);
10412 if (Op0.getValueType() == MVT::i1)
10413 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10416 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10417 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10418 // Do the comparison at i32 if it's smaller, besides the Atom case.
10419 // This avoids subregister aliasing issues. Keep the smaller reference
10420 // if we're optimizing for size, however, as that'll allow better folding
10421 // of memory operations.
10422 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10423 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10424 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10425 !Subtarget->isAtom()) {
10426 unsigned ExtendOp =
10427 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10428 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10429 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10431 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10432 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10433 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10435 return SDValue(Sub.getNode(), 1);
10437 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10440 /// Convert a comparison if required by the subtarget.
10441 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10442 SelectionDAG &DAG) const {
10443 // If the subtarget does not support the FUCOMI instruction, floating-point
10444 // comparisons have to be converted.
10445 if (Subtarget->hasCMov() ||
10446 Cmp.getOpcode() != X86ISD::CMP ||
10447 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10448 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10451 // The instruction selector will select an FUCOM instruction instead of
10452 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10453 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10454 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10456 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10457 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10458 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10459 DAG.getConstant(8, MVT::i8));
10460 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10461 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10464 static bool isAllOnes(SDValue V) {
10465 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10466 return C && C->isAllOnesValue();
10469 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10470 /// if it's possible.
10471 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10472 SDLoc dl, SelectionDAG &DAG) const {
10473 SDValue Op0 = And.getOperand(0);
10474 SDValue Op1 = And.getOperand(1);
10475 if (Op0.getOpcode() == ISD::TRUNCATE)
10476 Op0 = Op0.getOperand(0);
10477 if (Op1.getOpcode() == ISD::TRUNCATE)
10478 Op1 = Op1.getOperand(0);
10481 if (Op1.getOpcode() == ISD::SHL)
10482 std::swap(Op0, Op1);
10483 if (Op0.getOpcode() == ISD::SHL) {
10484 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10485 if (And00C->getZExtValue() == 1) {
10486 // If we looked past a truncate, check that it's only truncating away
10488 unsigned BitWidth = Op0.getValueSizeInBits();
10489 unsigned AndBitWidth = And.getValueSizeInBits();
10490 if (BitWidth > AndBitWidth) {
10492 DAG.computeKnownBits(Op0, Zeros, Ones);
10493 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10497 RHS = Op0.getOperand(1);
10499 } else if (Op1.getOpcode() == ISD::Constant) {
10500 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10501 uint64_t AndRHSVal = AndRHS->getZExtValue();
10502 SDValue AndLHS = Op0;
10504 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10505 LHS = AndLHS.getOperand(0);
10506 RHS = AndLHS.getOperand(1);
10509 // Use BT if the immediate can't be encoded in a TEST instruction.
10510 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10512 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10516 if (LHS.getNode()) {
10517 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10518 // instruction. Since the shift amount is in-range-or-undefined, we know
10519 // that doing a bittest on the i32 value is ok. We extend to i32 because
10520 // the encoding for the i16 version is larger than the i32 version.
10521 // Also promote i16 to i32 for performance / code size reason.
10522 if (LHS.getValueType() == MVT::i8 ||
10523 LHS.getValueType() == MVT::i16)
10524 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10526 // If the operand types disagree, extend the shift amount to match. Since
10527 // BT ignores high bits (like shifts) we can use anyextend.
10528 if (LHS.getValueType() != RHS.getValueType())
10529 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10531 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10532 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10533 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10534 DAG.getConstant(Cond, MVT::i8), BT);
10540 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10542 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10547 // SSE Condition code mapping:
10556 switch (SetCCOpcode) {
10557 default: llvm_unreachable("Unexpected SETCC condition");
10559 case ISD::SETEQ: SSECC = 0; break;
10561 case ISD::SETGT: Swap = true; // Fallthrough
10563 case ISD::SETOLT: SSECC = 1; break;
10565 case ISD::SETGE: Swap = true; // Fallthrough
10567 case ISD::SETOLE: SSECC = 2; break;
10568 case ISD::SETUO: SSECC = 3; break;
10570 case ISD::SETNE: SSECC = 4; break;
10571 case ISD::SETULE: Swap = true; // Fallthrough
10572 case ISD::SETUGE: SSECC = 5; break;
10573 case ISD::SETULT: Swap = true; // Fallthrough
10574 case ISD::SETUGT: SSECC = 6; break;
10575 case ISD::SETO: SSECC = 7; break;
10577 case ISD::SETONE: SSECC = 8; break;
10580 std::swap(Op0, Op1);
10585 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10586 // ones, and then concatenate the result back.
10587 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10588 MVT VT = Op.getSimpleValueType();
10590 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10591 "Unsupported value type for operation");
10593 unsigned NumElems = VT.getVectorNumElements();
10595 SDValue CC = Op.getOperand(2);
10597 // Extract the LHS vectors
10598 SDValue LHS = Op.getOperand(0);
10599 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10600 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10602 // Extract the RHS vectors
10603 SDValue RHS = Op.getOperand(1);
10604 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10605 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10607 // Issue the operation on the smaller types and concatenate the result back
10608 MVT EltVT = VT.getVectorElementType();
10609 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10610 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10611 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10612 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10615 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10616 const X86Subtarget *Subtarget) {
10617 SDValue Op0 = Op.getOperand(0);
10618 SDValue Op1 = Op.getOperand(1);
10619 SDValue CC = Op.getOperand(2);
10620 MVT VT = Op.getSimpleValueType();
10623 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10624 Op.getValueType().getScalarType() == MVT::i1 &&
10625 "Cannot set masked compare for this operation");
10627 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10629 bool Unsigned = false;
10632 switch (SetCCOpcode) {
10633 default: llvm_unreachable("Unexpected SETCC condition");
10634 case ISD::SETNE: SSECC = 4; break;
10635 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10636 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10637 case ISD::SETLT: Swap = true; //fall-through
10638 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10639 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10640 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10641 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10642 case ISD::SETULE: Unsigned = true; //fall-through
10643 case ISD::SETLE: SSECC = 2; break;
10647 std::swap(Op0, Op1);
10649 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10650 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10651 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10652 DAG.getConstant(SSECC, MVT::i8));
10655 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10656 /// operand \p Op1. If non-trivial (for example because it's not constant)
10657 /// return an empty value.
10658 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10660 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10664 MVT VT = Op1.getSimpleValueType();
10665 MVT EVT = VT.getVectorElementType();
10666 unsigned n = VT.getVectorNumElements();
10667 SmallVector<SDValue, 8> ULTOp1;
10669 for (unsigned i = 0; i < n; ++i) {
10670 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10671 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10674 // Avoid underflow.
10675 APInt Val = Elt->getAPIntValue();
10679 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10682 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10685 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10686 SelectionDAG &DAG) {
10687 SDValue Op0 = Op.getOperand(0);
10688 SDValue Op1 = Op.getOperand(1);
10689 SDValue CC = Op.getOperand(2);
10690 MVT VT = Op.getSimpleValueType();
10691 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10692 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10697 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10698 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10701 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10702 unsigned Opc = X86ISD::CMPP;
10703 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10704 assert(VT.getVectorNumElements() <= 16);
10705 Opc = X86ISD::CMPM;
10707 // In the two special cases we can't handle, emit two comparisons.
10710 unsigned CombineOpc;
10711 if (SetCCOpcode == ISD::SETUEQ) {
10712 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10714 assert(SetCCOpcode == ISD::SETONE);
10715 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10718 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10719 DAG.getConstant(CC0, MVT::i8));
10720 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10721 DAG.getConstant(CC1, MVT::i8));
10722 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10724 // Handle all other FP comparisons here.
10725 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10726 DAG.getConstant(SSECC, MVT::i8));
10729 // Break 256-bit integer vector compare into smaller ones.
10730 if (VT.is256BitVector() && !Subtarget->hasInt256())
10731 return Lower256IntVSETCC(Op, DAG);
10733 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10734 EVT OpVT = Op1.getValueType();
10735 if (Subtarget->hasAVX512()) {
10736 if (Op1.getValueType().is512BitVector() ||
10737 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10738 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10740 // In AVX-512 architecture setcc returns mask with i1 elements,
10741 // But there is no compare instruction for i8 and i16 elements.
10742 // We are not talking about 512-bit operands in this case, these
10743 // types are illegal.
10745 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10746 OpVT.getVectorElementType().getSizeInBits() >= 8))
10747 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10748 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10751 // We are handling one of the integer comparisons here. Since SSE only has
10752 // GT and EQ comparisons for integer, swapping operands and multiple
10753 // operations may be required for some comparisons.
10755 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10756 bool Subus = false;
10758 switch (SetCCOpcode) {
10759 default: llvm_unreachable("Unexpected SETCC condition");
10760 case ISD::SETNE: Invert = true;
10761 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10762 case ISD::SETLT: Swap = true;
10763 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10764 case ISD::SETGE: Swap = true;
10765 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10766 Invert = true; break;
10767 case ISD::SETULT: Swap = true;
10768 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10769 FlipSigns = true; break;
10770 case ISD::SETUGE: Swap = true;
10771 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10772 FlipSigns = true; Invert = true; break;
10775 // Special case: Use min/max operations for SETULE/SETUGE
10776 MVT VET = VT.getVectorElementType();
10778 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10779 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10782 switch (SetCCOpcode) {
10784 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10785 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10788 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10791 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10792 if (!MinMax && hasSubus) {
10793 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10795 // t = psubus Op0, Op1
10796 // pcmpeq t, <0..0>
10797 switch (SetCCOpcode) {
10799 case ISD::SETULT: {
10800 // If the comparison is against a constant we can turn this into a
10801 // setule. With psubus, setule does not require a swap. This is
10802 // beneficial because the constant in the register is no longer
10803 // destructed as the destination so it can be hoisted out of a loop.
10804 // Only do this pre-AVX since vpcmp* is no longer destructive.
10805 if (Subtarget->hasAVX())
10807 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10808 if (ULEOp1.getNode()) {
10810 Subus = true; Invert = false; Swap = false;
10814 // Psubus is better than flip-sign because it requires no inversion.
10815 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10816 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10820 Opc = X86ISD::SUBUS;
10826 std::swap(Op0, Op1);
10828 // Check that the operation in question is available (most are plain SSE2,
10829 // but PCMPGTQ and PCMPEQQ have different requirements).
10830 if (VT == MVT::v2i64) {
10831 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10832 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10834 // First cast everything to the right type.
10835 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10836 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10838 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10839 // bits of the inputs before performing those operations. The lower
10840 // compare is always unsigned.
10843 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10845 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10846 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10847 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10848 Sign, Zero, Sign, Zero);
10850 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10851 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10853 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10854 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10855 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10857 // Create masks for only the low parts/high parts of the 64 bit integers.
10858 static const int MaskHi[] = { 1, 1, 3, 3 };
10859 static const int MaskLo[] = { 0, 0, 2, 2 };
10860 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10861 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10862 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10864 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10865 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10868 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10870 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10873 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10874 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10875 // pcmpeqd + pshufd + pand.
10876 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10878 // First cast everything to the right type.
10879 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10880 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10883 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10885 // Make sure the lower and upper halves are both all-ones.
10886 static const int Mask[] = { 1, 0, 3, 2 };
10887 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10888 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10891 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10893 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10897 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10898 // bits of the inputs before performing those operations.
10900 EVT EltVT = VT.getVectorElementType();
10901 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10902 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10903 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10906 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10908 // If the logical-not of the result is required, perform that now.
10910 Result = DAG.getNOT(dl, Result, VT);
10913 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10916 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10917 getZeroVector(VT, Subtarget, DAG, dl));
10922 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10924 MVT VT = Op.getSimpleValueType();
10926 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10928 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10929 && "SetCC type must be 8-bit or 1-bit integer");
10930 SDValue Op0 = Op.getOperand(0);
10931 SDValue Op1 = Op.getOperand(1);
10933 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10935 // Optimize to BT if possible.
10936 // Lower (X & (1 << N)) == 0 to BT(X, N).
10937 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10938 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10939 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10940 Op1.getOpcode() == ISD::Constant &&
10941 cast<ConstantSDNode>(Op1)->isNullValue() &&
10942 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10943 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10944 if (NewSetCC.getNode())
10948 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10950 if (Op1.getOpcode() == ISD::Constant &&
10951 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10952 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10953 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10955 // If the input is a setcc, then reuse the input setcc or use a new one with
10956 // the inverted condition.
10957 if (Op0.getOpcode() == X86ISD::SETCC) {
10958 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10959 bool Invert = (CC == ISD::SETNE) ^
10960 cast<ConstantSDNode>(Op1)->isNullValue();
10964 CCode = X86::GetOppositeBranchCondition(CCode);
10965 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10966 DAG.getConstant(CCode, MVT::i8),
10967 Op0.getOperand(1));
10969 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10973 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10974 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10975 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10977 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10978 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10981 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10982 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10983 if (X86CC == X86::COND_INVALID)
10986 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10987 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10988 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10989 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10991 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10995 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10996 static bool isX86LogicalCmp(SDValue Op) {
10997 unsigned Opc = Op.getNode()->getOpcode();
10998 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10999 Opc == X86ISD::SAHF)
11001 if (Op.getResNo() == 1 &&
11002 (Opc == X86ISD::ADD ||
11003 Opc == X86ISD::SUB ||
11004 Opc == X86ISD::ADC ||
11005 Opc == X86ISD::SBB ||
11006 Opc == X86ISD::SMUL ||
11007 Opc == X86ISD::UMUL ||
11008 Opc == X86ISD::INC ||
11009 Opc == X86ISD::DEC ||
11010 Opc == X86ISD::OR ||
11011 Opc == X86ISD::XOR ||
11012 Opc == X86ISD::AND))
11015 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11021 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11022 if (V.getOpcode() != ISD::TRUNCATE)
11025 SDValue VOp0 = V.getOperand(0);
11026 unsigned InBits = VOp0.getValueSizeInBits();
11027 unsigned Bits = V.getValueSizeInBits();
11028 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11031 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11032 bool addTest = true;
11033 SDValue Cond = Op.getOperand(0);
11034 SDValue Op1 = Op.getOperand(1);
11035 SDValue Op2 = Op.getOperand(2);
11037 EVT VT = Op1.getValueType();
11040 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11041 // are available. Otherwise fp cmovs get lowered into a less efficient branch
11042 // sequence later on.
11043 if (Cond.getOpcode() == ISD::SETCC &&
11044 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11045 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11046 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11047 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11048 int SSECC = translateX86FSETCC(
11049 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11052 if (Subtarget->hasAVX512()) {
11053 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11054 DAG.getConstant(SSECC, MVT::i8));
11055 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11057 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11058 DAG.getConstant(SSECC, MVT::i8));
11059 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11060 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11061 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11065 if (Cond.getOpcode() == ISD::SETCC) {
11066 SDValue NewCond = LowerSETCC(Cond, DAG);
11067 if (NewCond.getNode())
11071 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11072 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11073 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11074 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11075 if (Cond.getOpcode() == X86ISD::SETCC &&
11076 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11077 isZero(Cond.getOperand(1).getOperand(1))) {
11078 SDValue Cmp = Cond.getOperand(1);
11080 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11082 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11083 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11084 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11086 SDValue CmpOp0 = Cmp.getOperand(0);
11087 // Apply further optimizations for special cases
11088 // (select (x != 0), -1, 0) -> neg & sbb
11089 // (select (x == 0), 0, -1) -> neg & sbb
11090 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11091 if (YC->isNullValue() &&
11092 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11093 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11094 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11095 DAG.getConstant(0, CmpOp0.getValueType()),
11097 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11098 DAG.getConstant(X86::COND_B, MVT::i8),
11099 SDValue(Neg.getNode(), 1));
11103 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11104 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11105 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11107 SDValue Res = // Res = 0 or -1.
11108 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11109 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11111 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11112 Res = DAG.getNOT(DL, Res, Res.getValueType());
11114 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11115 if (!N2C || !N2C->isNullValue())
11116 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11121 // Look past (and (setcc_carry (cmp ...)), 1).
11122 if (Cond.getOpcode() == ISD::AND &&
11123 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11124 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11125 if (C && C->getAPIntValue() == 1)
11126 Cond = Cond.getOperand(0);
11129 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11130 // setting operand in place of the X86ISD::SETCC.
11131 unsigned CondOpcode = Cond.getOpcode();
11132 if (CondOpcode == X86ISD::SETCC ||
11133 CondOpcode == X86ISD::SETCC_CARRY) {
11134 CC = Cond.getOperand(0);
11136 SDValue Cmp = Cond.getOperand(1);
11137 unsigned Opc = Cmp.getOpcode();
11138 MVT VT = Op.getSimpleValueType();
11140 bool IllegalFPCMov = false;
11141 if (VT.isFloatingPoint() && !VT.isVector() &&
11142 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11143 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11145 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11146 Opc == X86ISD::BT) { // FIXME
11150 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11151 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11152 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11153 Cond.getOperand(0).getValueType() != MVT::i8)) {
11154 SDValue LHS = Cond.getOperand(0);
11155 SDValue RHS = Cond.getOperand(1);
11156 unsigned X86Opcode;
11159 switch (CondOpcode) {
11160 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11161 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11162 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11163 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11164 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11165 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11166 default: llvm_unreachable("unexpected overflowing operator");
11168 if (CondOpcode == ISD::UMULO)
11169 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11172 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11174 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11176 if (CondOpcode == ISD::UMULO)
11177 Cond = X86Op.getValue(2);
11179 Cond = X86Op.getValue(1);
11181 CC = DAG.getConstant(X86Cond, MVT::i8);
11186 // Look pass the truncate if the high bits are known zero.
11187 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11188 Cond = Cond.getOperand(0);
11190 // We know the result of AND is compared against zero. Try to match
11192 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11193 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11194 if (NewSetCC.getNode()) {
11195 CC = NewSetCC.getOperand(0);
11196 Cond = NewSetCC.getOperand(1);
11203 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11204 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11207 // a < b ? -1 : 0 -> RES = ~setcc_carry
11208 // a < b ? 0 : -1 -> RES = setcc_carry
11209 // a >= b ? -1 : 0 -> RES = setcc_carry
11210 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11211 if (Cond.getOpcode() == X86ISD::SUB) {
11212 Cond = ConvertCmpIfNecessary(Cond, DAG);
11213 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11215 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11216 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11217 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11218 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11219 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11220 return DAG.getNOT(DL, Res, Res.getValueType());
11225 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11226 // widen the cmov and push the truncate through. This avoids introducing a new
11227 // branch during isel and doesn't add any extensions.
11228 if (Op.getValueType() == MVT::i8 &&
11229 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11230 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11231 if (T1.getValueType() == T2.getValueType() &&
11232 // Blacklist CopyFromReg to avoid partial register stalls.
11233 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11234 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11235 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11236 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11240 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11241 // condition is true.
11242 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11243 SDValue Ops[] = { Op2, Op1, CC, Cond };
11244 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11247 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11248 MVT VT = Op->getSimpleValueType(0);
11249 SDValue In = Op->getOperand(0);
11250 MVT InVT = In.getSimpleValueType();
11253 unsigned int NumElts = VT.getVectorNumElements();
11254 if (NumElts != 8 && NumElts != 16)
11257 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11258 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11260 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11261 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11263 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11264 Constant *C = ConstantInt::get(*DAG.getContext(),
11265 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11267 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11268 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11269 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11270 MachinePointerInfo::getConstantPool(),
11271 false, false, false, Alignment);
11272 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11273 if (VT.is512BitVector())
11275 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11278 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11279 SelectionDAG &DAG) {
11280 MVT VT = Op->getSimpleValueType(0);
11281 SDValue In = Op->getOperand(0);
11282 MVT InVT = In.getSimpleValueType();
11285 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11286 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11288 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11289 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11290 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11293 if (Subtarget->hasInt256())
11294 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11296 // Optimize vectors in AVX mode
11297 // Sign extend v8i16 to v8i32 and
11300 // Divide input vector into two parts
11301 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11302 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11303 // concat the vectors to original VT
11305 unsigned NumElems = InVT.getVectorNumElements();
11306 SDValue Undef = DAG.getUNDEF(InVT);
11308 SmallVector<int,8> ShufMask1(NumElems, -1);
11309 for (unsigned i = 0; i != NumElems/2; ++i)
11312 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11314 SmallVector<int,8> ShufMask2(NumElems, -1);
11315 for (unsigned i = 0; i != NumElems/2; ++i)
11316 ShufMask2[i] = i + NumElems/2;
11318 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11320 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11321 VT.getVectorNumElements()/2);
11323 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11324 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11326 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11329 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11330 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11331 // from the AND / OR.
11332 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11333 Opc = Op.getOpcode();
11334 if (Opc != ISD::OR && Opc != ISD::AND)
11336 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11337 Op.getOperand(0).hasOneUse() &&
11338 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11339 Op.getOperand(1).hasOneUse());
11342 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11343 // 1 and that the SETCC node has a single use.
11344 static bool isXor1OfSetCC(SDValue Op) {
11345 if (Op.getOpcode() != ISD::XOR)
11347 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11348 if (N1C && N1C->getAPIntValue() == 1) {
11349 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11350 Op.getOperand(0).hasOneUse();
11355 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11356 bool addTest = true;
11357 SDValue Chain = Op.getOperand(0);
11358 SDValue Cond = Op.getOperand(1);
11359 SDValue Dest = Op.getOperand(2);
11362 bool Inverted = false;
11364 if (Cond.getOpcode() == ISD::SETCC) {
11365 // Check for setcc([su]{add,sub,mul}o == 0).
11366 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11367 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11368 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11369 Cond.getOperand(0).getResNo() == 1 &&
11370 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11371 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11372 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11373 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11374 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11375 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11377 Cond = Cond.getOperand(0);
11379 SDValue NewCond = LowerSETCC(Cond, DAG);
11380 if (NewCond.getNode())
11385 // FIXME: LowerXALUO doesn't handle these!!
11386 else if (Cond.getOpcode() == X86ISD::ADD ||
11387 Cond.getOpcode() == X86ISD::SUB ||
11388 Cond.getOpcode() == X86ISD::SMUL ||
11389 Cond.getOpcode() == X86ISD::UMUL)
11390 Cond = LowerXALUO(Cond, DAG);
11393 // Look pass (and (setcc_carry (cmp ...)), 1).
11394 if (Cond.getOpcode() == ISD::AND &&
11395 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11396 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11397 if (C && C->getAPIntValue() == 1)
11398 Cond = Cond.getOperand(0);
11401 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11402 // setting operand in place of the X86ISD::SETCC.
11403 unsigned CondOpcode = Cond.getOpcode();
11404 if (CondOpcode == X86ISD::SETCC ||
11405 CondOpcode == X86ISD::SETCC_CARRY) {
11406 CC = Cond.getOperand(0);
11408 SDValue Cmp = Cond.getOperand(1);
11409 unsigned Opc = Cmp.getOpcode();
11410 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11411 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11415 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11419 // These can only come from an arithmetic instruction with overflow,
11420 // e.g. SADDO, UADDO.
11421 Cond = Cond.getNode()->getOperand(1);
11427 CondOpcode = Cond.getOpcode();
11428 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11429 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11430 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11431 Cond.getOperand(0).getValueType() != MVT::i8)) {
11432 SDValue LHS = Cond.getOperand(0);
11433 SDValue RHS = Cond.getOperand(1);
11434 unsigned X86Opcode;
11437 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11438 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11440 switch (CondOpcode) {
11441 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11443 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11445 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11448 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11449 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11451 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11453 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11456 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11457 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11458 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11459 default: llvm_unreachable("unexpected overflowing operator");
11462 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11463 if (CondOpcode == ISD::UMULO)
11464 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11467 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11469 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11471 if (CondOpcode == ISD::UMULO)
11472 Cond = X86Op.getValue(2);
11474 Cond = X86Op.getValue(1);
11476 CC = DAG.getConstant(X86Cond, MVT::i8);
11480 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11481 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11482 if (CondOpc == ISD::OR) {
11483 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11484 // two branches instead of an explicit OR instruction with a
11486 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11487 isX86LogicalCmp(Cmp)) {
11488 CC = Cond.getOperand(0).getOperand(0);
11489 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11490 Chain, Dest, CC, Cmp);
11491 CC = Cond.getOperand(1).getOperand(0);
11495 } else { // ISD::AND
11496 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11497 // two branches instead of an explicit AND instruction with a
11498 // separate test. However, we only do this if this block doesn't
11499 // have a fall-through edge, because this requires an explicit
11500 // jmp when the condition is false.
11501 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11502 isX86LogicalCmp(Cmp) &&
11503 Op.getNode()->hasOneUse()) {
11504 X86::CondCode CCode =
11505 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11506 CCode = X86::GetOppositeBranchCondition(CCode);
11507 CC = DAG.getConstant(CCode, MVT::i8);
11508 SDNode *User = *Op.getNode()->use_begin();
11509 // Look for an unconditional branch following this conditional branch.
11510 // We need this because we need to reverse the successors in order
11511 // to implement FCMP_OEQ.
11512 if (User->getOpcode() == ISD::BR) {
11513 SDValue FalseBB = User->getOperand(1);
11515 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11516 assert(NewBR == User);
11520 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11521 Chain, Dest, CC, Cmp);
11522 X86::CondCode CCode =
11523 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11524 CCode = X86::GetOppositeBranchCondition(CCode);
11525 CC = DAG.getConstant(CCode, MVT::i8);
11531 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11532 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11533 // It should be transformed during dag combiner except when the condition
11534 // is set by a arithmetics with overflow node.
11535 X86::CondCode CCode =
11536 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11537 CCode = X86::GetOppositeBranchCondition(CCode);
11538 CC = DAG.getConstant(CCode, MVT::i8);
11539 Cond = Cond.getOperand(0).getOperand(1);
11541 } else if (Cond.getOpcode() == ISD::SETCC &&
11542 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11543 // For FCMP_OEQ, we can emit
11544 // two branches instead of an explicit AND instruction with a
11545 // separate test. However, we only do this if this block doesn't
11546 // have a fall-through edge, because this requires an explicit
11547 // jmp when the condition is false.
11548 if (Op.getNode()->hasOneUse()) {
11549 SDNode *User = *Op.getNode()->use_begin();
11550 // Look for an unconditional branch following this conditional branch.
11551 // We need this because we need to reverse the successors in order
11552 // to implement FCMP_OEQ.
11553 if (User->getOpcode() == ISD::BR) {
11554 SDValue FalseBB = User->getOperand(1);
11556 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11557 assert(NewBR == User);
11561 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11562 Cond.getOperand(0), Cond.getOperand(1));
11563 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11564 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11565 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11566 Chain, Dest, CC, Cmp);
11567 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11572 } else if (Cond.getOpcode() == ISD::SETCC &&
11573 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11574 // For FCMP_UNE, we can emit
11575 // two branches instead of an explicit AND instruction with a
11576 // separate test. However, we only do this if this block doesn't
11577 // have a fall-through edge, because this requires an explicit
11578 // jmp when the condition is false.
11579 if (Op.getNode()->hasOneUse()) {
11580 SDNode *User = *Op.getNode()->use_begin();
11581 // Look for an unconditional branch following this conditional branch.
11582 // We need this because we need to reverse the successors in order
11583 // to implement FCMP_UNE.
11584 if (User->getOpcode() == ISD::BR) {
11585 SDValue FalseBB = User->getOperand(1);
11587 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11588 assert(NewBR == User);
11591 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11592 Cond.getOperand(0), Cond.getOperand(1));
11593 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11594 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11595 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11596 Chain, Dest, CC, Cmp);
11597 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11607 // Look pass the truncate if the high bits are known zero.
11608 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11609 Cond = Cond.getOperand(0);
11611 // We know the result of AND is compared against zero. Try to match
11613 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11614 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11615 if (NewSetCC.getNode()) {
11616 CC = NewSetCC.getOperand(0);
11617 Cond = NewSetCC.getOperand(1);
11624 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11625 CC = DAG.getConstant(X86Cond, MVT::i8);
11626 Cond = EmitTest(Cond, X86Cond, dl, DAG);
11628 Cond = ConvertCmpIfNecessary(Cond, DAG);
11629 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11630 Chain, Dest, CC, Cond);
11633 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11634 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11635 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11636 // that the guard pages used by the OS virtual memory manager are allocated in
11637 // correct sequence.
11639 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11640 SelectionDAG &DAG) const {
11641 MachineFunction &MF = DAG.getMachineFunction();
11642 bool SplitStack = MF.shouldSplitStack();
11643 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11649 SDNode* Node = Op.getNode();
11651 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11652 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11653 " not tell us which reg is the stack pointer!");
11654 EVT VT = Node->getValueType(0);
11655 SDValue Tmp1 = SDValue(Node, 0);
11656 SDValue Tmp2 = SDValue(Node, 1);
11657 SDValue Tmp3 = Node->getOperand(2);
11658 SDValue Chain = Tmp1.getOperand(0);
11660 // Chain the dynamic stack allocation so that it doesn't modify the stack
11661 // pointer when other instructions are using the stack.
11662 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11665 SDValue Size = Tmp2.getOperand(1);
11666 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11667 Chain = SP.getValue(1);
11668 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11669 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
11670 unsigned StackAlign = TFI.getStackAlignment();
11671 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11672 if (Align > StackAlign)
11673 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11674 DAG.getConstant(-(uint64_t)Align, VT));
11675 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11677 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11678 DAG.getIntPtrConstant(0, true), SDValue(),
11681 SDValue Ops[2] = { Tmp1, Tmp2 };
11682 return DAG.getMergeValues(Ops, dl);
11686 SDValue Chain = Op.getOperand(0);
11687 SDValue Size = Op.getOperand(1);
11688 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11689 EVT VT = Op.getNode()->getValueType(0);
11691 bool Is64Bit = Subtarget->is64Bit();
11692 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11695 MachineRegisterInfo &MRI = MF.getRegInfo();
11698 // The 64 bit implementation of segmented stacks needs to clobber both r10
11699 // r11. This makes it impossible to use it along with nested parameters.
11700 const Function *F = MF.getFunction();
11702 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11704 if (I->hasNestAttr())
11705 report_fatal_error("Cannot use segmented stacks with functions that "
11706 "have nested arguments.");
11709 const TargetRegisterClass *AddrRegClass =
11710 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11711 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11712 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11713 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11714 DAG.getRegister(Vreg, SPTy));
11715 SDValue Ops1[2] = { Value, Chain };
11716 return DAG.getMergeValues(Ops1, dl);
11719 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11721 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11722 Flag = Chain.getValue(1);
11723 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11725 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11727 const X86RegisterInfo *RegInfo =
11728 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
11729 unsigned SPReg = RegInfo->getStackRegister();
11730 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11731 Chain = SP.getValue(1);
11734 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11735 DAG.getConstant(-(uint64_t)Align, VT));
11736 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11739 SDValue Ops1[2] = { SP, Chain };
11740 return DAG.getMergeValues(Ops1, dl);
11744 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11745 MachineFunction &MF = DAG.getMachineFunction();
11746 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11748 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11751 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11752 // vastart just stores the address of the VarArgsFrameIndex slot into the
11753 // memory location argument.
11754 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11756 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11757 MachinePointerInfo(SV), false, false, 0);
11761 // gp_offset (0 - 6 * 8)
11762 // fp_offset (48 - 48 + 8 * 16)
11763 // overflow_arg_area (point to parameters coming in memory).
11765 SmallVector<SDValue, 8> MemOps;
11766 SDValue FIN = Op.getOperand(1);
11768 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11769 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11771 FIN, MachinePointerInfo(SV), false, false, 0);
11772 MemOps.push_back(Store);
11775 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11776 FIN, DAG.getIntPtrConstant(4));
11777 Store = DAG.getStore(Op.getOperand(0), DL,
11778 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11780 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11781 MemOps.push_back(Store);
11783 // Store ptr to overflow_arg_area
11784 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11785 FIN, DAG.getIntPtrConstant(4));
11786 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11788 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11789 MachinePointerInfo(SV, 8),
11791 MemOps.push_back(Store);
11793 // Store ptr to reg_save_area.
11794 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11795 FIN, DAG.getIntPtrConstant(8));
11796 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11798 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11799 MachinePointerInfo(SV, 16), false, false, 0);
11800 MemOps.push_back(Store);
11801 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11804 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11805 assert(Subtarget->is64Bit() &&
11806 "LowerVAARG only handles 64-bit va_arg!");
11807 assert((Subtarget->isTargetLinux() ||
11808 Subtarget->isTargetDarwin()) &&
11809 "Unhandled target in LowerVAARG");
11810 assert(Op.getNode()->getNumOperands() == 4);
11811 SDValue Chain = Op.getOperand(0);
11812 SDValue SrcPtr = Op.getOperand(1);
11813 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11814 unsigned Align = Op.getConstantOperandVal(3);
11817 EVT ArgVT = Op.getNode()->getValueType(0);
11818 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11819 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11822 // Decide which area this value should be read from.
11823 // TODO: Implement the AMD64 ABI in its entirety. This simple
11824 // selection mechanism works only for the basic types.
11825 if (ArgVT == MVT::f80) {
11826 llvm_unreachable("va_arg for f80 not yet implemented");
11827 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11828 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11829 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11830 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11832 llvm_unreachable("Unhandled argument type in LowerVAARG");
11835 if (ArgMode == 2) {
11836 // Sanity Check: Make sure using fp_offset makes sense.
11837 assert(!DAG.getTarget().Options.UseSoftFloat &&
11838 !(DAG.getMachineFunction()
11839 .getFunction()->getAttributes()
11840 .hasAttribute(AttributeSet::FunctionIndex,
11841 Attribute::NoImplicitFloat)) &&
11842 Subtarget->hasSSE1());
11845 // Insert VAARG_64 node into the DAG
11846 // VAARG_64 returns two values: Variable Argument Address, Chain
11847 SmallVector<SDValue, 11> InstOps;
11848 InstOps.push_back(Chain);
11849 InstOps.push_back(SrcPtr);
11850 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11851 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11852 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11853 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11854 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11855 VTs, InstOps, MVT::i64,
11856 MachinePointerInfo(SV),
11858 /*Volatile=*/false,
11860 /*WriteMem=*/true);
11861 Chain = VAARG.getValue(1);
11863 // Load the next argument and return it
11864 return DAG.getLoad(ArgVT, dl,
11867 MachinePointerInfo(),
11868 false, false, false, 0);
11871 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11872 SelectionDAG &DAG) {
11873 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11874 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11875 SDValue Chain = Op.getOperand(0);
11876 SDValue DstPtr = Op.getOperand(1);
11877 SDValue SrcPtr = Op.getOperand(2);
11878 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11879 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11882 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11883 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11885 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11888 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11889 // amount is a constant. Takes immediate version of shift as input.
11890 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11891 SDValue SrcOp, uint64_t ShiftAmt,
11892 SelectionDAG &DAG) {
11893 MVT ElementType = VT.getVectorElementType();
11895 // Fold this packed shift into its first operand if ShiftAmt is 0.
11899 // Check for ShiftAmt >= element width
11900 if (ShiftAmt >= ElementType.getSizeInBits()) {
11901 if (Opc == X86ISD::VSRAI)
11902 ShiftAmt = ElementType.getSizeInBits() - 1;
11904 return DAG.getConstant(0, VT);
11907 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11908 && "Unknown target vector shift-by-constant node");
11910 // Fold this packed vector shift into a build vector if SrcOp is a
11911 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11912 if (VT == SrcOp.getSimpleValueType() &&
11913 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11914 SmallVector<SDValue, 8> Elts;
11915 unsigned NumElts = SrcOp->getNumOperands();
11916 ConstantSDNode *ND;
11919 default: llvm_unreachable(nullptr);
11920 case X86ISD::VSHLI:
11921 for (unsigned i=0; i!=NumElts; ++i) {
11922 SDValue CurrentOp = SrcOp->getOperand(i);
11923 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11924 Elts.push_back(CurrentOp);
11927 ND = cast<ConstantSDNode>(CurrentOp);
11928 const APInt &C = ND->getAPIntValue();
11929 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11932 case X86ISD::VSRLI:
11933 for (unsigned i=0; i!=NumElts; ++i) {
11934 SDValue CurrentOp = SrcOp->getOperand(i);
11935 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11936 Elts.push_back(CurrentOp);
11939 ND = cast<ConstantSDNode>(CurrentOp);
11940 const APInt &C = ND->getAPIntValue();
11941 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11944 case X86ISD::VSRAI:
11945 for (unsigned i=0; i!=NumElts; ++i) {
11946 SDValue CurrentOp = SrcOp->getOperand(i);
11947 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11948 Elts.push_back(CurrentOp);
11951 ND = cast<ConstantSDNode>(CurrentOp);
11952 const APInt &C = ND->getAPIntValue();
11953 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11958 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11961 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11964 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11965 // may or may not be a constant. Takes immediate version of shift as input.
11966 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11967 SDValue SrcOp, SDValue ShAmt,
11968 SelectionDAG &DAG) {
11969 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11971 // Catch shift-by-constant.
11972 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11973 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11974 CShAmt->getZExtValue(), DAG);
11976 // Change opcode to non-immediate version
11978 default: llvm_unreachable("Unknown target vector shift node");
11979 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11980 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11981 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11984 // Need to build a vector containing shift amount
11985 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11988 ShOps[1] = DAG.getConstant(0, MVT::i32);
11989 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11990 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11992 // The return type has to be a 128-bit type with the same element
11993 // type as the input type.
11994 MVT EltVT = VT.getVectorElementType();
11995 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11997 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11998 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12001 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12003 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12005 default: return SDValue(); // Don't custom lower most intrinsics.
12006 // Comparison intrinsics.
12007 case Intrinsic::x86_sse_comieq_ss:
12008 case Intrinsic::x86_sse_comilt_ss:
12009 case Intrinsic::x86_sse_comile_ss:
12010 case Intrinsic::x86_sse_comigt_ss:
12011 case Intrinsic::x86_sse_comige_ss:
12012 case Intrinsic::x86_sse_comineq_ss:
12013 case Intrinsic::x86_sse_ucomieq_ss:
12014 case Intrinsic::x86_sse_ucomilt_ss:
12015 case Intrinsic::x86_sse_ucomile_ss:
12016 case Intrinsic::x86_sse_ucomigt_ss:
12017 case Intrinsic::x86_sse_ucomige_ss:
12018 case Intrinsic::x86_sse_ucomineq_ss:
12019 case Intrinsic::x86_sse2_comieq_sd:
12020 case Intrinsic::x86_sse2_comilt_sd:
12021 case Intrinsic::x86_sse2_comile_sd:
12022 case Intrinsic::x86_sse2_comigt_sd:
12023 case Intrinsic::x86_sse2_comige_sd:
12024 case Intrinsic::x86_sse2_comineq_sd:
12025 case Intrinsic::x86_sse2_ucomieq_sd:
12026 case Intrinsic::x86_sse2_ucomilt_sd:
12027 case Intrinsic::x86_sse2_ucomile_sd:
12028 case Intrinsic::x86_sse2_ucomigt_sd:
12029 case Intrinsic::x86_sse2_ucomige_sd:
12030 case Intrinsic::x86_sse2_ucomineq_sd: {
12034 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12035 case Intrinsic::x86_sse_comieq_ss:
12036 case Intrinsic::x86_sse2_comieq_sd:
12037 Opc = X86ISD::COMI;
12040 case Intrinsic::x86_sse_comilt_ss:
12041 case Intrinsic::x86_sse2_comilt_sd:
12042 Opc = X86ISD::COMI;
12045 case Intrinsic::x86_sse_comile_ss:
12046 case Intrinsic::x86_sse2_comile_sd:
12047 Opc = X86ISD::COMI;
12050 case Intrinsic::x86_sse_comigt_ss:
12051 case Intrinsic::x86_sse2_comigt_sd:
12052 Opc = X86ISD::COMI;
12055 case Intrinsic::x86_sse_comige_ss:
12056 case Intrinsic::x86_sse2_comige_sd:
12057 Opc = X86ISD::COMI;
12060 case Intrinsic::x86_sse_comineq_ss:
12061 case Intrinsic::x86_sse2_comineq_sd:
12062 Opc = X86ISD::COMI;
12065 case Intrinsic::x86_sse_ucomieq_ss:
12066 case Intrinsic::x86_sse2_ucomieq_sd:
12067 Opc = X86ISD::UCOMI;
12070 case Intrinsic::x86_sse_ucomilt_ss:
12071 case Intrinsic::x86_sse2_ucomilt_sd:
12072 Opc = X86ISD::UCOMI;
12075 case Intrinsic::x86_sse_ucomile_ss:
12076 case Intrinsic::x86_sse2_ucomile_sd:
12077 Opc = X86ISD::UCOMI;
12080 case Intrinsic::x86_sse_ucomigt_ss:
12081 case Intrinsic::x86_sse2_ucomigt_sd:
12082 Opc = X86ISD::UCOMI;
12085 case Intrinsic::x86_sse_ucomige_ss:
12086 case Intrinsic::x86_sse2_ucomige_sd:
12087 Opc = X86ISD::UCOMI;
12090 case Intrinsic::x86_sse_ucomineq_ss:
12091 case Intrinsic::x86_sse2_ucomineq_sd:
12092 Opc = X86ISD::UCOMI;
12097 SDValue LHS = Op.getOperand(1);
12098 SDValue RHS = Op.getOperand(2);
12099 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12100 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12101 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12102 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12103 DAG.getConstant(X86CC, MVT::i8), Cond);
12104 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12107 // Arithmetic intrinsics.
12108 case Intrinsic::x86_sse2_pmulu_dq:
12109 case Intrinsic::x86_avx2_pmulu_dq:
12110 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12111 Op.getOperand(1), Op.getOperand(2));
12113 case Intrinsic::x86_sse41_pmuldq:
12114 case Intrinsic::x86_avx2_pmul_dq:
12115 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12116 Op.getOperand(1), Op.getOperand(2));
12118 case Intrinsic::x86_sse2_pmulhu_w:
12119 case Intrinsic::x86_avx2_pmulhu_w:
12120 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12121 Op.getOperand(1), Op.getOperand(2));
12123 case Intrinsic::x86_sse2_pmulh_w:
12124 case Intrinsic::x86_avx2_pmulh_w:
12125 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12126 Op.getOperand(1), Op.getOperand(2));
12128 // SSE2/AVX2 sub with unsigned saturation intrinsics
12129 case Intrinsic::x86_sse2_psubus_b:
12130 case Intrinsic::x86_sse2_psubus_w:
12131 case Intrinsic::x86_avx2_psubus_b:
12132 case Intrinsic::x86_avx2_psubus_w:
12133 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12134 Op.getOperand(1), Op.getOperand(2));
12136 // SSE3/AVX horizontal add/sub intrinsics
12137 case Intrinsic::x86_sse3_hadd_ps:
12138 case Intrinsic::x86_sse3_hadd_pd:
12139 case Intrinsic::x86_avx_hadd_ps_256:
12140 case Intrinsic::x86_avx_hadd_pd_256:
12141 case Intrinsic::x86_sse3_hsub_ps:
12142 case Intrinsic::x86_sse3_hsub_pd:
12143 case Intrinsic::x86_avx_hsub_ps_256:
12144 case Intrinsic::x86_avx_hsub_pd_256:
12145 case Intrinsic::x86_ssse3_phadd_w_128:
12146 case Intrinsic::x86_ssse3_phadd_d_128:
12147 case Intrinsic::x86_avx2_phadd_w:
12148 case Intrinsic::x86_avx2_phadd_d:
12149 case Intrinsic::x86_ssse3_phsub_w_128:
12150 case Intrinsic::x86_ssse3_phsub_d_128:
12151 case Intrinsic::x86_avx2_phsub_w:
12152 case Intrinsic::x86_avx2_phsub_d: {
12155 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12156 case Intrinsic::x86_sse3_hadd_ps:
12157 case Intrinsic::x86_sse3_hadd_pd:
12158 case Intrinsic::x86_avx_hadd_ps_256:
12159 case Intrinsic::x86_avx_hadd_pd_256:
12160 Opcode = X86ISD::FHADD;
12162 case Intrinsic::x86_sse3_hsub_ps:
12163 case Intrinsic::x86_sse3_hsub_pd:
12164 case Intrinsic::x86_avx_hsub_ps_256:
12165 case Intrinsic::x86_avx_hsub_pd_256:
12166 Opcode = X86ISD::FHSUB;
12168 case Intrinsic::x86_ssse3_phadd_w_128:
12169 case Intrinsic::x86_ssse3_phadd_d_128:
12170 case Intrinsic::x86_avx2_phadd_w:
12171 case Intrinsic::x86_avx2_phadd_d:
12172 Opcode = X86ISD::HADD;
12174 case Intrinsic::x86_ssse3_phsub_w_128:
12175 case Intrinsic::x86_ssse3_phsub_d_128:
12176 case Intrinsic::x86_avx2_phsub_w:
12177 case Intrinsic::x86_avx2_phsub_d:
12178 Opcode = X86ISD::HSUB;
12181 return DAG.getNode(Opcode, dl, Op.getValueType(),
12182 Op.getOperand(1), Op.getOperand(2));
12185 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12186 case Intrinsic::x86_sse2_pmaxu_b:
12187 case Intrinsic::x86_sse41_pmaxuw:
12188 case Intrinsic::x86_sse41_pmaxud:
12189 case Intrinsic::x86_avx2_pmaxu_b:
12190 case Intrinsic::x86_avx2_pmaxu_w:
12191 case Intrinsic::x86_avx2_pmaxu_d:
12192 case Intrinsic::x86_sse2_pminu_b:
12193 case Intrinsic::x86_sse41_pminuw:
12194 case Intrinsic::x86_sse41_pminud:
12195 case Intrinsic::x86_avx2_pminu_b:
12196 case Intrinsic::x86_avx2_pminu_w:
12197 case Intrinsic::x86_avx2_pminu_d:
12198 case Intrinsic::x86_sse41_pmaxsb:
12199 case Intrinsic::x86_sse2_pmaxs_w:
12200 case Intrinsic::x86_sse41_pmaxsd:
12201 case Intrinsic::x86_avx2_pmaxs_b:
12202 case Intrinsic::x86_avx2_pmaxs_w:
12203 case Intrinsic::x86_avx2_pmaxs_d:
12204 case Intrinsic::x86_sse41_pminsb:
12205 case Intrinsic::x86_sse2_pmins_w:
12206 case Intrinsic::x86_sse41_pminsd:
12207 case Intrinsic::x86_avx2_pmins_b:
12208 case Intrinsic::x86_avx2_pmins_w:
12209 case Intrinsic::x86_avx2_pmins_d: {
12212 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12213 case Intrinsic::x86_sse2_pmaxu_b:
12214 case Intrinsic::x86_sse41_pmaxuw:
12215 case Intrinsic::x86_sse41_pmaxud:
12216 case Intrinsic::x86_avx2_pmaxu_b:
12217 case Intrinsic::x86_avx2_pmaxu_w:
12218 case Intrinsic::x86_avx2_pmaxu_d:
12219 Opcode = X86ISD::UMAX;
12221 case Intrinsic::x86_sse2_pminu_b:
12222 case Intrinsic::x86_sse41_pminuw:
12223 case Intrinsic::x86_sse41_pminud:
12224 case Intrinsic::x86_avx2_pminu_b:
12225 case Intrinsic::x86_avx2_pminu_w:
12226 case Intrinsic::x86_avx2_pminu_d:
12227 Opcode = X86ISD::UMIN;
12229 case Intrinsic::x86_sse41_pmaxsb:
12230 case Intrinsic::x86_sse2_pmaxs_w:
12231 case Intrinsic::x86_sse41_pmaxsd:
12232 case Intrinsic::x86_avx2_pmaxs_b:
12233 case Intrinsic::x86_avx2_pmaxs_w:
12234 case Intrinsic::x86_avx2_pmaxs_d:
12235 Opcode = X86ISD::SMAX;
12237 case Intrinsic::x86_sse41_pminsb:
12238 case Intrinsic::x86_sse2_pmins_w:
12239 case Intrinsic::x86_sse41_pminsd:
12240 case Intrinsic::x86_avx2_pmins_b:
12241 case Intrinsic::x86_avx2_pmins_w:
12242 case Intrinsic::x86_avx2_pmins_d:
12243 Opcode = X86ISD::SMIN;
12246 return DAG.getNode(Opcode, dl, Op.getValueType(),
12247 Op.getOperand(1), Op.getOperand(2));
12250 // SSE/SSE2/AVX floating point max/min intrinsics.
12251 case Intrinsic::x86_sse_max_ps:
12252 case Intrinsic::x86_sse2_max_pd:
12253 case Intrinsic::x86_avx_max_ps_256:
12254 case Intrinsic::x86_avx_max_pd_256:
12255 case Intrinsic::x86_sse_min_ps:
12256 case Intrinsic::x86_sse2_min_pd:
12257 case Intrinsic::x86_avx_min_ps_256:
12258 case Intrinsic::x86_avx_min_pd_256: {
12261 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12262 case Intrinsic::x86_sse_max_ps:
12263 case Intrinsic::x86_sse2_max_pd:
12264 case Intrinsic::x86_avx_max_ps_256:
12265 case Intrinsic::x86_avx_max_pd_256:
12266 Opcode = X86ISD::FMAX;
12268 case Intrinsic::x86_sse_min_ps:
12269 case Intrinsic::x86_sse2_min_pd:
12270 case Intrinsic::x86_avx_min_ps_256:
12271 case Intrinsic::x86_avx_min_pd_256:
12272 Opcode = X86ISD::FMIN;
12275 return DAG.getNode(Opcode, dl, Op.getValueType(),
12276 Op.getOperand(1), Op.getOperand(2));
12279 // AVX2 variable shift intrinsics
12280 case Intrinsic::x86_avx2_psllv_d:
12281 case Intrinsic::x86_avx2_psllv_q:
12282 case Intrinsic::x86_avx2_psllv_d_256:
12283 case Intrinsic::x86_avx2_psllv_q_256:
12284 case Intrinsic::x86_avx2_psrlv_d:
12285 case Intrinsic::x86_avx2_psrlv_q:
12286 case Intrinsic::x86_avx2_psrlv_d_256:
12287 case Intrinsic::x86_avx2_psrlv_q_256:
12288 case Intrinsic::x86_avx2_psrav_d:
12289 case Intrinsic::x86_avx2_psrav_d_256: {
12292 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12293 case Intrinsic::x86_avx2_psllv_d:
12294 case Intrinsic::x86_avx2_psllv_q:
12295 case Intrinsic::x86_avx2_psllv_d_256:
12296 case Intrinsic::x86_avx2_psllv_q_256:
12299 case Intrinsic::x86_avx2_psrlv_d:
12300 case Intrinsic::x86_avx2_psrlv_q:
12301 case Intrinsic::x86_avx2_psrlv_d_256:
12302 case Intrinsic::x86_avx2_psrlv_q_256:
12305 case Intrinsic::x86_avx2_psrav_d:
12306 case Intrinsic::x86_avx2_psrav_d_256:
12310 return DAG.getNode(Opcode, dl, Op.getValueType(),
12311 Op.getOperand(1), Op.getOperand(2));
12314 case Intrinsic::x86_ssse3_pshuf_b_128:
12315 case Intrinsic::x86_avx2_pshuf_b:
12316 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12317 Op.getOperand(1), Op.getOperand(2));
12319 case Intrinsic::x86_ssse3_psign_b_128:
12320 case Intrinsic::x86_ssse3_psign_w_128:
12321 case Intrinsic::x86_ssse3_psign_d_128:
12322 case Intrinsic::x86_avx2_psign_b:
12323 case Intrinsic::x86_avx2_psign_w:
12324 case Intrinsic::x86_avx2_psign_d:
12325 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12326 Op.getOperand(1), Op.getOperand(2));
12328 case Intrinsic::x86_sse41_insertps:
12329 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12330 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12332 case Intrinsic::x86_avx_vperm2f128_ps_256:
12333 case Intrinsic::x86_avx_vperm2f128_pd_256:
12334 case Intrinsic::x86_avx_vperm2f128_si_256:
12335 case Intrinsic::x86_avx2_vperm2i128:
12336 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12337 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12339 case Intrinsic::x86_avx2_permd:
12340 case Intrinsic::x86_avx2_permps:
12341 // Operands intentionally swapped. Mask is last operand to intrinsic,
12342 // but second operand for node/instruction.
12343 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12344 Op.getOperand(2), Op.getOperand(1));
12346 case Intrinsic::x86_sse_sqrt_ps:
12347 case Intrinsic::x86_sse2_sqrt_pd:
12348 case Intrinsic::x86_avx_sqrt_ps_256:
12349 case Intrinsic::x86_avx_sqrt_pd_256:
12350 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12352 // ptest and testp intrinsics. The intrinsic these come from are designed to
12353 // return an integer value, not just an instruction so lower it to the ptest
12354 // or testp pattern and a setcc for the result.
12355 case Intrinsic::x86_sse41_ptestz:
12356 case Intrinsic::x86_sse41_ptestc:
12357 case Intrinsic::x86_sse41_ptestnzc:
12358 case Intrinsic::x86_avx_ptestz_256:
12359 case Intrinsic::x86_avx_ptestc_256:
12360 case Intrinsic::x86_avx_ptestnzc_256:
12361 case Intrinsic::x86_avx_vtestz_ps:
12362 case Intrinsic::x86_avx_vtestc_ps:
12363 case Intrinsic::x86_avx_vtestnzc_ps:
12364 case Intrinsic::x86_avx_vtestz_pd:
12365 case Intrinsic::x86_avx_vtestc_pd:
12366 case Intrinsic::x86_avx_vtestnzc_pd:
12367 case Intrinsic::x86_avx_vtestz_ps_256:
12368 case Intrinsic::x86_avx_vtestc_ps_256:
12369 case Intrinsic::x86_avx_vtestnzc_ps_256:
12370 case Intrinsic::x86_avx_vtestz_pd_256:
12371 case Intrinsic::x86_avx_vtestc_pd_256:
12372 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12373 bool IsTestPacked = false;
12376 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12377 case Intrinsic::x86_avx_vtestz_ps:
12378 case Intrinsic::x86_avx_vtestz_pd:
12379 case Intrinsic::x86_avx_vtestz_ps_256:
12380 case Intrinsic::x86_avx_vtestz_pd_256:
12381 IsTestPacked = true; // Fallthrough
12382 case Intrinsic::x86_sse41_ptestz:
12383 case Intrinsic::x86_avx_ptestz_256:
12385 X86CC = X86::COND_E;
12387 case Intrinsic::x86_avx_vtestc_ps:
12388 case Intrinsic::x86_avx_vtestc_pd:
12389 case Intrinsic::x86_avx_vtestc_ps_256:
12390 case Intrinsic::x86_avx_vtestc_pd_256:
12391 IsTestPacked = true; // Fallthrough
12392 case Intrinsic::x86_sse41_ptestc:
12393 case Intrinsic::x86_avx_ptestc_256:
12395 X86CC = X86::COND_B;
12397 case Intrinsic::x86_avx_vtestnzc_ps:
12398 case Intrinsic::x86_avx_vtestnzc_pd:
12399 case Intrinsic::x86_avx_vtestnzc_ps_256:
12400 case Intrinsic::x86_avx_vtestnzc_pd_256:
12401 IsTestPacked = true; // Fallthrough
12402 case Intrinsic::x86_sse41_ptestnzc:
12403 case Intrinsic::x86_avx_ptestnzc_256:
12405 X86CC = X86::COND_A;
12409 SDValue LHS = Op.getOperand(1);
12410 SDValue RHS = Op.getOperand(2);
12411 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12412 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12413 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12414 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12415 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12417 case Intrinsic::x86_avx512_kortestz_w:
12418 case Intrinsic::x86_avx512_kortestc_w: {
12419 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12420 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12421 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12422 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12423 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12424 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12425 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12428 // SSE/AVX shift intrinsics
12429 case Intrinsic::x86_sse2_psll_w:
12430 case Intrinsic::x86_sse2_psll_d:
12431 case Intrinsic::x86_sse2_psll_q:
12432 case Intrinsic::x86_avx2_psll_w:
12433 case Intrinsic::x86_avx2_psll_d:
12434 case Intrinsic::x86_avx2_psll_q:
12435 case Intrinsic::x86_sse2_psrl_w:
12436 case Intrinsic::x86_sse2_psrl_d:
12437 case Intrinsic::x86_sse2_psrl_q:
12438 case Intrinsic::x86_avx2_psrl_w:
12439 case Intrinsic::x86_avx2_psrl_d:
12440 case Intrinsic::x86_avx2_psrl_q:
12441 case Intrinsic::x86_sse2_psra_w:
12442 case Intrinsic::x86_sse2_psra_d:
12443 case Intrinsic::x86_avx2_psra_w:
12444 case Intrinsic::x86_avx2_psra_d: {
12447 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12448 case Intrinsic::x86_sse2_psll_w:
12449 case Intrinsic::x86_sse2_psll_d:
12450 case Intrinsic::x86_sse2_psll_q:
12451 case Intrinsic::x86_avx2_psll_w:
12452 case Intrinsic::x86_avx2_psll_d:
12453 case Intrinsic::x86_avx2_psll_q:
12454 Opcode = X86ISD::VSHL;
12456 case Intrinsic::x86_sse2_psrl_w:
12457 case Intrinsic::x86_sse2_psrl_d:
12458 case Intrinsic::x86_sse2_psrl_q:
12459 case Intrinsic::x86_avx2_psrl_w:
12460 case Intrinsic::x86_avx2_psrl_d:
12461 case Intrinsic::x86_avx2_psrl_q:
12462 Opcode = X86ISD::VSRL;
12464 case Intrinsic::x86_sse2_psra_w:
12465 case Intrinsic::x86_sse2_psra_d:
12466 case Intrinsic::x86_avx2_psra_w:
12467 case Intrinsic::x86_avx2_psra_d:
12468 Opcode = X86ISD::VSRA;
12471 return DAG.getNode(Opcode, dl, Op.getValueType(),
12472 Op.getOperand(1), Op.getOperand(2));
12475 // SSE/AVX immediate shift intrinsics
12476 case Intrinsic::x86_sse2_pslli_w:
12477 case Intrinsic::x86_sse2_pslli_d:
12478 case Intrinsic::x86_sse2_pslli_q:
12479 case Intrinsic::x86_avx2_pslli_w:
12480 case Intrinsic::x86_avx2_pslli_d:
12481 case Intrinsic::x86_avx2_pslli_q:
12482 case Intrinsic::x86_sse2_psrli_w:
12483 case Intrinsic::x86_sse2_psrli_d:
12484 case Intrinsic::x86_sse2_psrli_q:
12485 case Intrinsic::x86_avx2_psrli_w:
12486 case Intrinsic::x86_avx2_psrli_d:
12487 case Intrinsic::x86_avx2_psrli_q:
12488 case Intrinsic::x86_sse2_psrai_w:
12489 case Intrinsic::x86_sse2_psrai_d:
12490 case Intrinsic::x86_avx2_psrai_w:
12491 case Intrinsic::x86_avx2_psrai_d: {
12494 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12495 case Intrinsic::x86_sse2_pslli_w:
12496 case Intrinsic::x86_sse2_pslli_d:
12497 case Intrinsic::x86_sse2_pslli_q:
12498 case Intrinsic::x86_avx2_pslli_w:
12499 case Intrinsic::x86_avx2_pslli_d:
12500 case Intrinsic::x86_avx2_pslli_q:
12501 Opcode = X86ISD::VSHLI;
12503 case Intrinsic::x86_sse2_psrli_w:
12504 case Intrinsic::x86_sse2_psrli_d:
12505 case Intrinsic::x86_sse2_psrli_q:
12506 case Intrinsic::x86_avx2_psrli_w:
12507 case Intrinsic::x86_avx2_psrli_d:
12508 case Intrinsic::x86_avx2_psrli_q:
12509 Opcode = X86ISD::VSRLI;
12511 case Intrinsic::x86_sse2_psrai_w:
12512 case Intrinsic::x86_sse2_psrai_d:
12513 case Intrinsic::x86_avx2_psrai_w:
12514 case Intrinsic::x86_avx2_psrai_d:
12515 Opcode = X86ISD::VSRAI;
12518 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12519 Op.getOperand(1), Op.getOperand(2), DAG);
12522 case Intrinsic::x86_sse42_pcmpistria128:
12523 case Intrinsic::x86_sse42_pcmpestria128:
12524 case Intrinsic::x86_sse42_pcmpistric128:
12525 case Intrinsic::x86_sse42_pcmpestric128:
12526 case Intrinsic::x86_sse42_pcmpistrio128:
12527 case Intrinsic::x86_sse42_pcmpestrio128:
12528 case Intrinsic::x86_sse42_pcmpistris128:
12529 case Intrinsic::x86_sse42_pcmpestris128:
12530 case Intrinsic::x86_sse42_pcmpistriz128:
12531 case Intrinsic::x86_sse42_pcmpestriz128: {
12535 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12536 case Intrinsic::x86_sse42_pcmpistria128:
12537 Opcode = X86ISD::PCMPISTRI;
12538 X86CC = X86::COND_A;
12540 case Intrinsic::x86_sse42_pcmpestria128:
12541 Opcode = X86ISD::PCMPESTRI;
12542 X86CC = X86::COND_A;
12544 case Intrinsic::x86_sse42_pcmpistric128:
12545 Opcode = X86ISD::PCMPISTRI;
12546 X86CC = X86::COND_B;
12548 case Intrinsic::x86_sse42_pcmpestric128:
12549 Opcode = X86ISD::PCMPESTRI;
12550 X86CC = X86::COND_B;
12552 case Intrinsic::x86_sse42_pcmpistrio128:
12553 Opcode = X86ISD::PCMPISTRI;
12554 X86CC = X86::COND_O;
12556 case Intrinsic::x86_sse42_pcmpestrio128:
12557 Opcode = X86ISD::PCMPESTRI;
12558 X86CC = X86::COND_O;
12560 case Intrinsic::x86_sse42_pcmpistris128:
12561 Opcode = X86ISD::PCMPISTRI;
12562 X86CC = X86::COND_S;
12564 case Intrinsic::x86_sse42_pcmpestris128:
12565 Opcode = X86ISD::PCMPESTRI;
12566 X86CC = X86::COND_S;
12568 case Intrinsic::x86_sse42_pcmpistriz128:
12569 Opcode = X86ISD::PCMPISTRI;
12570 X86CC = X86::COND_E;
12572 case Intrinsic::x86_sse42_pcmpestriz128:
12573 Opcode = X86ISD::PCMPESTRI;
12574 X86CC = X86::COND_E;
12577 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12578 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12579 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12580 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12581 DAG.getConstant(X86CC, MVT::i8),
12582 SDValue(PCMP.getNode(), 1));
12583 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12586 case Intrinsic::x86_sse42_pcmpistri128:
12587 case Intrinsic::x86_sse42_pcmpestri128: {
12589 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12590 Opcode = X86ISD::PCMPISTRI;
12592 Opcode = X86ISD::PCMPESTRI;
12594 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12595 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12596 return DAG.getNode(Opcode, dl, VTs, NewOps);
12598 case Intrinsic::x86_fma_vfmadd_ps:
12599 case Intrinsic::x86_fma_vfmadd_pd:
12600 case Intrinsic::x86_fma_vfmsub_ps:
12601 case Intrinsic::x86_fma_vfmsub_pd:
12602 case Intrinsic::x86_fma_vfnmadd_ps:
12603 case Intrinsic::x86_fma_vfnmadd_pd:
12604 case Intrinsic::x86_fma_vfnmsub_ps:
12605 case Intrinsic::x86_fma_vfnmsub_pd:
12606 case Intrinsic::x86_fma_vfmaddsub_ps:
12607 case Intrinsic::x86_fma_vfmaddsub_pd:
12608 case Intrinsic::x86_fma_vfmsubadd_ps:
12609 case Intrinsic::x86_fma_vfmsubadd_pd:
12610 case Intrinsic::x86_fma_vfmadd_ps_256:
12611 case Intrinsic::x86_fma_vfmadd_pd_256:
12612 case Intrinsic::x86_fma_vfmsub_ps_256:
12613 case Intrinsic::x86_fma_vfmsub_pd_256:
12614 case Intrinsic::x86_fma_vfnmadd_ps_256:
12615 case Intrinsic::x86_fma_vfnmadd_pd_256:
12616 case Intrinsic::x86_fma_vfnmsub_ps_256:
12617 case Intrinsic::x86_fma_vfnmsub_pd_256:
12618 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12619 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12620 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12621 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12622 case Intrinsic::x86_fma_vfmadd_ps_512:
12623 case Intrinsic::x86_fma_vfmadd_pd_512:
12624 case Intrinsic::x86_fma_vfmsub_ps_512:
12625 case Intrinsic::x86_fma_vfmsub_pd_512:
12626 case Intrinsic::x86_fma_vfnmadd_ps_512:
12627 case Intrinsic::x86_fma_vfnmadd_pd_512:
12628 case Intrinsic::x86_fma_vfnmsub_ps_512:
12629 case Intrinsic::x86_fma_vfnmsub_pd_512:
12630 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12631 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12632 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12633 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12636 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12637 case Intrinsic::x86_fma_vfmadd_ps:
12638 case Intrinsic::x86_fma_vfmadd_pd:
12639 case Intrinsic::x86_fma_vfmadd_ps_256:
12640 case Intrinsic::x86_fma_vfmadd_pd_256:
12641 case Intrinsic::x86_fma_vfmadd_ps_512:
12642 case Intrinsic::x86_fma_vfmadd_pd_512:
12643 Opc = X86ISD::FMADD;
12645 case Intrinsic::x86_fma_vfmsub_ps:
12646 case Intrinsic::x86_fma_vfmsub_pd:
12647 case Intrinsic::x86_fma_vfmsub_ps_256:
12648 case Intrinsic::x86_fma_vfmsub_pd_256:
12649 case Intrinsic::x86_fma_vfmsub_ps_512:
12650 case Intrinsic::x86_fma_vfmsub_pd_512:
12651 Opc = X86ISD::FMSUB;
12653 case Intrinsic::x86_fma_vfnmadd_ps:
12654 case Intrinsic::x86_fma_vfnmadd_pd:
12655 case Intrinsic::x86_fma_vfnmadd_ps_256:
12656 case Intrinsic::x86_fma_vfnmadd_pd_256:
12657 case Intrinsic::x86_fma_vfnmadd_ps_512:
12658 case Intrinsic::x86_fma_vfnmadd_pd_512:
12659 Opc = X86ISD::FNMADD;
12661 case Intrinsic::x86_fma_vfnmsub_ps:
12662 case Intrinsic::x86_fma_vfnmsub_pd:
12663 case Intrinsic::x86_fma_vfnmsub_ps_256:
12664 case Intrinsic::x86_fma_vfnmsub_pd_256:
12665 case Intrinsic::x86_fma_vfnmsub_ps_512:
12666 case Intrinsic::x86_fma_vfnmsub_pd_512:
12667 Opc = X86ISD::FNMSUB;
12669 case Intrinsic::x86_fma_vfmaddsub_ps:
12670 case Intrinsic::x86_fma_vfmaddsub_pd:
12671 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12672 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12673 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12674 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12675 Opc = X86ISD::FMADDSUB;
12677 case Intrinsic::x86_fma_vfmsubadd_ps:
12678 case Intrinsic::x86_fma_vfmsubadd_pd:
12679 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12680 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12681 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12682 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12683 Opc = X86ISD::FMSUBADD;
12687 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12688 Op.getOperand(2), Op.getOperand(3));
12693 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12694 SDValue Src, SDValue Mask, SDValue Base,
12695 SDValue Index, SDValue ScaleOp, SDValue Chain,
12696 const X86Subtarget * Subtarget) {
12698 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12699 assert(C && "Invalid scale type");
12700 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12701 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12702 Index.getSimpleValueType().getVectorNumElements());
12704 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12706 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12708 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12709 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12710 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12711 SDValue Segment = DAG.getRegister(0, MVT::i32);
12712 if (Src.getOpcode() == ISD::UNDEF)
12713 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12714 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12715 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12716 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12717 return DAG.getMergeValues(RetOps, dl);
12720 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12721 SDValue Src, SDValue Mask, SDValue Base,
12722 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12724 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12725 assert(C && "Invalid scale type");
12726 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12727 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12728 SDValue Segment = DAG.getRegister(0, MVT::i32);
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(MaskVT, MVT::Other);
12738 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12739 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12740 return SDValue(Res, 1);
12743 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12744 SDValue Mask, SDValue Base, SDValue Index,
12745 SDValue ScaleOp, SDValue Chain) {
12747 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12748 assert(C && "Invalid scale type");
12749 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12750 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12751 SDValue Segment = DAG.getRegister(0, MVT::i32);
12753 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12755 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12757 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12759 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12760 //SDVTList VTs = DAG.getVTList(MVT::Other);
12761 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12762 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12763 return SDValue(Res, 0);
12766 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12767 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12768 // also used to custom lower READCYCLECOUNTER nodes.
12769 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12770 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12771 SmallVectorImpl<SDValue> &Results) {
12772 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12773 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12776 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12777 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12778 // and the EAX register is loaded with the low-order 32 bits.
12779 if (Subtarget->is64Bit()) {
12780 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12781 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12784 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12785 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12788 SDValue Chain = HI.getValue(1);
12790 if (Opcode == X86ISD::RDTSCP_DAG) {
12791 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12793 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12794 // the ECX register. Add 'ecx' explicitly to the chain.
12795 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12797 // Explicitly store the content of ECX at the location passed in input
12798 // to the 'rdtscp' intrinsic.
12799 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12800 MachinePointerInfo(), false, false, 0);
12803 if (Subtarget->is64Bit()) {
12804 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12805 // the EAX register is loaded with the low-order 32 bits.
12806 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12807 DAG.getConstant(32, MVT::i8));
12808 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12809 Results.push_back(Chain);
12813 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12814 SDValue Ops[] = { LO, HI };
12815 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12816 Results.push_back(Pair);
12817 Results.push_back(Chain);
12820 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12821 SelectionDAG &DAG) {
12822 SmallVector<SDValue, 2> Results;
12824 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12826 return DAG.getMergeValues(Results, DL);
12829 enum IntrinsicType {
12830 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12833 struct IntrinsicData {
12834 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12835 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12836 IntrinsicType Type;
12841 std::map < unsigned, IntrinsicData> IntrMap;
12842 static void InitIntinsicsMap() {
12843 static bool Initialized = false;
12846 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12847 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12848 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12849 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12850 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12851 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12852 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12853 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12854 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12855 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12856 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
12857 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12858 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
12859 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12860 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
12861 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12862 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
12863 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12865 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12866 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12867 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
12868 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12869 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
12870 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12871 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
12872 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12873 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
12874 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12875 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
12876 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12877 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
12878 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12879 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
12880 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12882 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
12883 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12884 X86::VGATHERPF1QPSm)));
12885 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
12886 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12887 X86::VGATHERPF1QPDm)));
12888 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
12889 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12890 X86::VGATHERPF1DPDm)));
12891 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
12892 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12893 X86::VGATHERPF1DPSm)));
12894 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
12895 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12896 X86::VSCATTERPF1QPSm)));
12897 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
12898 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12899 X86::VSCATTERPF1QPDm)));
12900 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
12901 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12902 X86::VSCATTERPF1DPDm)));
12903 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
12904 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12905 X86::VSCATTERPF1DPSm)));
12906 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12907 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12908 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12909 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12910 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12911 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12912 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12913 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12914 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12915 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12916 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12917 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12918 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12919 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
12920 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12921 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
12922 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12923 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
12924 Initialized = true;
12927 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12928 SelectionDAG &DAG) {
12929 InitIntinsicsMap();
12930 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12931 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12932 if (itr == IntrMap.end())
12936 IntrinsicData Intr = itr->second;
12937 switch(Intr.Type) {
12940 // Emit the node with the right value type.
12941 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12942 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12944 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12945 // Otherwise return the value from Rand, which is always 0, casted to i32.
12946 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12947 DAG.getConstant(1, Op->getValueType(1)),
12948 DAG.getConstant(X86::COND_B, MVT::i32),
12949 SDValue(Result.getNode(), 1) };
12950 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12951 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12954 // Return { result, isValid, chain }.
12955 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12956 SDValue(Result.getNode(), 2));
12959 //gather(v1, mask, index, base, scale);
12960 SDValue Chain = Op.getOperand(0);
12961 SDValue Src = Op.getOperand(2);
12962 SDValue Base = Op.getOperand(3);
12963 SDValue Index = Op.getOperand(4);
12964 SDValue Mask = Op.getOperand(5);
12965 SDValue Scale = Op.getOperand(6);
12966 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12970 //scatter(base, mask, index, v1, scale);
12971 SDValue Chain = Op.getOperand(0);
12972 SDValue Base = Op.getOperand(2);
12973 SDValue Mask = Op.getOperand(3);
12974 SDValue Index = Op.getOperand(4);
12975 SDValue Src = Op.getOperand(5);
12976 SDValue Scale = Op.getOperand(6);
12977 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12980 SDValue Hint = Op.getOperand(6);
12982 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
12983 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12984 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12985 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12986 SDValue Chain = Op.getOperand(0);
12987 SDValue Mask = Op.getOperand(2);
12988 SDValue Index = Op.getOperand(3);
12989 SDValue Base = Op.getOperand(4);
12990 SDValue Scale = Op.getOperand(5);
12991 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12993 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12995 SmallVector<SDValue, 2> Results;
12996 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12997 return DAG.getMergeValues(Results, dl);
12999 // XTEST intrinsics.
13001 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13002 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13003 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13004 DAG.getConstant(X86::COND_NE, MVT::i8),
13006 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13007 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13008 Ret, SDValue(InTrans.getNode(), 1));
13011 llvm_unreachable("Unknown Intrinsic Type");
13014 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13015 SelectionDAG &DAG) const {
13016 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13017 MFI->setReturnAddressIsTaken(true);
13019 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13022 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13024 EVT PtrVT = getPointerTy();
13027 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13028 const X86RegisterInfo *RegInfo =
13029 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13030 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13031 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13032 DAG.getNode(ISD::ADD, dl, PtrVT,
13033 FrameAddr, Offset),
13034 MachinePointerInfo(), false, false, false, 0);
13037 // Just load the return address.
13038 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13039 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13040 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13043 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13044 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13045 MFI->setFrameAddressIsTaken(true);
13047 EVT VT = Op.getValueType();
13048 SDLoc dl(Op); // FIXME probably not meaningful
13049 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13050 const X86RegisterInfo *RegInfo =
13051 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13052 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13053 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13054 (FrameReg == X86::EBP && VT == MVT::i32)) &&
13055 "Invalid Frame Register!");
13056 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13058 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13059 MachinePointerInfo(),
13060 false, false, false, 0);
13064 // FIXME? Maybe this could be a TableGen attribute on some registers and
13065 // this table could be generated automatically from RegInfo.
13066 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13068 unsigned Reg = StringSwitch<unsigned>(RegName)
13069 .Case("esp", X86::ESP)
13070 .Case("rsp", X86::RSP)
13074 report_fatal_error("Invalid register name global variable");
13077 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13078 SelectionDAG &DAG) const {
13079 const X86RegisterInfo *RegInfo =
13080 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13081 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13084 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13085 SDValue Chain = Op.getOperand(0);
13086 SDValue Offset = Op.getOperand(1);
13087 SDValue Handler = Op.getOperand(2);
13090 EVT PtrVT = getPointerTy();
13091 const X86RegisterInfo *RegInfo =
13092 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13093 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13094 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13095 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13096 "Invalid Frame Register!");
13097 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13098 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13100 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13101 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13102 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13103 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13105 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13107 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13108 DAG.getRegister(StoreAddrReg, PtrVT));
13111 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13112 SelectionDAG &DAG) const {
13114 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13115 DAG.getVTList(MVT::i32, MVT::Other),
13116 Op.getOperand(0), Op.getOperand(1));
13119 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13120 SelectionDAG &DAG) const {
13122 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13123 Op.getOperand(0), Op.getOperand(1));
13126 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13127 return Op.getOperand(0);
13130 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13131 SelectionDAG &DAG) const {
13132 SDValue Root = Op.getOperand(0);
13133 SDValue Trmp = Op.getOperand(1); // trampoline
13134 SDValue FPtr = Op.getOperand(2); // nested function
13135 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13138 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13139 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13141 if (Subtarget->is64Bit()) {
13142 SDValue OutChains[6];
13144 // Large code-model.
13145 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13146 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13148 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13149 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13151 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13153 // Load the pointer to the nested function into R11.
13154 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13155 SDValue Addr = Trmp;
13156 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13157 Addr, MachinePointerInfo(TrmpAddr),
13160 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13161 DAG.getConstant(2, MVT::i64));
13162 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13163 MachinePointerInfo(TrmpAddr, 2),
13166 // Load the 'nest' parameter value into R10.
13167 // R10 is specified in X86CallingConv.td
13168 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13169 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13170 DAG.getConstant(10, MVT::i64));
13171 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13172 Addr, MachinePointerInfo(TrmpAddr, 10),
13175 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13176 DAG.getConstant(12, MVT::i64));
13177 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13178 MachinePointerInfo(TrmpAddr, 12),
13181 // Jump to the nested function.
13182 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13183 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13184 DAG.getConstant(20, MVT::i64));
13185 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13186 Addr, MachinePointerInfo(TrmpAddr, 20),
13189 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13190 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13191 DAG.getConstant(22, MVT::i64));
13192 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13193 MachinePointerInfo(TrmpAddr, 22),
13196 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13198 const Function *Func =
13199 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13200 CallingConv::ID CC = Func->getCallingConv();
13205 llvm_unreachable("Unsupported calling convention");
13206 case CallingConv::C:
13207 case CallingConv::X86_StdCall: {
13208 // Pass 'nest' parameter in ECX.
13209 // Must be kept in sync with X86CallingConv.td
13210 NestReg = X86::ECX;
13212 // Check that ECX wasn't needed by an 'inreg' parameter.
13213 FunctionType *FTy = Func->getFunctionType();
13214 const AttributeSet &Attrs = Func->getAttributes();
13216 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13217 unsigned InRegCount = 0;
13220 for (FunctionType::param_iterator I = FTy->param_begin(),
13221 E = FTy->param_end(); I != E; ++I, ++Idx)
13222 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13223 // FIXME: should only count parameters that are lowered to integers.
13224 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13226 if (InRegCount > 2) {
13227 report_fatal_error("Nest register in use - reduce number of inreg"
13233 case CallingConv::X86_FastCall:
13234 case CallingConv::X86_ThisCall:
13235 case CallingConv::Fast:
13236 // Pass 'nest' parameter in EAX.
13237 // Must be kept in sync with X86CallingConv.td
13238 NestReg = X86::EAX;
13242 SDValue OutChains[4];
13243 SDValue Addr, Disp;
13245 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13246 DAG.getConstant(10, MVT::i32));
13247 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13249 // This is storing the opcode for MOV32ri.
13250 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13251 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13252 OutChains[0] = DAG.getStore(Root, dl,
13253 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13254 Trmp, MachinePointerInfo(TrmpAddr),
13257 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13258 DAG.getConstant(1, MVT::i32));
13259 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13260 MachinePointerInfo(TrmpAddr, 1),
13263 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13264 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13265 DAG.getConstant(5, MVT::i32));
13266 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13267 MachinePointerInfo(TrmpAddr, 5),
13270 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13271 DAG.getConstant(6, MVT::i32));
13272 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13273 MachinePointerInfo(TrmpAddr, 6),
13276 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13280 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13281 SelectionDAG &DAG) const {
13283 The rounding mode is in bits 11:10 of FPSR, and has the following
13285 00 Round to nearest
13290 FLT_ROUNDS, on the other hand, expects the following:
13297 To perform the conversion, we do:
13298 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13301 MachineFunction &MF = DAG.getMachineFunction();
13302 const TargetMachine &TM = MF.getTarget();
13303 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13304 unsigned StackAlignment = TFI.getStackAlignment();
13305 MVT VT = Op.getSimpleValueType();
13308 // Save FP Control Word to stack slot
13309 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13310 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13312 MachineMemOperand *MMO =
13313 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13314 MachineMemOperand::MOStore, 2, 2);
13316 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13317 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13318 DAG.getVTList(MVT::Other),
13319 Ops, MVT::i16, MMO);
13321 // Load FP Control Word from stack slot
13322 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13323 MachinePointerInfo(), false, false, false, 0);
13325 // Transform as necessary
13327 DAG.getNode(ISD::SRL, DL, MVT::i16,
13328 DAG.getNode(ISD::AND, DL, MVT::i16,
13329 CWD, DAG.getConstant(0x800, MVT::i16)),
13330 DAG.getConstant(11, MVT::i8));
13332 DAG.getNode(ISD::SRL, DL, MVT::i16,
13333 DAG.getNode(ISD::AND, DL, MVT::i16,
13334 CWD, DAG.getConstant(0x400, MVT::i16)),
13335 DAG.getConstant(9, MVT::i8));
13338 DAG.getNode(ISD::AND, DL, MVT::i16,
13339 DAG.getNode(ISD::ADD, DL, MVT::i16,
13340 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13341 DAG.getConstant(1, MVT::i16)),
13342 DAG.getConstant(3, MVT::i16));
13344 return DAG.getNode((VT.getSizeInBits() < 16 ?
13345 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13348 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13349 MVT VT = Op.getSimpleValueType();
13351 unsigned NumBits = VT.getSizeInBits();
13354 Op = Op.getOperand(0);
13355 if (VT == MVT::i8) {
13356 // Zero extend to i32 since there is not an i8 bsr.
13358 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13361 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13362 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13363 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13365 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13368 DAG.getConstant(NumBits+NumBits-1, OpVT),
13369 DAG.getConstant(X86::COND_E, MVT::i8),
13372 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13374 // Finally xor with NumBits-1.
13375 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13378 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13382 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13383 MVT VT = Op.getSimpleValueType();
13385 unsigned NumBits = VT.getSizeInBits();
13388 Op = Op.getOperand(0);
13389 if (VT == MVT::i8) {
13390 // Zero extend to i32 since there is not an i8 bsr.
13392 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13395 // Issue a bsr (scan bits in reverse).
13396 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13397 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13399 // And xor with NumBits-1.
13400 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13403 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13407 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13408 MVT VT = Op.getSimpleValueType();
13409 unsigned NumBits = VT.getSizeInBits();
13411 Op = Op.getOperand(0);
13413 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13414 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13415 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13417 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13420 DAG.getConstant(NumBits, VT),
13421 DAG.getConstant(X86::COND_E, MVT::i8),
13424 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13427 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13428 // ones, and then concatenate the result back.
13429 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13430 MVT VT = Op.getSimpleValueType();
13432 assert(VT.is256BitVector() && VT.isInteger() &&
13433 "Unsupported value type for operation");
13435 unsigned NumElems = VT.getVectorNumElements();
13438 // Extract the LHS vectors
13439 SDValue LHS = Op.getOperand(0);
13440 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13441 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13443 // Extract the RHS vectors
13444 SDValue RHS = Op.getOperand(1);
13445 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13446 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13448 MVT EltVT = VT.getVectorElementType();
13449 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13451 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13452 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13453 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13456 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13457 assert(Op.getSimpleValueType().is256BitVector() &&
13458 Op.getSimpleValueType().isInteger() &&
13459 "Only handle AVX 256-bit vector integer operation");
13460 return Lower256IntArith(Op, DAG);
13463 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13464 assert(Op.getSimpleValueType().is256BitVector() &&
13465 Op.getSimpleValueType().isInteger() &&
13466 "Only handle AVX 256-bit vector integer operation");
13467 return Lower256IntArith(Op, DAG);
13470 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13471 SelectionDAG &DAG) {
13473 MVT VT = Op.getSimpleValueType();
13475 // Decompose 256-bit ops into smaller 128-bit ops.
13476 if (VT.is256BitVector() && !Subtarget->hasInt256())
13477 return Lower256IntArith(Op, DAG);
13479 SDValue A = Op.getOperand(0);
13480 SDValue B = Op.getOperand(1);
13482 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13483 if (VT == MVT::v4i32) {
13484 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13485 "Should not custom lower when pmuldq is available!");
13487 // Extract the odd parts.
13488 static const int UnpackMask[] = { 1, -1, 3, -1 };
13489 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13490 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13492 // Multiply the even parts.
13493 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13494 // Now multiply odd parts.
13495 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13497 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13498 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13500 // Merge the two vectors back together with a shuffle. This expands into 2
13502 static const int ShufMask[] = { 0, 4, 2, 6 };
13503 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13506 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13507 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13509 // Ahi = psrlqi(a, 32);
13510 // Bhi = psrlqi(b, 32);
13512 // AloBlo = pmuludq(a, b);
13513 // AloBhi = pmuludq(a, Bhi);
13514 // AhiBlo = pmuludq(Ahi, b);
13516 // AloBhi = psllqi(AloBhi, 32);
13517 // AhiBlo = psllqi(AhiBlo, 32);
13518 // return AloBlo + AloBhi + AhiBlo;
13520 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13521 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13523 // Bit cast to 32-bit vectors for MULUDQ
13524 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13525 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13526 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13527 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13528 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13529 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13531 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13532 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13533 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13535 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13536 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13538 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13539 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13542 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13543 assert(Subtarget->isTargetWin64() && "Unexpected target");
13544 EVT VT = Op.getValueType();
13545 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13546 "Unexpected return type for lowering");
13550 switch (Op->getOpcode()) {
13551 default: llvm_unreachable("Unexpected request for libcall!");
13552 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13553 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13554 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13555 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13556 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13557 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13561 SDValue InChain = DAG.getEntryNode();
13563 TargetLowering::ArgListTy Args;
13564 TargetLowering::ArgListEntry Entry;
13565 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13566 EVT ArgVT = Op->getOperand(i).getValueType();
13567 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13568 "Unexpected argument type for lowering");
13569 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13570 Entry.Node = StackPtr;
13571 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13573 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13574 Entry.Ty = PointerType::get(ArgTy,0);
13575 Entry.isSExt = false;
13576 Entry.isZExt = false;
13577 Args.push_back(Entry);
13580 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13583 TargetLowering::CallLoweringInfo CLI(DAG);
13584 CLI.setDebugLoc(dl).setChain(InChain)
13585 .setCallee(getLibcallCallingConv(LC),
13586 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13588 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13590 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13591 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13594 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13595 SelectionDAG &DAG) {
13596 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13597 EVT VT = Op0.getValueType();
13600 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13601 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13603 // Get the high parts.
13604 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13605 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13606 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13608 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13610 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13611 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13613 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13614 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13615 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13616 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13617 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13619 // Shuffle it back into the right order.
13620 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13621 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13622 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13623 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13625 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13626 // unsigned multiply.
13627 if (IsSigned && !Subtarget->hasSSE41()) {
13629 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13630 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13631 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13632 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13633 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13635 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13636 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13639 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13642 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13643 const X86Subtarget *Subtarget) {
13644 MVT VT = Op.getSimpleValueType();
13646 SDValue R = Op.getOperand(0);
13647 SDValue Amt = Op.getOperand(1);
13649 // Optimize shl/srl/sra with constant shift amount.
13650 if (isSplatVector(Amt.getNode())) {
13651 SDValue SclrAmt = Amt->getOperand(0);
13652 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13653 uint64_t ShiftAmt = C->getZExtValue();
13655 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13656 (Subtarget->hasInt256() &&
13657 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13658 (Subtarget->hasAVX512() &&
13659 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13660 if (Op.getOpcode() == ISD::SHL)
13661 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13663 if (Op.getOpcode() == ISD::SRL)
13664 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13666 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13667 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13671 if (VT == MVT::v16i8) {
13672 if (Op.getOpcode() == ISD::SHL) {
13673 // Make a large shift.
13674 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13675 MVT::v8i16, R, ShiftAmt,
13677 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13678 // Zero out the rightmost bits.
13679 SmallVector<SDValue, 16> V(16,
13680 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13682 return DAG.getNode(ISD::AND, dl, VT, SHL,
13683 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13685 if (Op.getOpcode() == ISD::SRL) {
13686 // Make a large shift.
13687 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13688 MVT::v8i16, R, ShiftAmt,
13690 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13691 // Zero out the leftmost bits.
13692 SmallVector<SDValue, 16> V(16,
13693 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13695 return DAG.getNode(ISD::AND, dl, VT, SRL,
13696 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13698 if (Op.getOpcode() == ISD::SRA) {
13699 if (ShiftAmt == 7) {
13700 // R s>> 7 === R s< 0
13701 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13702 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13705 // R s>> a === ((R u>> a) ^ m) - m
13706 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13707 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13709 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13710 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13711 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13714 llvm_unreachable("Unknown shift opcode.");
13717 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13718 if (Op.getOpcode() == ISD::SHL) {
13719 // Make a large shift.
13720 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13721 MVT::v16i16, R, ShiftAmt,
13723 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13724 // Zero out the rightmost bits.
13725 SmallVector<SDValue, 32> V(32,
13726 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13728 return DAG.getNode(ISD::AND, dl, VT, SHL,
13729 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13731 if (Op.getOpcode() == ISD::SRL) {
13732 // Make a large shift.
13733 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13734 MVT::v16i16, R, ShiftAmt,
13736 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13737 // Zero out the leftmost bits.
13738 SmallVector<SDValue, 32> V(32,
13739 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13741 return DAG.getNode(ISD::AND, dl, VT, SRL,
13742 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13744 if (Op.getOpcode() == ISD::SRA) {
13745 if (ShiftAmt == 7) {
13746 // R s>> 7 === R s< 0
13747 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13748 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13751 // R s>> a === ((R u>> a) ^ m) - m
13752 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13753 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13755 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13756 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13757 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13760 llvm_unreachable("Unknown shift opcode.");
13765 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13766 if (!Subtarget->is64Bit() &&
13767 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13768 Amt.getOpcode() == ISD::BITCAST &&
13769 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13770 Amt = Amt.getOperand(0);
13771 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13772 VT.getVectorNumElements();
13773 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13774 uint64_t ShiftAmt = 0;
13775 for (unsigned i = 0; i != Ratio; ++i) {
13776 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13780 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13782 // Check remaining shift amounts.
13783 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13784 uint64_t ShAmt = 0;
13785 for (unsigned j = 0; j != Ratio; ++j) {
13786 ConstantSDNode *C =
13787 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13791 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13793 if (ShAmt != ShiftAmt)
13796 switch (Op.getOpcode()) {
13798 llvm_unreachable("Unknown shift opcode!");
13800 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13803 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13806 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13814 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13815 const X86Subtarget* Subtarget) {
13816 MVT VT = Op.getSimpleValueType();
13818 SDValue R = Op.getOperand(0);
13819 SDValue Amt = Op.getOperand(1);
13821 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13822 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13823 (Subtarget->hasInt256() &&
13824 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13825 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13826 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13828 EVT EltVT = VT.getVectorElementType();
13830 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13831 unsigned NumElts = VT.getVectorNumElements();
13833 for (i = 0; i != NumElts; ++i) {
13834 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13838 for (j = i; j != NumElts; ++j) {
13839 SDValue Arg = Amt.getOperand(j);
13840 if (Arg.getOpcode() == ISD::UNDEF) continue;
13841 if (Arg != Amt.getOperand(i))
13844 if (i != NumElts && j == NumElts)
13845 BaseShAmt = Amt.getOperand(i);
13847 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13848 Amt = Amt.getOperand(0);
13849 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13850 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13851 SDValue InVec = Amt.getOperand(0);
13852 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13853 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13855 for (; i != NumElts; ++i) {
13856 SDValue Arg = InVec.getOperand(i);
13857 if (Arg.getOpcode() == ISD::UNDEF) continue;
13861 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13862 if (ConstantSDNode *C =
13863 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13864 unsigned SplatIdx =
13865 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13866 if (C->getZExtValue() == SplatIdx)
13867 BaseShAmt = InVec.getOperand(1);
13870 if (!BaseShAmt.getNode())
13871 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13872 DAG.getIntPtrConstant(0));
13876 if (BaseShAmt.getNode()) {
13877 if (EltVT.bitsGT(MVT::i32))
13878 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13879 else if (EltVT.bitsLT(MVT::i32))
13880 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13882 switch (Op.getOpcode()) {
13884 llvm_unreachable("Unknown shift opcode!");
13886 switch (VT.SimpleTy) {
13887 default: return SDValue();
13896 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13899 switch (VT.SimpleTy) {
13900 default: return SDValue();
13907 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13910 switch (VT.SimpleTy) {
13911 default: return SDValue();
13920 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13926 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13927 if (!Subtarget->is64Bit() &&
13928 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13929 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13930 Amt.getOpcode() == ISD::BITCAST &&
13931 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13932 Amt = Amt.getOperand(0);
13933 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13934 VT.getVectorNumElements();
13935 std::vector<SDValue> Vals(Ratio);
13936 for (unsigned i = 0; i != Ratio; ++i)
13937 Vals[i] = Amt.getOperand(i);
13938 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13939 for (unsigned j = 0; j != Ratio; ++j)
13940 if (Vals[j] != Amt.getOperand(i + j))
13943 switch (Op.getOpcode()) {
13945 llvm_unreachable("Unknown shift opcode!");
13947 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13949 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13951 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13958 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13959 SelectionDAG &DAG) {
13961 MVT VT = Op.getSimpleValueType();
13963 SDValue R = Op.getOperand(0);
13964 SDValue Amt = Op.getOperand(1);
13967 if (!Subtarget->hasSSE2())
13970 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13974 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13978 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13980 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13981 if (Subtarget->hasInt256()) {
13982 if (Op.getOpcode() == ISD::SRL &&
13983 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13984 VT == MVT::v4i64 || VT == MVT::v8i32))
13986 if (Op.getOpcode() == ISD::SHL &&
13987 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13988 VT == MVT::v4i64 || VT == MVT::v8i32))
13990 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13994 // If possible, lower this packed shift into a vector multiply instead of
13995 // expanding it into a sequence of scalar shifts.
13996 // Do this only if the vector shift count is a constant build_vector.
13997 if (Op.getOpcode() == ISD::SHL &&
13998 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13999 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14000 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14001 SmallVector<SDValue, 8> Elts;
14002 EVT SVT = VT.getScalarType();
14003 unsigned SVTBits = SVT.getSizeInBits();
14004 const APInt &One = APInt(SVTBits, 1);
14005 unsigned NumElems = VT.getVectorNumElements();
14007 for (unsigned i=0; i !=NumElems; ++i) {
14008 SDValue Op = Amt->getOperand(i);
14009 if (Op->getOpcode() == ISD::UNDEF) {
14010 Elts.push_back(Op);
14014 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14015 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14016 uint64_t ShAmt = C.getZExtValue();
14017 if (ShAmt >= SVTBits) {
14018 Elts.push_back(DAG.getUNDEF(SVT));
14021 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14023 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14024 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14027 // Lower SHL with variable shift amount.
14028 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14029 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14031 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14032 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14033 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14034 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14037 // If possible, lower this shift as a sequence of two shifts by
14038 // constant plus a MOVSS/MOVSD instead of scalarizing it.
14040 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14042 // Could be rewritten as:
14043 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14045 // The advantage is that the two shifts from the example would be
14046 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14047 // the vector shift into four scalar shifts plus four pairs of vector
14049 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14050 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14051 unsigned TargetOpcode = X86ISD::MOVSS;
14052 bool CanBeSimplified;
14053 // The splat value for the first packed shift (the 'X' from the example).
14054 SDValue Amt1 = Amt->getOperand(0);
14055 // The splat value for the second packed shift (the 'Y' from the example).
14056 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14057 Amt->getOperand(2);
14059 // See if it is possible to replace this node with a sequence of
14060 // two shifts followed by a MOVSS/MOVSD
14061 if (VT == MVT::v4i32) {
14062 // Check if it is legal to use a MOVSS.
14063 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14064 Amt2 == Amt->getOperand(3);
14065 if (!CanBeSimplified) {
14066 // Otherwise, check if we can still simplify this node using a MOVSD.
14067 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14068 Amt->getOperand(2) == Amt->getOperand(3);
14069 TargetOpcode = X86ISD::MOVSD;
14070 Amt2 = Amt->getOperand(2);
14073 // Do similar checks for the case where the machine value type
14075 CanBeSimplified = Amt1 == Amt->getOperand(1);
14076 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14077 CanBeSimplified = Amt2 == Amt->getOperand(i);
14079 if (!CanBeSimplified) {
14080 TargetOpcode = X86ISD::MOVSD;
14081 CanBeSimplified = true;
14082 Amt2 = Amt->getOperand(4);
14083 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14084 CanBeSimplified = Amt1 == Amt->getOperand(i);
14085 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14086 CanBeSimplified = Amt2 == Amt->getOperand(j);
14090 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14091 isa<ConstantSDNode>(Amt2)) {
14092 // Replace this node with two shifts followed by a MOVSS/MOVSD.
14093 EVT CastVT = MVT::v4i32;
14095 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14096 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14098 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14099 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14100 if (TargetOpcode == X86ISD::MOVSD)
14101 CastVT = MVT::v2i64;
14102 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14103 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14104 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14106 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14110 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14111 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14114 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14115 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14117 // Turn 'a' into a mask suitable for VSELECT
14118 SDValue VSelM = DAG.getConstant(0x80, VT);
14119 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14120 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14122 SDValue CM1 = DAG.getConstant(0x0f, VT);
14123 SDValue CM2 = DAG.getConstant(0x3f, VT);
14125 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14126 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14127 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14128 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14129 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14132 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14133 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14134 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14136 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14137 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14138 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14139 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14140 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14143 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14144 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14145 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14147 // return VSELECT(r, r+r, a);
14148 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14149 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14153 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14154 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14155 // solution better.
14156 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14157 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14159 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14160 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14161 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14162 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14163 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14166 // Decompose 256-bit shifts into smaller 128-bit shifts.
14167 if (VT.is256BitVector()) {
14168 unsigned NumElems = VT.getVectorNumElements();
14169 MVT EltVT = VT.getVectorElementType();
14170 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14172 // Extract the two vectors
14173 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14174 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14176 // Recreate the shift amount vectors
14177 SDValue Amt1, Amt2;
14178 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14179 // Constant shift amount
14180 SmallVector<SDValue, 4> Amt1Csts;
14181 SmallVector<SDValue, 4> Amt2Csts;
14182 for (unsigned i = 0; i != NumElems/2; ++i)
14183 Amt1Csts.push_back(Amt->getOperand(i));
14184 for (unsigned i = NumElems/2; i != NumElems; ++i)
14185 Amt2Csts.push_back(Amt->getOperand(i));
14187 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14188 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14190 // Variable shift amount
14191 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14192 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14195 // Issue new vector shifts for the smaller types
14196 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14197 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14199 // Concatenate the result back
14200 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14206 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14207 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14208 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14209 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14210 // has only one use.
14211 SDNode *N = Op.getNode();
14212 SDValue LHS = N->getOperand(0);
14213 SDValue RHS = N->getOperand(1);
14214 unsigned BaseOp = 0;
14217 switch (Op.getOpcode()) {
14218 default: llvm_unreachable("Unknown ovf instruction!");
14220 // A subtract of one will be selected as a INC. Note that INC doesn't
14221 // set CF, so we can't do this for UADDO.
14222 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14224 BaseOp = X86ISD::INC;
14225 Cond = X86::COND_O;
14228 BaseOp = X86ISD::ADD;
14229 Cond = X86::COND_O;
14232 BaseOp = X86ISD::ADD;
14233 Cond = X86::COND_B;
14236 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14237 // set CF, so we can't do this for USUBO.
14238 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14240 BaseOp = X86ISD::DEC;
14241 Cond = X86::COND_O;
14244 BaseOp = X86ISD::SUB;
14245 Cond = X86::COND_O;
14248 BaseOp = X86ISD::SUB;
14249 Cond = X86::COND_B;
14252 BaseOp = X86ISD::SMUL;
14253 Cond = X86::COND_O;
14255 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14256 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14258 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14261 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14262 DAG.getConstant(X86::COND_O, MVT::i32),
14263 SDValue(Sum.getNode(), 2));
14265 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14269 // Also sets EFLAGS.
14270 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14271 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14274 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14275 DAG.getConstant(Cond, MVT::i32),
14276 SDValue(Sum.getNode(), 1));
14278 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14281 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14282 SelectionDAG &DAG) const {
14284 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14285 MVT VT = Op.getSimpleValueType();
14287 if (!Subtarget->hasSSE2() || !VT.isVector())
14290 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14291 ExtraVT.getScalarType().getSizeInBits();
14293 switch (VT.SimpleTy) {
14294 default: return SDValue();
14297 if (!Subtarget->hasFp256())
14299 if (!Subtarget->hasInt256()) {
14300 // needs to be split
14301 unsigned NumElems = VT.getVectorNumElements();
14303 // Extract the LHS vectors
14304 SDValue LHS = Op.getOperand(0);
14305 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14306 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14308 MVT EltVT = VT.getVectorElementType();
14309 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14311 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14312 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14313 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14315 SDValue Extra = DAG.getValueType(ExtraVT);
14317 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14318 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14320 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14325 SDValue Op0 = Op.getOperand(0);
14326 SDValue Op00 = Op0.getOperand(0);
14328 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14329 if (Op0.getOpcode() == ISD::BITCAST &&
14330 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14331 // (sext (vzext x)) -> (vsext x)
14332 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14333 if (Tmp1.getNode()) {
14334 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14335 // This folding is only valid when the in-reg type is a vector of i8,
14337 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14338 ExtraEltVT == MVT::i32) {
14339 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14340 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14341 "This optimization is invalid without a VZEXT.");
14342 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14348 // If the above didn't work, then just use Shift-Left + Shift-Right.
14349 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14351 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14357 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14358 SelectionDAG &DAG) {
14360 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14361 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14362 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14363 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14365 // The only fence that needs an instruction is a sequentially-consistent
14366 // cross-thread fence.
14367 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14368 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14369 // no-sse2). There isn't any reason to disable it if the target processor
14371 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14372 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14374 SDValue Chain = Op.getOperand(0);
14375 SDValue Zero = DAG.getConstant(0, MVT::i32);
14377 DAG.getRegister(X86::ESP, MVT::i32), // Base
14378 DAG.getTargetConstant(1, MVT::i8), // Scale
14379 DAG.getRegister(0, MVT::i32), // Index
14380 DAG.getTargetConstant(0, MVT::i32), // Disp
14381 DAG.getRegister(0, MVT::i32), // Segment.
14385 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14386 return SDValue(Res, 0);
14389 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14390 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14393 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14394 SelectionDAG &DAG) {
14395 MVT T = Op.getSimpleValueType();
14399 switch(T.SimpleTy) {
14400 default: llvm_unreachable("Invalid value type!");
14401 case MVT::i8: Reg = X86::AL; size = 1; break;
14402 case MVT::i16: Reg = X86::AX; size = 2; break;
14403 case MVT::i32: Reg = X86::EAX; size = 4; break;
14405 assert(Subtarget->is64Bit() && "Node not type legal!");
14406 Reg = X86::RAX; size = 8;
14409 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14410 Op.getOperand(2), SDValue());
14411 SDValue Ops[] = { cpIn.getValue(0),
14414 DAG.getTargetConstant(size, MVT::i8),
14415 cpIn.getValue(1) };
14416 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14417 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14418 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14421 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14425 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14426 SelectionDAG &DAG) {
14427 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14428 MVT DstVT = Op.getSimpleValueType();
14430 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14431 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14432 if (DstVT != MVT::f64)
14433 // This conversion needs to be expanded.
14436 SDValue InVec = Op->getOperand(0);
14438 unsigned NumElts = SrcVT.getVectorNumElements();
14439 EVT SVT = SrcVT.getVectorElementType();
14441 // Widen the vector in input in the case of MVT::v2i32.
14442 // Example: from MVT::v2i32 to MVT::v4i32.
14443 SmallVector<SDValue, 16> Elts;
14444 for (unsigned i = 0, e = NumElts; i != e; ++i)
14445 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14446 DAG.getIntPtrConstant(i)));
14448 // Explicitly mark the extra elements as Undef.
14449 SDValue Undef = DAG.getUNDEF(SVT);
14450 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14451 Elts.push_back(Undef);
14453 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14454 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14455 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14456 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14457 DAG.getIntPtrConstant(0));
14460 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14461 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14462 assert((DstVT == MVT::i64 ||
14463 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14464 "Unexpected custom BITCAST");
14465 // i64 <=> MMX conversions are Legal.
14466 if (SrcVT==MVT::i64 && DstVT.isVector())
14468 if (DstVT==MVT::i64 && SrcVT.isVector())
14470 // MMX <=> MMX conversions are Legal.
14471 if (SrcVT.isVector() && DstVT.isVector())
14473 // All other conversions need to be expanded.
14477 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14478 SDNode *Node = Op.getNode();
14480 EVT T = Node->getValueType(0);
14481 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14482 DAG.getConstant(0, T), Node->getOperand(2));
14483 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14484 cast<AtomicSDNode>(Node)->getMemoryVT(),
14485 Node->getOperand(0),
14486 Node->getOperand(1), negOp,
14487 cast<AtomicSDNode>(Node)->getMemOperand(),
14488 cast<AtomicSDNode>(Node)->getOrdering(),
14489 cast<AtomicSDNode>(Node)->getSynchScope());
14492 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14493 SDNode *Node = Op.getNode();
14495 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14497 // Convert seq_cst store -> xchg
14498 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14499 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14500 // (The only way to get a 16-byte store is cmpxchg16b)
14501 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14502 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14503 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14504 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14505 cast<AtomicSDNode>(Node)->getMemoryVT(),
14506 Node->getOperand(0),
14507 Node->getOperand(1), Node->getOperand(2),
14508 cast<AtomicSDNode>(Node)->getMemOperand(),
14509 cast<AtomicSDNode>(Node)->getOrdering(),
14510 cast<AtomicSDNode>(Node)->getSynchScope());
14511 return Swap.getValue(1);
14513 // Other atomic stores have a simple pattern.
14517 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14518 EVT VT = Op.getNode()->getSimpleValueType(0);
14520 // Let legalize expand this if it isn't a legal type yet.
14521 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14524 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14527 bool ExtraOp = false;
14528 switch (Op.getOpcode()) {
14529 default: llvm_unreachable("Invalid code");
14530 case ISD::ADDC: Opc = X86ISD::ADD; break;
14531 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14532 case ISD::SUBC: Opc = X86ISD::SUB; break;
14533 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14537 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14539 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14540 Op.getOperand(1), Op.getOperand(2));
14543 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14544 SelectionDAG &DAG) {
14545 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14547 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14548 // which returns the values as { float, float } (in XMM0) or
14549 // { double, double } (which is returned in XMM0, XMM1).
14551 SDValue Arg = Op.getOperand(0);
14552 EVT ArgVT = Arg.getValueType();
14553 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14555 TargetLowering::ArgListTy Args;
14556 TargetLowering::ArgListEntry Entry;
14560 Entry.isSExt = false;
14561 Entry.isZExt = false;
14562 Args.push_back(Entry);
14564 bool isF64 = ArgVT == MVT::f64;
14565 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14566 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14567 // the results are returned via SRet in memory.
14568 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14569 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14570 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14572 Type *RetTy = isF64
14573 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14574 : (Type*)VectorType::get(ArgTy, 4);
14576 TargetLowering::CallLoweringInfo CLI(DAG);
14577 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14578 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14580 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14583 // Returned in xmm0 and xmm1.
14584 return CallResult.first;
14586 // Returned in bits 0:31 and 32:64 xmm0.
14587 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14588 CallResult.first, DAG.getIntPtrConstant(0));
14589 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14590 CallResult.first, DAG.getIntPtrConstant(1));
14591 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14592 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14595 /// LowerOperation - Provide custom lowering hooks for some operations.
14597 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14598 switch (Op.getOpcode()) {
14599 default: llvm_unreachable("Should not custom lower this!");
14600 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14601 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14602 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14603 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14604 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14605 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14606 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14607 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14608 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14609 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14610 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14611 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14612 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14613 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14614 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14615 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14616 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14617 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14618 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14619 case ISD::SHL_PARTS:
14620 case ISD::SRA_PARTS:
14621 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14622 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14623 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14624 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14625 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14626 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14627 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14628 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14629 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14630 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14631 case ISD::FABS: return LowerFABS(Op, DAG);
14632 case ISD::FNEG: return LowerFNEG(Op, DAG);
14633 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14634 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14635 case ISD::SETCC: return LowerSETCC(Op, DAG);
14636 case ISD::SELECT: return LowerSELECT(Op, DAG);
14637 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14638 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14639 case ISD::VASTART: return LowerVASTART(Op, DAG);
14640 case ISD::VAARG: return LowerVAARG(Op, DAG);
14641 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14642 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14643 case ISD::INTRINSIC_VOID:
14644 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14645 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14646 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14647 case ISD::FRAME_TO_ARGS_OFFSET:
14648 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14649 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14650 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14651 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14652 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14653 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14654 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14655 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14656 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14657 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14658 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14659 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14660 case ISD::UMUL_LOHI:
14661 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14664 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14670 case ISD::UMULO: return LowerXALUO(Op, DAG);
14671 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14672 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14676 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14677 case ISD::ADD: return LowerADD(Op, DAG);
14678 case ISD::SUB: return LowerSUB(Op, DAG);
14679 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14683 static void ReplaceATOMIC_LOAD(SDNode *Node,
14684 SmallVectorImpl<SDValue> &Results,
14685 SelectionDAG &DAG) {
14687 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14689 // Convert wide load -> cmpxchg8b/cmpxchg16b
14690 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14691 // (The only way to get a 16-byte load is cmpxchg16b)
14692 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14693 SDValue Zero = DAG.getConstant(0, VT);
14694 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14695 Node->getOperand(0),
14696 Node->getOperand(1), Zero, Zero,
14697 cast<AtomicSDNode>(Node)->getMemOperand(),
14698 cast<AtomicSDNode>(Node)->getOrdering(),
14699 cast<AtomicSDNode>(Node)->getOrdering(),
14700 cast<AtomicSDNode>(Node)->getSynchScope());
14701 Results.push_back(Swap.getValue(0));
14702 Results.push_back(Swap.getValue(1));
14706 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14707 SelectionDAG &DAG, unsigned NewOp) {
14709 assert (Node->getValueType(0) == MVT::i64 &&
14710 "Only know how to expand i64 atomics");
14712 SDValue Chain = Node->getOperand(0);
14713 SDValue In1 = Node->getOperand(1);
14714 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14715 Node->getOperand(2), DAG.getIntPtrConstant(0));
14716 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14717 Node->getOperand(2), DAG.getIntPtrConstant(1));
14718 SDValue Ops[] = { Chain, In1, In2L, In2H };
14719 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14721 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14722 cast<MemSDNode>(Node)->getMemOperand());
14723 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14724 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14725 Results.push_back(Result.getValue(2));
14728 /// ReplaceNodeResults - Replace a node with an illegal result type
14729 /// with a new node built out of custom code.
14730 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14731 SmallVectorImpl<SDValue>&Results,
14732 SelectionDAG &DAG) const {
14734 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14735 switch (N->getOpcode()) {
14737 llvm_unreachable("Do not know how to custom type legalize this operation!");
14738 case ISD::SIGN_EXTEND_INREG:
14743 // We don't want to expand or promote these.
14750 case ISD::UDIVREM: {
14751 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14752 Results.push_back(V);
14755 case ISD::FP_TO_SINT:
14756 case ISD::FP_TO_UINT: {
14757 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14759 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14762 std::pair<SDValue,SDValue> Vals =
14763 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14764 SDValue FIST = Vals.first, StackSlot = Vals.second;
14765 if (FIST.getNode()) {
14766 EVT VT = N->getValueType(0);
14767 // Return a load from the stack slot.
14768 if (StackSlot.getNode())
14769 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14770 MachinePointerInfo(),
14771 false, false, false, 0));
14773 Results.push_back(FIST);
14777 case ISD::UINT_TO_FP: {
14778 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14779 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14780 N->getValueType(0) != MVT::v2f32)
14782 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14784 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14786 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14787 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14788 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14789 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14790 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14791 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14794 case ISD::FP_ROUND: {
14795 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14797 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14798 Results.push_back(V);
14801 case ISD::INTRINSIC_W_CHAIN: {
14802 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14804 default : llvm_unreachable("Do not know how to custom type "
14805 "legalize this intrinsic operation!");
14806 case Intrinsic::x86_rdtsc:
14807 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14809 case Intrinsic::x86_rdtscp:
14810 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14814 case ISD::READCYCLECOUNTER: {
14815 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14818 case ISD::ATOMIC_CMP_SWAP: {
14819 EVT T = N->getValueType(0);
14820 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14821 bool Regs64bit = T == MVT::i128;
14822 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14823 SDValue cpInL, cpInH;
14824 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14825 DAG.getConstant(0, HalfT));
14826 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14827 DAG.getConstant(1, HalfT));
14828 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14829 Regs64bit ? X86::RAX : X86::EAX,
14831 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14832 Regs64bit ? X86::RDX : X86::EDX,
14833 cpInH, cpInL.getValue(1));
14834 SDValue swapInL, swapInH;
14835 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14836 DAG.getConstant(0, HalfT));
14837 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14838 DAG.getConstant(1, HalfT));
14839 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14840 Regs64bit ? X86::RBX : X86::EBX,
14841 swapInL, cpInH.getValue(1));
14842 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14843 Regs64bit ? X86::RCX : X86::ECX,
14844 swapInH, swapInL.getValue(1));
14845 SDValue Ops[] = { swapInH.getValue(0),
14847 swapInH.getValue(1) };
14848 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14849 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14850 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14851 X86ISD::LCMPXCHG8_DAG;
14852 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14853 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14854 Regs64bit ? X86::RAX : X86::EAX,
14855 HalfT, Result.getValue(1));
14856 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14857 Regs64bit ? X86::RDX : X86::EDX,
14858 HalfT, cpOutL.getValue(2));
14859 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14860 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14861 Results.push_back(cpOutH.getValue(1));
14864 case ISD::ATOMIC_LOAD_ADD:
14865 case ISD::ATOMIC_LOAD_AND:
14866 case ISD::ATOMIC_LOAD_NAND:
14867 case ISD::ATOMIC_LOAD_OR:
14868 case ISD::ATOMIC_LOAD_SUB:
14869 case ISD::ATOMIC_LOAD_XOR:
14870 case ISD::ATOMIC_LOAD_MAX:
14871 case ISD::ATOMIC_LOAD_MIN:
14872 case ISD::ATOMIC_LOAD_UMAX:
14873 case ISD::ATOMIC_LOAD_UMIN:
14874 case ISD::ATOMIC_SWAP: {
14876 switch (N->getOpcode()) {
14877 default: llvm_unreachable("Unexpected opcode");
14878 case ISD::ATOMIC_LOAD_ADD:
14879 Opc = X86ISD::ATOMADD64_DAG;
14881 case ISD::ATOMIC_LOAD_AND:
14882 Opc = X86ISD::ATOMAND64_DAG;
14884 case ISD::ATOMIC_LOAD_NAND:
14885 Opc = X86ISD::ATOMNAND64_DAG;
14887 case ISD::ATOMIC_LOAD_OR:
14888 Opc = X86ISD::ATOMOR64_DAG;
14890 case ISD::ATOMIC_LOAD_SUB:
14891 Opc = X86ISD::ATOMSUB64_DAG;
14893 case ISD::ATOMIC_LOAD_XOR:
14894 Opc = X86ISD::ATOMXOR64_DAG;
14896 case ISD::ATOMIC_LOAD_MAX:
14897 Opc = X86ISD::ATOMMAX64_DAG;
14899 case ISD::ATOMIC_LOAD_MIN:
14900 Opc = X86ISD::ATOMMIN64_DAG;
14902 case ISD::ATOMIC_LOAD_UMAX:
14903 Opc = X86ISD::ATOMUMAX64_DAG;
14905 case ISD::ATOMIC_LOAD_UMIN:
14906 Opc = X86ISD::ATOMUMIN64_DAG;
14908 case ISD::ATOMIC_SWAP:
14909 Opc = X86ISD::ATOMSWAP64_DAG;
14912 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14915 case ISD::ATOMIC_LOAD: {
14916 ReplaceATOMIC_LOAD(N, Results, DAG);
14919 case ISD::BITCAST: {
14920 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14921 EVT DstVT = N->getValueType(0);
14922 EVT SrcVT = N->getOperand(0)->getValueType(0);
14924 if (SrcVT != MVT::f64 ||
14925 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14928 unsigned NumElts = DstVT.getVectorNumElements();
14929 EVT SVT = DstVT.getVectorElementType();
14930 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14931 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14932 MVT::v2f64, N->getOperand(0));
14933 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14935 SmallVector<SDValue, 8> Elts;
14936 for (unsigned i = 0, e = NumElts; i != e; ++i)
14937 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14938 ToVecInt, DAG.getIntPtrConstant(i)));
14940 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14945 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14947 default: return nullptr;
14948 case X86ISD::BSF: return "X86ISD::BSF";
14949 case X86ISD::BSR: return "X86ISD::BSR";
14950 case X86ISD::SHLD: return "X86ISD::SHLD";
14951 case X86ISD::SHRD: return "X86ISD::SHRD";
14952 case X86ISD::FAND: return "X86ISD::FAND";
14953 case X86ISD::FANDN: return "X86ISD::FANDN";
14954 case X86ISD::FOR: return "X86ISD::FOR";
14955 case X86ISD::FXOR: return "X86ISD::FXOR";
14956 case X86ISD::FSRL: return "X86ISD::FSRL";
14957 case X86ISD::FILD: return "X86ISD::FILD";
14958 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14959 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14960 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14961 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14962 case X86ISD::FLD: return "X86ISD::FLD";
14963 case X86ISD::FST: return "X86ISD::FST";
14964 case X86ISD::CALL: return "X86ISD::CALL";
14965 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14966 case X86ISD::BT: return "X86ISD::BT";
14967 case X86ISD::CMP: return "X86ISD::CMP";
14968 case X86ISD::COMI: return "X86ISD::COMI";
14969 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14970 case X86ISD::CMPM: return "X86ISD::CMPM";
14971 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14972 case X86ISD::SETCC: return "X86ISD::SETCC";
14973 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14974 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14975 case X86ISD::CMOV: return "X86ISD::CMOV";
14976 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14977 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14978 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14979 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14980 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14981 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14982 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14983 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14984 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14985 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14986 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14987 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14988 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14989 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14990 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14991 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14992 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14993 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14994 case X86ISD::HADD: return "X86ISD::HADD";
14995 case X86ISD::HSUB: return "X86ISD::HSUB";
14996 case X86ISD::FHADD: return "X86ISD::FHADD";
14997 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14998 case X86ISD::UMAX: return "X86ISD::UMAX";
14999 case X86ISD::UMIN: return "X86ISD::UMIN";
15000 case X86ISD::SMAX: return "X86ISD::SMAX";
15001 case X86ISD::SMIN: return "X86ISD::SMIN";
15002 case X86ISD::FMAX: return "X86ISD::FMAX";
15003 case X86ISD::FMIN: return "X86ISD::FMIN";
15004 case X86ISD::FMAXC: return "X86ISD::FMAXC";
15005 case X86ISD::FMINC: return "X86ISD::FMINC";
15006 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
15007 case X86ISD::FRCP: return "X86ISD::FRCP";
15008 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
15009 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
15010 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
15011 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
15012 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
15013 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
15014 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
15015 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
15016 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
15017 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
15018 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
15019 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
15020 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
15021 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
15022 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
15023 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
15024 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
15025 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
15026 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
15027 case X86ISD::VZEXT: return "X86ISD::VZEXT";
15028 case X86ISD::VSEXT: return "X86ISD::VSEXT";
15029 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
15030 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
15031 case X86ISD::VINSERT: return "X86ISD::VINSERT";
15032 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
15033 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
15034 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
15035 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
15036 case X86ISD::VSHL: return "X86ISD::VSHL";
15037 case X86ISD::VSRL: return "X86ISD::VSRL";
15038 case X86ISD::VSRA: return "X86ISD::VSRA";
15039 case X86ISD::VSHLI: return "X86ISD::VSHLI";
15040 case X86ISD::VSRLI: return "X86ISD::VSRLI";
15041 case X86ISD::VSRAI: return "X86ISD::VSRAI";
15042 case X86ISD::CMPP: return "X86ISD::CMPP";
15043 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
15044 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
15045 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
15046 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
15047 case X86ISD::ADD: return "X86ISD::ADD";
15048 case X86ISD::SUB: return "X86ISD::SUB";
15049 case X86ISD::ADC: return "X86ISD::ADC";
15050 case X86ISD::SBB: return "X86ISD::SBB";
15051 case X86ISD::SMUL: return "X86ISD::SMUL";
15052 case X86ISD::UMUL: return "X86ISD::UMUL";
15053 case X86ISD::INC: return "X86ISD::INC";
15054 case X86ISD::DEC: return "X86ISD::DEC";
15055 case X86ISD::OR: return "X86ISD::OR";
15056 case X86ISD::XOR: return "X86ISD::XOR";
15057 case X86ISD::AND: return "X86ISD::AND";
15058 case X86ISD::BEXTR: return "X86ISD::BEXTR";
15059 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
15060 case X86ISD::PTEST: return "X86ISD::PTEST";
15061 case X86ISD::TESTP: return "X86ISD::TESTP";
15062 case X86ISD::TESTM: return "X86ISD::TESTM";
15063 case X86ISD::TESTNM: return "X86ISD::TESTNM";
15064 case X86ISD::KORTEST: return "X86ISD::KORTEST";
15065 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
15066 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
15067 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
15068 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
15069 case X86ISD::SHUFP: return "X86ISD::SHUFP";
15070 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
15071 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
15072 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
15073 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
15074 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
15075 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
15076 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
15077 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
15078 case X86ISD::MOVSD: return "X86ISD::MOVSD";
15079 case X86ISD::MOVSS: return "X86ISD::MOVSS";
15080 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
15081 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
15082 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
15083 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
15084 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
15085 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
15086 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
15087 case X86ISD::VPERMV: return "X86ISD::VPERMV";
15088 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
15089 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
15090 case X86ISD::VPERMI: return "X86ISD::VPERMI";
15091 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
15092 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
15093 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15094 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
15095 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
15096 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
15097 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
15098 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
15099 case X86ISD::SAHF: return "X86ISD::SAHF";
15100 case X86ISD::RDRAND: return "X86ISD::RDRAND";
15101 case X86ISD::RDSEED: return "X86ISD::RDSEED";
15102 case X86ISD::FMADD: return "X86ISD::FMADD";
15103 case X86ISD::FMSUB: return "X86ISD::FMSUB";
15104 case X86ISD::FNMADD: return "X86ISD::FNMADD";
15105 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
15106 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
15107 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
15108 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
15109 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
15110 case X86ISD::XTEST: return "X86ISD::XTEST";
15114 // isLegalAddressingMode - Return true if the addressing mode represented
15115 // by AM is legal for this target, for a load/store of the specified type.
15116 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15118 // X86 supports extremely general addressing modes.
15119 CodeModel::Model M = getTargetMachine().getCodeModel();
15120 Reloc::Model R = getTargetMachine().getRelocationModel();
15122 // X86 allows a sign-extended 32-bit immediate field as a displacement.
15123 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15128 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15130 // If a reference to this global requires an extra load, we can't fold it.
15131 if (isGlobalStubReference(GVFlags))
15134 // If BaseGV requires a register for the PIC base, we cannot also have a
15135 // BaseReg specified.
15136 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15139 // If lower 4G is not available, then we must use rip-relative addressing.
15140 if ((M != CodeModel::Small || R != Reloc::Static) &&
15141 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15145 switch (AM.Scale) {
15151 // These scales always work.
15156 // These scales are formed with basereg+scalereg. Only accept if there is
15161 default: // Other stuff never works.
15168 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15169 unsigned Bits = Ty->getScalarSizeInBits();
15171 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15172 // particularly cheaper than those without.
15176 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15177 // variable shifts just as cheap as scalar ones.
15178 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15181 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15182 // fully general vector.
15186 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15187 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15189 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15190 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15191 return NumBits1 > NumBits2;
15194 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15195 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15198 if (!isTypeLegal(EVT::getEVT(Ty1)))
15201 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15203 // Assuming the caller doesn't have a zeroext or signext return parameter,
15204 // truncation all the way down to i1 is valid.
15208 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15209 return isInt<32>(Imm);
15212 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15213 // Can also use sub to handle negated immediates.
15214 return isInt<32>(Imm);
15217 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15218 if (!VT1.isInteger() || !VT2.isInteger())
15220 unsigned NumBits1 = VT1.getSizeInBits();
15221 unsigned NumBits2 = VT2.getSizeInBits();
15222 return NumBits1 > NumBits2;
15225 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15226 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15227 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15230 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15231 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15232 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15235 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15236 EVT VT1 = Val.getValueType();
15237 if (isZExtFree(VT1, VT2))
15240 if (Val.getOpcode() != ISD::LOAD)
15243 if (!VT1.isSimple() || !VT1.isInteger() ||
15244 !VT2.isSimple() || !VT2.isInteger())
15247 switch (VT1.getSimpleVT().SimpleTy) {
15252 // X86 has 8, 16, and 32-bit zero-extending loads.
15260 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15261 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15264 VT = VT.getScalarType();
15266 if (!VT.isSimple())
15269 switch (VT.getSimpleVT().SimpleTy) {
15280 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15281 // i16 instructions are longer (0x66 prefix) and potentially slower.
15282 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15285 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15286 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15287 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15288 /// are assumed to be legal.
15290 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15292 if (!VT.isSimple())
15295 MVT SVT = VT.getSimpleVT();
15297 // Very little shuffling can be done for 64-bit vectors right now.
15298 if (VT.getSizeInBits() == 64)
15301 // If this is a single-input shuffle with no 128 bit lane crossings we can
15302 // lower it into pshufb.
15303 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15304 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15305 bool isLegal = true;
15306 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15307 if (M[I] >= (int)SVT.getVectorNumElements() ||
15308 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15317 // FIXME: blends, shifts.
15318 return (SVT.getVectorNumElements() == 2 ||
15319 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15320 isMOVLMask(M, SVT) ||
15321 isSHUFPMask(M, SVT) ||
15322 isPSHUFDMask(M, SVT) ||
15323 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15324 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15325 isPALIGNRMask(M, SVT, Subtarget) ||
15326 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15327 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15328 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15329 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15330 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15334 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15336 if (!VT.isSimple())
15339 MVT SVT = VT.getSimpleVT();
15340 unsigned NumElts = SVT.getVectorNumElements();
15341 // FIXME: This collection of masks seems suspect.
15344 if (NumElts == 4 && SVT.is128BitVector()) {
15345 return (isMOVLMask(Mask, SVT) ||
15346 isCommutedMOVLMask(Mask, SVT, true) ||
15347 isSHUFPMask(Mask, SVT) ||
15348 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15353 //===----------------------------------------------------------------------===//
15354 // X86 Scheduler Hooks
15355 //===----------------------------------------------------------------------===//
15357 /// Utility function to emit xbegin specifying the start of an RTM region.
15358 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15359 const TargetInstrInfo *TII) {
15360 DebugLoc DL = MI->getDebugLoc();
15362 const BasicBlock *BB = MBB->getBasicBlock();
15363 MachineFunction::iterator I = MBB;
15366 // For the v = xbegin(), we generate
15377 MachineBasicBlock *thisMBB = MBB;
15378 MachineFunction *MF = MBB->getParent();
15379 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15380 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15381 MF->insert(I, mainMBB);
15382 MF->insert(I, sinkMBB);
15384 // Transfer the remainder of BB and its successor edges to sinkMBB.
15385 sinkMBB->splice(sinkMBB->begin(), MBB,
15386 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15387 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15391 // # fallthrough to mainMBB
15392 // # abortion to sinkMBB
15393 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15394 thisMBB->addSuccessor(mainMBB);
15395 thisMBB->addSuccessor(sinkMBB);
15399 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15400 mainMBB->addSuccessor(sinkMBB);
15403 // EAX is live into the sinkMBB
15404 sinkMBB->addLiveIn(X86::EAX);
15405 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15406 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15409 MI->eraseFromParent();
15413 // Get CMPXCHG opcode for the specified data type.
15414 static unsigned getCmpXChgOpcode(EVT VT) {
15415 switch (VT.getSimpleVT().SimpleTy) {
15416 case MVT::i8: return X86::LCMPXCHG8;
15417 case MVT::i16: return X86::LCMPXCHG16;
15418 case MVT::i32: return X86::LCMPXCHG32;
15419 case MVT::i64: return X86::LCMPXCHG64;
15423 llvm_unreachable("Invalid operand size!");
15426 // Get LOAD opcode for the specified data type.
15427 static unsigned getLoadOpcode(EVT VT) {
15428 switch (VT.getSimpleVT().SimpleTy) {
15429 case MVT::i8: return X86::MOV8rm;
15430 case MVT::i16: return X86::MOV16rm;
15431 case MVT::i32: return X86::MOV32rm;
15432 case MVT::i64: return X86::MOV64rm;
15436 llvm_unreachable("Invalid operand size!");
15439 // Get opcode of the non-atomic one from the specified atomic instruction.
15440 static unsigned getNonAtomicOpcode(unsigned Opc) {
15442 case X86::ATOMAND8: return X86::AND8rr;
15443 case X86::ATOMAND16: return X86::AND16rr;
15444 case X86::ATOMAND32: return X86::AND32rr;
15445 case X86::ATOMAND64: return X86::AND64rr;
15446 case X86::ATOMOR8: return X86::OR8rr;
15447 case X86::ATOMOR16: return X86::OR16rr;
15448 case X86::ATOMOR32: return X86::OR32rr;
15449 case X86::ATOMOR64: return X86::OR64rr;
15450 case X86::ATOMXOR8: return X86::XOR8rr;
15451 case X86::ATOMXOR16: return X86::XOR16rr;
15452 case X86::ATOMXOR32: return X86::XOR32rr;
15453 case X86::ATOMXOR64: return X86::XOR64rr;
15455 llvm_unreachable("Unhandled atomic-load-op opcode!");
15458 // Get opcode of the non-atomic one from the specified atomic instruction with
15460 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15461 unsigned &ExtraOpc) {
15463 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15464 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15465 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15466 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15467 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15468 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15469 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15470 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15471 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15472 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15473 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15474 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15475 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15476 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15477 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15478 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15479 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15480 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15481 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15482 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15484 llvm_unreachable("Unhandled atomic-load-op opcode!");
15487 // Get opcode of the non-atomic one from the specified atomic instruction for
15488 // 64-bit data type on 32-bit target.
15489 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15491 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15492 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15493 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15494 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15495 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15496 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15497 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15498 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15499 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15500 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15502 llvm_unreachable("Unhandled atomic-load-op opcode!");
15505 // Get opcode of the non-atomic one from the specified atomic instruction for
15506 // 64-bit data type on 32-bit target with extra opcode.
15507 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15509 unsigned &ExtraOpc) {
15511 case X86::ATOMNAND6432:
15512 ExtraOpc = X86::NOT32r;
15513 HiOpc = X86::AND32rr;
15514 return X86::AND32rr;
15516 llvm_unreachable("Unhandled atomic-load-op opcode!");
15519 // Get pseudo CMOV opcode from the specified data type.
15520 static unsigned getPseudoCMOVOpc(EVT VT) {
15521 switch (VT.getSimpleVT().SimpleTy) {
15522 case MVT::i8: return X86::CMOV_GR8;
15523 case MVT::i16: return X86::CMOV_GR16;
15524 case MVT::i32: return X86::CMOV_GR32;
15528 llvm_unreachable("Unknown CMOV opcode!");
15531 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15532 // They will be translated into a spin-loop or compare-exchange loop from
15535 // dst = atomic-fetch-op MI.addr, MI.val
15541 // t1 = LOAD MI.addr
15543 // t4 = phi(t1, t3 / loop)
15544 // t2 = OP MI.val, t4
15546 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15552 MachineBasicBlock *
15553 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15554 MachineBasicBlock *MBB) const {
15555 MachineFunction *MF = MBB->getParent();
15556 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15557 DebugLoc DL = MI->getDebugLoc();
15559 MachineRegisterInfo &MRI = MF->getRegInfo();
15561 const BasicBlock *BB = MBB->getBasicBlock();
15562 MachineFunction::iterator I = MBB;
15565 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15566 "Unexpected number of operands");
15568 assert(MI->hasOneMemOperand() &&
15569 "Expected atomic-load-op to have one memoperand");
15571 // Memory Reference
15572 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15573 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15575 unsigned DstReg, SrcReg;
15576 unsigned MemOpndSlot;
15578 unsigned CurOp = 0;
15580 DstReg = MI->getOperand(CurOp++).getReg();
15581 MemOpndSlot = CurOp;
15582 CurOp += X86::AddrNumOperands;
15583 SrcReg = MI->getOperand(CurOp++).getReg();
15585 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15586 MVT::SimpleValueType VT = *RC->vt_begin();
15587 unsigned t1 = MRI.createVirtualRegister(RC);
15588 unsigned t2 = MRI.createVirtualRegister(RC);
15589 unsigned t3 = MRI.createVirtualRegister(RC);
15590 unsigned t4 = MRI.createVirtualRegister(RC);
15591 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15593 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15594 unsigned LOADOpc = getLoadOpcode(VT);
15596 // For the atomic load-arith operator, we generate
15599 // t1 = LOAD [MI.addr]
15601 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15602 // t1 = OP MI.val, EAX
15604 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15610 MachineBasicBlock *thisMBB = MBB;
15611 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15612 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15613 MF->insert(I, mainMBB);
15614 MF->insert(I, sinkMBB);
15616 MachineInstrBuilder MIB;
15618 // Transfer the remainder of BB and its successor edges to sinkMBB.
15619 sinkMBB->splice(sinkMBB->begin(), MBB,
15620 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15621 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15624 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15625 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15626 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15628 NewMO.setIsKill(false);
15629 MIB.addOperand(NewMO);
15631 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15632 unsigned flags = (*MMOI)->getFlags();
15633 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15634 MachineMemOperand *MMO =
15635 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15636 (*MMOI)->getSize(),
15637 (*MMOI)->getBaseAlignment(),
15638 (*MMOI)->getTBAAInfo(),
15639 (*MMOI)->getRanges());
15640 MIB.addMemOperand(MMO);
15643 thisMBB->addSuccessor(mainMBB);
15646 MachineBasicBlock *origMainMBB = mainMBB;
15649 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15650 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15652 unsigned Opc = MI->getOpcode();
15655 llvm_unreachable("Unhandled atomic-load-op opcode!");
15656 case X86::ATOMAND8:
15657 case X86::ATOMAND16:
15658 case X86::ATOMAND32:
15659 case X86::ATOMAND64:
15661 case X86::ATOMOR16:
15662 case X86::ATOMOR32:
15663 case X86::ATOMOR64:
15664 case X86::ATOMXOR8:
15665 case X86::ATOMXOR16:
15666 case X86::ATOMXOR32:
15667 case X86::ATOMXOR64: {
15668 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15669 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15673 case X86::ATOMNAND8:
15674 case X86::ATOMNAND16:
15675 case X86::ATOMNAND32:
15676 case X86::ATOMNAND64: {
15677 unsigned Tmp = MRI.createVirtualRegister(RC);
15679 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15680 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15682 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15685 case X86::ATOMMAX8:
15686 case X86::ATOMMAX16:
15687 case X86::ATOMMAX32:
15688 case X86::ATOMMAX64:
15689 case X86::ATOMMIN8:
15690 case X86::ATOMMIN16:
15691 case X86::ATOMMIN32:
15692 case X86::ATOMMIN64:
15693 case X86::ATOMUMAX8:
15694 case X86::ATOMUMAX16:
15695 case X86::ATOMUMAX32:
15696 case X86::ATOMUMAX64:
15697 case X86::ATOMUMIN8:
15698 case X86::ATOMUMIN16:
15699 case X86::ATOMUMIN32:
15700 case X86::ATOMUMIN64: {
15702 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15704 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15708 if (Subtarget->hasCMov()) {
15709 if (VT != MVT::i8) {
15711 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15715 // Promote i8 to i32 to use CMOV32
15716 const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
15717 const TargetRegisterClass *RC32 =
15718 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15719 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15720 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15721 unsigned Tmp = MRI.createVirtualRegister(RC32);
15723 unsigned Undef = MRI.createVirtualRegister(RC32);
15724 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15726 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15729 .addImm(X86::sub_8bit);
15730 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15733 .addImm(X86::sub_8bit);
15735 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15739 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15740 .addReg(Tmp, 0, X86::sub_8bit);
15743 // Use pseudo select and lower them.
15744 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15745 "Invalid atomic-load-op transformation!");
15746 unsigned SelOpc = getPseudoCMOVOpc(VT);
15747 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15748 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15749 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15750 .addReg(SrcReg).addReg(t4)
15752 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15753 // Replace the original PHI node as mainMBB is changed after CMOV
15755 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15756 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15757 Phi->eraseFromParent();
15763 // Copy PhyReg back from virtual register.
15764 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15767 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15768 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15769 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15771 NewMO.setIsKill(false);
15772 MIB.addOperand(NewMO);
15775 MIB.setMemRefs(MMOBegin, MMOEnd);
15777 // Copy PhyReg back to virtual register.
15778 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15781 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15783 mainMBB->addSuccessor(origMainMBB);
15784 mainMBB->addSuccessor(sinkMBB);
15787 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15788 TII->get(TargetOpcode::COPY), DstReg)
15791 MI->eraseFromParent();
15795 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15796 // instructions. They will be translated into a spin-loop or compare-exchange
15800 // dst = atomic-fetch-op MI.addr, MI.val
15806 // t1L = LOAD [MI.addr + 0]
15807 // t1H = LOAD [MI.addr + 4]
15809 // t4L = phi(t1L, t3L / loop)
15810 // t4H = phi(t1H, t3H / loop)
15811 // t2L = OP MI.val.lo, t4L
15812 // t2H = OP MI.val.hi, t4H
15817 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15825 MachineBasicBlock *
15826 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15827 MachineBasicBlock *MBB) const {
15828 MachineFunction *MF = MBB->getParent();
15829 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15830 DebugLoc DL = MI->getDebugLoc();
15832 MachineRegisterInfo &MRI = MF->getRegInfo();
15834 const BasicBlock *BB = MBB->getBasicBlock();
15835 MachineFunction::iterator I = MBB;
15838 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15839 "Unexpected number of operands");
15841 assert(MI->hasOneMemOperand() &&
15842 "Expected atomic-load-op32 to have one memoperand");
15844 // Memory Reference
15845 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15846 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15848 unsigned DstLoReg, DstHiReg;
15849 unsigned SrcLoReg, SrcHiReg;
15850 unsigned MemOpndSlot;
15852 unsigned CurOp = 0;
15854 DstLoReg = MI->getOperand(CurOp++).getReg();
15855 DstHiReg = MI->getOperand(CurOp++).getReg();
15856 MemOpndSlot = CurOp;
15857 CurOp += X86::AddrNumOperands;
15858 SrcLoReg = MI->getOperand(CurOp++).getReg();
15859 SrcHiReg = MI->getOperand(CurOp++).getReg();
15861 const TargetRegisterClass *RC = &X86::GR32RegClass;
15862 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15864 unsigned t1L = MRI.createVirtualRegister(RC);
15865 unsigned t1H = MRI.createVirtualRegister(RC);
15866 unsigned t2L = MRI.createVirtualRegister(RC);
15867 unsigned t2H = MRI.createVirtualRegister(RC);
15868 unsigned t3L = MRI.createVirtualRegister(RC);
15869 unsigned t3H = MRI.createVirtualRegister(RC);
15870 unsigned t4L = MRI.createVirtualRegister(RC);
15871 unsigned t4H = MRI.createVirtualRegister(RC);
15873 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15874 unsigned LOADOpc = X86::MOV32rm;
15876 // For the atomic load-arith operator, we generate
15879 // t1L = LOAD [MI.addr + 0]
15880 // t1H = LOAD [MI.addr + 4]
15882 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15883 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15884 // t2L = OP MI.val.lo, t4L
15885 // t2H = OP MI.val.hi, t4H
15888 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15896 MachineBasicBlock *thisMBB = MBB;
15897 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15898 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15899 MF->insert(I, mainMBB);
15900 MF->insert(I, sinkMBB);
15902 MachineInstrBuilder MIB;
15904 // Transfer the remainder of BB and its successor edges to sinkMBB.
15905 sinkMBB->splice(sinkMBB->begin(), MBB,
15906 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15907 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15911 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15912 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15913 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15915 NewMO.setIsKill(false);
15916 MIB.addOperand(NewMO);
15918 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15919 unsigned flags = (*MMOI)->getFlags();
15920 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15921 MachineMemOperand *MMO =
15922 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15923 (*MMOI)->getSize(),
15924 (*MMOI)->getBaseAlignment(),
15925 (*MMOI)->getTBAAInfo(),
15926 (*MMOI)->getRanges());
15927 MIB.addMemOperand(MMO);
15929 MachineInstr *LowMI = MIB;
15932 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15933 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15934 if (i == X86::AddrDisp) {
15935 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15937 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15939 NewMO.setIsKill(false);
15940 MIB.addOperand(NewMO);
15943 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15945 thisMBB->addSuccessor(mainMBB);
15948 MachineBasicBlock *origMainMBB = mainMBB;
15951 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15952 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15953 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15954 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15956 unsigned Opc = MI->getOpcode();
15959 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15960 case X86::ATOMAND6432:
15961 case X86::ATOMOR6432:
15962 case X86::ATOMXOR6432:
15963 case X86::ATOMADD6432:
15964 case X86::ATOMSUB6432: {
15966 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15967 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15969 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15973 case X86::ATOMNAND6432: {
15974 unsigned HiOpc, NOTOpc;
15975 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15976 unsigned TmpL = MRI.createVirtualRegister(RC);
15977 unsigned TmpH = MRI.createVirtualRegister(RC);
15978 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15980 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15982 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15983 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15986 case X86::ATOMMAX6432:
15987 case X86::ATOMMIN6432:
15988 case X86::ATOMUMAX6432:
15989 case X86::ATOMUMIN6432: {
15991 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15992 unsigned cL = MRI.createVirtualRegister(RC8);
15993 unsigned cH = MRI.createVirtualRegister(RC8);
15994 unsigned cL32 = MRI.createVirtualRegister(RC);
15995 unsigned cH32 = MRI.createVirtualRegister(RC);
15996 unsigned cc = MRI.createVirtualRegister(RC);
15997 // cl := cmp src_lo, lo
15998 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15999 .addReg(SrcLoReg).addReg(t4L);
16000 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16001 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16002 // ch := cmp src_hi, hi
16003 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16004 .addReg(SrcHiReg).addReg(t4H);
16005 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16006 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16007 // cc := if (src_hi == hi) ? cl : ch;
16008 if (Subtarget->hasCMov()) {
16009 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16010 .addReg(cH32).addReg(cL32);
16012 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16013 .addReg(cH32).addReg(cL32)
16014 .addImm(X86::COND_E);
16015 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16017 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16018 if (Subtarget->hasCMov()) {
16019 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16020 .addReg(SrcLoReg).addReg(t4L);
16021 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16022 .addReg(SrcHiReg).addReg(t4H);
16024 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16025 .addReg(SrcLoReg).addReg(t4L)
16026 .addImm(X86::COND_NE);
16027 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16028 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16029 // 2nd CMOV lowering.
16030 mainMBB->addLiveIn(X86::EFLAGS);
16031 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16032 .addReg(SrcHiReg).addReg(t4H)
16033 .addImm(X86::COND_NE);
16034 mainMBB = EmitLoweredSelect(MIB, mainMBB);
16035 // Replace the original PHI node as mainMBB is changed after CMOV
16037 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16038 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16039 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16040 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16041 PhiL->eraseFromParent();
16042 PhiH->eraseFromParent();
16046 case X86::ATOMSWAP6432: {
16048 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16049 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16050 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16055 // Copy EDX:EAX back from HiReg:LoReg
16056 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16057 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16058 // Copy ECX:EBX from t1H:t1L
16059 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16060 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16062 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16063 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16064 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16066 NewMO.setIsKill(false);
16067 MIB.addOperand(NewMO);
16069 MIB.setMemRefs(MMOBegin, MMOEnd);
16071 // Copy EDX:EAX back to t3H:t3L
16072 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16073 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16075 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16077 mainMBB->addSuccessor(origMainMBB);
16078 mainMBB->addSuccessor(sinkMBB);
16081 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16082 TII->get(TargetOpcode::COPY), DstLoReg)
16084 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16085 TII->get(TargetOpcode::COPY), DstHiReg)
16088 MI->eraseFromParent();
16092 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16093 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16094 // in the .td file.
16095 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16096 const TargetInstrInfo *TII) {
16098 switch (MI->getOpcode()) {
16099 default: llvm_unreachable("illegal opcode!");
16100 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16101 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16102 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16103 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16104 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16105 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16106 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16107 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16110 DebugLoc dl = MI->getDebugLoc();
16111 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16113 unsigned NumArgs = MI->getNumOperands();
16114 for (unsigned i = 1; i < NumArgs; ++i) {
16115 MachineOperand &Op = MI->getOperand(i);
16116 if (!(Op.isReg() && Op.isImplicit()))
16117 MIB.addOperand(Op);
16119 if (MI->hasOneMemOperand())
16120 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16122 BuildMI(*BB, MI, dl,
16123 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16124 .addReg(X86::XMM0);
16126 MI->eraseFromParent();
16130 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16131 // defs in an instruction pattern
16132 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16133 const TargetInstrInfo *TII) {
16135 switch (MI->getOpcode()) {
16136 default: llvm_unreachable("illegal opcode!");
16137 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16138 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16139 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16140 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16141 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16142 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16143 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16144 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16147 DebugLoc dl = MI->getDebugLoc();
16148 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16150 unsigned NumArgs = MI->getNumOperands(); // remove the results
16151 for (unsigned i = 1; i < NumArgs; ++i) {
16152 MachineOperand &Op = MI->getOperand(i);
16153 if (!(Op.isReg() && Op.isImplicit()))
16154 MIB.addOperand(Op);
16156 if (MI->hasOneMemOperand())
16157 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16159 BuildMI(*BB, MI, dl,
16160 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16163 MI->eraseFromParent();
16167 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16168 const TargetInstrInfo *TII,
16169 const X86Subtarget* Subtarget) {
16170 DebugLoc dl = MI->getDebugLoc();
16172 // Address into RAX/EAX, other two args into ECX, EDX.
16173 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16174 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16175 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16176 for (int i = 0; i < X86::AddrNumOperands; ++i)
16177 MIB.addOperand(MI->getOperand(i));
16179 unsigned ValOps = X86::AddrNumOperands;
16180 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16181 .addReg(MI->getOperand(ValOps).getReg());
16182 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16183 .addReg(MI->getOperand(ValOps+1).getReg());
16185 // The instruction doesn't actually take any operands though.
16186 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16188 MI->eraseFromParent(); // The pseudo is gone now.
16192 MachineBasicBlock *
16193 X86TargetLowering::EmitVAARG64WithCustomInserter(
16195 MachineBasicBlock *MBB) const {
16196 // Emit va_arg instruction on X86-64.
16198 // Operands to this pseudo-instruction:
16199 // 0 ) Output : destination address (reg)
16200 // 1-5) Input : va_list address (addr, i64mem)
16201 // 6 ) ArgSize : Size (in bytes) of vararg type
16202 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16203 // 8 ) Align : Alignment of type
16204 // 9 ) EFLAGS (implicit-def)
16206 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16207 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16209 unsigned DestReg = MI->getOperand(0).getReg();
16210 MachineOperand &Base = MI->getOperand(1);
16211 MachineOperand &Scale = MI->getOperand(2);
16212 MachineOperand &Index = MI->getOperand(3);
16213 MachineOperand &Disp = MI->getOperand(4);
16214 MachineOperand &Segment = MI->getOperand(5);
16215 unsigned ArgSize = MI->getOperand(6).getImm();
16216 unsigned ArgMode = MI->getOperand(7).getImm();
16217 unsigned Align = MI->getOperand(8).getImm();
16219 // Memory Reference
16220 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16221 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16222 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16224 // Machine Information
16225 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16226 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16227 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16228 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16229 DebugLoc DL = MI->getDebugLoc();
16231 // struct va_list {
16234 // i64 overflow_area (address)
16235 // i64 reg_save_area (address)
16237 // sizeof(va_list) = 24
16238 // alignment(va_list) = 8
16240 unsigned TotalNumIntRegs = 6;
16241 unsigned TotalNumXMMRegs = 8;
16242 bool UseGPOffset = (ArgMode == 1);
16243 bool UseFPOffset = (ArgMode == 2);
16244 unsigned MaxOffset = TotalNumIntRegs * 8 +
16245 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16247 /* Align ArgSize to a multiple of 8 */
16248 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16249 bool NeedsAlign = (Align > 8);
16251 MachineBasicBlock *thisMBB = MBB;
16252 MachineBasicBlock *overflowMBB;
16253 MachineBasicBlock *offsetMBB;
16254 MachineBasicBlock *endMBB;
16256 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16257 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16258 unsigned OffsetReg = 0;
16260 if (!UseGPOffset && !UseFPOffset) {
16261 // If we only pull from the overflow region, we don't create a branch.
16262 // We don't need to alter control flow.
16263 OffsetDestReg = 0; // unused
16264 OverflowDestReg = DestReg;
16266 offsetMBB = nullptr;
16267 overflowMBB = thisMBB;
16270 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16271 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16272 // If not, pull from overflow_area. (branch to overflowMBB)
16277 // offsetMBB overflowMBB
16282 // Registers for the PHI in endMBB
16283 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16284 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16286 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16287 MachineFunction *MF = MBB->getParent();
16288 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16289 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16290 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16292 MachineFunction::iterator MBBIter = MBB;
16295 // Insert the new basic blocks
16296 MF->insert(MBBIter, offsetMBB);
16297 MF->insert(MBBIter, overflowMBB);
16298 MF->insert(MBBIter, endMBB);
16300 // Transfer the remainder of MBB and its successor edges to endMBB.
16301 endMBB->splice(endMBB->begin(), thisMBB,
16302 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16303 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16305 // Make offsetMBB and overflowMBB successors of thisMBB
16306 thisMBB->addSuccessor(offsetMBB);
16307 thisMBB->addSuccessor(overflowMBB);
16309 // endMBB is a successor of both offsetMBB and overflowMBB
16310 offsetMBB->addSuccessor(endMBB);
16311 overflowMBB->addSuccessor(endMBB);
16313 // Load the offset value into a register
16314 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16315 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16319 .addDisp(Disp, UseFPOffset ? 4 : 0)
16320 .addOperand(Segment)
16321 .setMemRefs(MMOBegin, MMOEnd);
16323 // Check if there is enough room left to pull this argument.
16324 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16326 .addImm(MaxOffset + 8 - ArgSizeA8);
16328 // Branch to "overflowMBB" if offset >= max
16329 // Fall through to "offsetMBB" otherwise
16330 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16331 .addMBB(overflowMBB);
16334 // In offsetMBB, emit code to use the reg_save_area.
16336 assert(OffsetReg != 0);
16338 // Read the reg_save_area address.
16339 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16340 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16345 .addOperand(Segment)
16346 .setMemRefs(MMOBegin, MMOEnd);
16348 // Zero-extend the offset
16349 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16350 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16353 .addImm(X86::sub_32bit);
16355 // Add the offset to the reg_save_area to get the final address.
16356 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16357 .addReg(OffsetReg64)
16358 .addReg(RegSaveReg);
16360 // Compute the offset for the next argument
16361 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16362 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16364 .addImm(UseFPOffset ? 16 : 8);
16366 // Store it back into the va_list.
16367 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16371 .addDisp(Disp, UseFPOffset ? 4 : 0)
16372 .addOperand(Segment)
16373 .addReg(NextOffsetReg)
16374 .setMemRefs(MMOBegin, MMOEnd);
16377 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16382 // Emit code to use overflow area
16385 // Load the overflow_area address into a register.
16386 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16387 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16392 .addOperand(Segment)
16393 .setMemRefs(MMOBegin, MMOEnd);
16395 // If we need to align it, do so. Otherwise, just copy the address
16396 // to OverflowDestReg.
16398 // Align the overflow address
16399 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16400 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16402 // aligned_addr = (addr + (align-1)) & ~(align-1)
16403 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16404 .addReg(OverflowAddrReg)
16407 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16409 .addImm(~(uint64_t)(Align-1));
16411 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16412 .addReg(OverflowAddrReg);
16415 // Compute the next overflow address after this argument.
16416 // (the overflow address should be kept 8-byte aligned)
16417 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16418 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16419 .addReg(OverflowDestReg)
16420 .addImm(ArgSizeA8);
16422 // Store the new overflow address.
16423 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16428 .addOperand(Segment)
16429 .addReg(NextAddrReg)
16430 .setMemRefs(MMOBegin, MMOEnd);
16432 // If we branched, emit the PHI to the front of endMBB.
16434 BuildMI(*endMBB, endMBB->begin(), DL,
16435 TII->get(X86::PHI), DestReg)
16436 .addReg(OffsetDestReg).addMBB(offsetMBB)
16437 .addReg(OverflowDestReg).addMBB(overflowMBB);
16440 // Erase the pseudo instruction
16441 MI->eraseFromParent();
16446 MachineBasicBlock *
16447 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16449 MachineBasicBlock *MBB) const {
16450 // Emit code to save XMM registers to the stack. The ABI says that the
16451 // number of registers to save is given in %al, so it's theoretically
16452 // possible to do an indirect jump trick to avoid saving all of them,
16453 // however this code takes a simpler approach and just executes all
16454 // of the stores if %al is non-zero. It's less code, and it's probably
16455 // easier on the hardware branch predictor, and stores aren't all that
16456 // expensive anyway.
16458 // Create the new basic blocks. One block contains all the XMM stores,
16459 // and one block is the final destination regardless of whether any
16460 // stores were performed.
16461 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16462 MachineFunction *F = MBB->getParent();
16463 MachineFunction::iterator MBBIter = MBB;
16465 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16466 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16467 F->insert(MBBIter, XMMSaveMBB);
16468 F->insert(MBBIter, EndMBB);
16470 // Transfer the remainder of MBB and its successor edges to EndMBB.
16471 EndMBB->splice(EndMBB->begin(), MBB,
16472 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16473 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16475 // The original block will now fall through to the XMM save block.
16476 MBB->addSuccessor(XMMSaveMBB);
16477 // The XMMSaveMBB will fall through to the end block.
16478 XMMSaveMBB->addSuccessor(EndMBB);
16480 // Now add the instructions.
16481 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16482 DebugLoc DL = MI->getDebugLoc();
16484 unsigned CountReg = MI->getOperand(0).getReg();
16485 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16486 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16488 if (!Subtarget->isTargetWin64()) {
16489 // If %al is 0, branch around the XMM save block.
16490 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16491 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16492 MBB->addSuccessor(EndMBB);
16495 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16496 // that was just emitted, but clearly shouldn't be "saved".
16497 assert((MI->getNumOperands() <= 3 ||
16498 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16499 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16500 && "Expected last argument to be EFLAGS");
16501 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16502 // In the XMM save block, save all the XMM argument registers.
16503 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16504 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16505 MachineMemOperand *MMO =
16506 F->getMachineMemOperand(
16507 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16508 MachineMemOperand::MOStore,
16509 /*Size=*/16, /*Align=*/16);
16510 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16511 .addFrameIndex(RegSaveFrameIndex)
16512 .addImm(/*Scale=*/1)
16513 .addReg(/*IndexReg=*/0)
16514 .addImm(/*Disp=*/Offset)
16515 .addReg(/*Segment=*/0)
16516 .addReg(MI->getOperand(i).getReg())
16517 .addMemOperand(MMO);
16520 MI->eraseFromParent(); // The pseudo instruction is gone now.
16525 // The EFLAGS operand of SelectItr might be missing a kill marker
16526 // because there were multiple uses of EFLAGS, and ISel didn't know
16527 // which to mark. Figure out whether SelectItr should have had a
16528 // kill marker, and set it if it should. Returns the correct kill
16530 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16531 MachineBasicBlock* BB,
16532 const TargetRegisterInfo* TRI) {
16533 // Scan forward through BB for a use/def of EFLAGS.
16534 MachineBasicBlock::iterator miI(std::next(SelectItr));
16535 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16536 const MachineInstr& mi = *miI;
16537 if (mi.readsRegister(X86::EFLAGS))
16539 if (mi.definesRegister(X86::EFLAGS))
16540 break; // Should have kill-flag - update below.
16543 // If we hit the end of the block, check whether EFLAGS is live into a
16545 if (miI == BB->end()) {
16546 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16547 sEnd = BB->succ_end();
16548 sItr != sEnd; ++sItr) {
16549 MachineBasicBlock* succ = *sItr;
16550 if (succ->isLiveIn(X86::EFLAGS))
16555 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16556 // out. SelectMI should have a kill flag on EFLAGS.
16557 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16561 MachineBasicBlock *
16562 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16563 MachineBasicBlock *BB) const {
16564 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16565 DebugLoc DL = MI->getDebugLoc();
16567 // To "insert" a SELECT_CC instruction, we actually have to insert the
16568 // diamond control-flow pattern. The incoming instruction knows the
16569 // destination vreg to set, the condition code register to branch on, the
16570 // true/false values to select between, and a branch opcode to use.
16571 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16572 MachineFunction::iterator It = BB;
16578 // cmpTY ccX, r1, r2
16580 // fallthrough --> copy0MBB
16581 MachineBasicBlock *thisMBB = BB;
16582 MachineFunction *F = BB->getParent();
16583 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16584 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16585 F->insert(It, copy0MBB);
16586 F->insert(It, sinkMBB);
16588 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16589 // live into the sink and copy blocks.
16590 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16591 if (!MI->killsRegister(X86::EFLAGS) &&
16592 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16593 copy0MBB->addLiveIn(X86::EFLAGS);
16594 sinkMBB->addLiveIn(X86::EFLAGS);
16597 // Transfer the remainder of BB and its successor edges to sinkMBB.
16598 sinkMBB->splice(sinkMBB->begin(), BB,
16599 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16600 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16602 // Add the true and fallthrough blocks as its successors.
16603 BB->addSuccessor(copy0MBB);
16604 BB->addSuccessor(sinkMBB);
16606 // Create the conditional branch instruction.
16608 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16609 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16612 // %FalseValue = ...
16613 // # fallthrough to sinkMBB
16614 copy0MBB->addSuccessor(sinkMBB);
16617 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16619 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16620 TII->get(X86::PHI), MI->getOperand(0).getReg())
16621 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16622 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16624 MI->eraseFromParent(); // The pseudo instruction is gone now.
16628 MachineBasicBlock *
16629 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16630 bool Is64Bit) const {
16631 MachineFunction *MF = BB->getParent();
16632 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16633 DebugLoc DL = MI->getDebugLoc();
16634 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16636 assert(MF->shouldSplitStack());
16638 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16639 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16642 // ... [Till the alloca]
16643 // If stacklet is not large enough, jump to mallocMBB
16646 // Allocate by subtracting from RSP
16647 // Jump to continueMBB
16650 // Allocate by call to runtime
16654 // [rest of original BB]
16657 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16658 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16659 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16661 MachineRegisterInfo &MRI = MF->getRegInfo();
16662 const TargetRegisterClass *AddrRegClass =
16663 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16665 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16666 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16667 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16668 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16669 sizeVReg = MI->getOperand(1).getReg(),
16670 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16672 MachineFunction::iterator MBBIter = BB;
16675 MF->insert(MBBIter, bumpMBB);
16676 MF->insert(MBBIter, mallocMBB);
16677 MF->insert(MBBIter, continueMBB);
16679 continueMBB->splice(continueMBB->begin(), BB,
16680 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16681 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16683 // Add code to the main basic block to check if the stack limit has been hit,
16684 // and if so, jump to mallocMBB otherwise to bumpMBB.
16685 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16686 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16687 .addReg(tmpSPVReg).addReg(sizeVReg);
16688 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16689 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16690 .addReg(SPLimitVReg);
16691 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16693 // bumpMBB simply decreases the stack pointer, since we know the current
16694 // stacklet has enough space.
16695 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16696 .addReg(SPLimitVReg);
16697 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16698 .addReg(SPLimitVReg);
16699 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16701 // Calls into a routine in libgcc to allocate more space from the heap.
16702 const uint32_t *RegMask =
16703 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16705 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16707 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16708 .addExternalSymbol("__morestack_allocate_stack_space")
16709 .addRegMask(RegMask)
16710 .addReg(X86::RDI, RegState::Implicit)
16711 .addReg(X86::RAX, RegState::ImplicitDefine);
16713 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16715 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16716 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16717 .addExternalSymbol("__morestack_allocate_stack_space")
16718 .addRegMask(RegMask)
16719 .addReg(X86::EAX, RegState::ImplicitDefine);
16723 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16726 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16727 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16728 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16730 // Set up the CFG correctly.
16731 BB->addSuccessor(bumpMBB);
16732 BB->addSuccessor(mallocMBB);
16733 mallocMBB->addSuccessor(continueMBB);
16734 bumpMBB->addSuccessor(continueMBB);
16736 // Take care of the PHI nodes.
16737 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16738 MI->getOperand(0).getReg())
16739 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16740 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16742 // Delete the original pseudo instruction.
16743 MI->eraseFromParent();
16746 return continueMBB;
16749 MachineBasicBlock *
16750 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16751 MachineBasicBlock *BB) const {
16752 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16753 DebugLoc DL = MI->getDebugLoc();
16755 assert(!Subtarget->isTargetMacho());
16757 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16758 // non-trivial part is impdef of ESP.
16760 if (Subtarget->isTargetWin64()) {
16761 if (Subtarget->isTargetCygMing()) {
16762 // ___chkstk(Mingw64):
16763 // Clobbers R10, R11, RAX and EFLAGS.
16765 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16766 .addExternalSymbol("___chkstk")
16767 .addReg(X86::RAX, RegState::Implicit)
16768 .addReg(X86::RSP, RegState::Implicit)
16769 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16770 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16771 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16773 // __chkstk(MSVCRT): does not update stack pointer.
16774 // Clobbers R10, R11 and EFLAGS.
16775 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16776 .addExternalSymbol("__chkstk")
16777 .addReg(X86::RAX, RegState::Implicit)
16778 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16779 // RAX has the offset to be subtracted from RSP.
16780 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16785 const char *StackProbeSymbol =
16786 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16788 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16789 .addExternalSymbol(StackProbeSymbol)
16790 .addReg(X86::EAX, RegState::Implicit)
16791 .addReg(X86::ESP, RegState::Implicit)
16792 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16793 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16794 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16797 MI->eraseFromParent(); // The pseudo instruction is gone now.
16801 MachineBasicBlock *
16802 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16803 MachineBasicBlock *BB) const {
16804 // This is pretty easy. We're taking the value that we received from
16805 // our load from the relocation, sticking it in either RDI (x86-64)
16806 // or EAX and doing an indirect call. The return value will then
16807 // be in the normal return register.
16808 MachineFunction *F = BB->getParent();
16809 const X86InstrInfo *TII
16810 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
16811 DebugLoc DL = MI->getDebugLoc();
16813 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16814 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16816 // Get a register mask for the lowered call.
16817 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16818 // proper register mask.
16819 const uint32_t *RegMask =
16820 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16821 if (Subtarget->is64Bit()) {
16822 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16823 TII->get(X86::MOV64rm), X86::RDI)
16825 .addImm(0).addReg(0)
16826 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16827 MI->getOperand(3).getTargetFlags())
16829 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16830 addDirectMem(MIB, X86::RDI);
16831 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16832 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
16833 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16834 TII->get(X86::MOV32rm), X86::EAX)
16836 .addImm(0).addReg(0)
16837 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16838 MI->getOperand(3).getTargetFlags())
16840 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16841 addDirectMem(MIB, X86::EAX);
16842 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16844 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16845 TII->get(X86::MOV32rm), X86::EAX)
16846 .addReg(TII->getGlobalBaseReg(F))
16847 .addImm(0).addReg(0)
16848 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16849 MI->getOperand(3).getTargetFlags())
16851 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16852 addDirectMem(MIB, X86::EAX);
16853 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16856 MI->eraseFromParent(); // The pseudo instruction is gone now.
16860 MachineBasicBlock *
16861 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16862 MachineBasicBlock *MBB) const {
16863 DebugLoc DL = MI->getDebugLoc();
16864 MachineFunction *MF = MBB->getParent();
16865 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16866 MachineRegisterInfo &MRI = MF->getRegInfo();
16868 const BasicBlock *BB = MBB->getBasicBlock();
16869 MachineFunction::iterator I = MBB;
16872 // Memory Reference
16873 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16874 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16877 unsigned MemOpndSlot = 0;
16879 unsigned CurOp = 0;
16881 DstReg = MI->getOperand(CurOp++).getReg();
16882 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16883 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16884 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16885 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16887 MemOpndSlot = CurOp;
16889 MVT PVT = getPointerTy();
16890 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16891 "Invalid Pointer Size!");
16893 // For v = setjmp(buf), we generate
16896 // buf[LabelOffset] = restoreMBB
16897 // SjLjSetup restoreMBB
16903 // v = phi(main, restore)
16908 MachineBasicBlock *thisMBB = MBB;
16909 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16910 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16911 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16912 MF->insert(I, mainMBB);
16913 MF->insert(I, sinkMBB);
16914 MF->push_back(restoreMBB);
16916 MachineInstrBuilder MIB;
16918 // Transfer the remainder of BB and its successor edges to sinkMBB.
16919 sinkMBB->splice(sinkMBB->begin(), MBB,
16920 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16921 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16924 unsigned PtrStoreOpc = 0;
16925 unsigned LabelReg = 0;
16926 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16927 Reloc::Model RM = MF->getTarget().getRelocationModel();
16928 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
16929 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16931 // Prepare IP either in reg or imm.
16932 if (!UseImmLabel) {
16933 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16934 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16935 LabelReg = MRI.createVirtualRegister(PtrRC);
16936 if (Subtarget->is64Bit()) {
16937 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16941 .addMBB(restoreMBB)
16944 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16945 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16946 .addReg(XII->getGlobalBaseReg(MF))
16949 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16953 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16955 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16956 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16957 if (i == X86::AddrDisp)
16958 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16960 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16963 MIB.addReg(LabelReg);
16965 MIB.addMBB(restoreMBB);
16966 MIB.setMemRefs(MMOBegin, MMOEnd);
16968 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16969 .addMBB(restoreMBB);
16971 const X86RegisterInfo *RegInfo =
16972 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
16973 MIB.addRegMask(RegInfo->getNoPreservedMask());
16974 thisMBB->addSuccessor(mainMBB);
16975 thisMBB->addSuccessor(restoreMBB);
16979 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16980 mainMBB->addSuccessor(sinkMBB);
16983 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16984 TII->get(X86::PHI), DstReg)
16985 .addReg(mainDstReg).addMBB(mainMBB)
16986 .addReg(restoreDstReg).addMBB(restoreMBB);
16989 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16990 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16991 restoreMBB->addSuccessor(sinkMBB);
16993 MI->eraseFromParent();
16997 MachineBasicBlock *
16998 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16999 MachineBasicBlock *MBB) const {
17000 DebugLoc DL = MI->getDebugLoc();
17001 MachineFunction *MF = MBB->getParent();
17002 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17003 MachineRegisterInfo &MRI = MF->getRegInfo();
17005 // Memory Reference
17006 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17007 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17009 MVT PVT = getPointerTy();
17010 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17011 "Invalid Pointer Size!");
17013 const TargetRegisterClass *RC =
17014 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17015 unsigned Tmp = MRI.createVirtualRegister(RC);
17016 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17017 const X86RegisterInfo *RegInfo =
17018 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17019 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17020 unsigned SP = RegInfo->getStackRegister();
17022 MachineInstrBuilder MIB;
17024 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17025 const int64_t SPOffset = 2 * PVT.getStoreSize();
17027 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17028 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17031 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17032 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17033 MIB.addOperand(MI->getOperand(i));
17034 MIB.setMemRefs(MMOBegin, MMOEnd);
17036 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17037 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17038 if (i == X86::AddrDisp)
17039 MIB.addDisp(MI->getOperand(i), LabelOffset);
17041 MIB.addOperand(MI->getOperand(i));
17043 MIB.setMemRefs(MMOBegin, MMOEnd);
17045 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17046 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17047 if (i == X86::AddrDisp)
17048 MIB.addDisp(MI->getOperand(i), SPOffset);
17050 MIB.addOperand(MI->getOperand(i));
17052 MIB.setMemRefs(MMOBegin, MMOEnd);
17054 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17056 MI->eraseFromParent();
17060 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17061 // accumulator loops. Writing back to the accumulator allows the coalescer
17062 // to remove extra copies in the loop.
17063 MachineBasicBlock *
17064 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17065 MachineBasicBlock *MBB) const {
17066 MachineOperand &AddendOp = MI->getOperand(3);
17068 // Bail out early if the addend isn't a register - we can't switch these.
17069 if (!AddendOp.isReg())
17072 MachineFunction &MF = *MBB->getParent();
17073 MachineRegisterInfo &MRI = MF.getRegInfo();
17075 // Check whether the addend is defined by a PHI:
17076 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17077 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17078 if (!AddendDef.isPHI())
17081 // Look for the following pattern:
17083 // %addend = phi [%entry, 0], [%loop, %result]
17085 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17089 // %addend = phi [%entry, 0], [%loop, %result]
17091 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17093 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17094 assert(AddendDef.getOperand(i).isReg());
17095 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17096 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17097 if (&PHISrcInst == MI) {
17098 // Found a matching instruction.
17099 unsigned NewFMAOpc = 0;
17100 switch (MI->getOpcode()) {
17101 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17102 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17103 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17104 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17105 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17106 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17107 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17108 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17109 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17110 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17111 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17112 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17113 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17114 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17115 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17116 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17117 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17118 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17119 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17120 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17121 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17122 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17123 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17124 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17125 default: llvm_unreachable("Unrecognized FMA variant.");
17128 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17129 MachineInstrBuilder MIB =
17130 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17131 .addOperand(MI->getOperand(0))
17132 .addOperand(MI->getOperand(3))
17133 .addOperand(MI->getOperand(2))
17134 .addOperand(MI->getOperand(1));
17135 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17136 MI->eraseFromParent();
17143 MachineBasicBlock *
17144 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17145 MachineBasicBlock *BB) const {
17146 switch (MI->getOpcode()) {
17147 default: llvm_unreachable("Unexpected instr type to insert");
17148 case X86::TAILJMPd64:
17149 case X86::TAILJMPr64:
17150 case X86::TAILJMPm64:
17151 llvm_unreachable("TAILJMP64 would not be touched here.");
17152 case X86::TCRETURNdi64:
17153 case X86::TCRETURNri64:
17154 case X86::TCRETURNmi64:
17156 case X86::WIN_ALLOCA:
17157 return EmitLoweredWinAlloca(MI, BB);
17158 case X86::SEG_ALLOCA_32:
17159 return EmitLoweredSegAlloca(MI, BB, false);
17160 case X86::SEG_ALLOCA_64:
17161 return EmitLoweredSegAlloca(MI, BB, true);
17162 case X86::TLSCall_32:
17163 case X86::TLSCall_64:
17164 return EmitLoweredTLSCall(MI, BB);
17165 case X86::CMOV_GR8:
17166 case X86::CMOV_FR32:
17167 case X86::CMOV_FR64:
17168 case X86::CMOV_V4F32:
17169 case X86::CMOV_V2F64:
17170 case X86::CMOV_V2I64:
17171 case X86::CMOV_V8F32:
17172 case X86::CMOV_V4F64:
17173 case X86::CMOV_V4I64:
17174 case X86::CMOV_V16F32:
17175 case X86::CMOV_V8F64:
17176 case X86::CMOV_V8I64:
17177 case X86::CMOV_GR16:
17178 case X86::CMOV_GR32:
17179 case X86::CMOV_RFP32:
17180 case X86::CMOV_RFP64:
17181 case X86::CMOV_RFP80:
17182 return EmitLoweredSelect(MI, BB);
17184 case X86::FP32_TO_INT16_IN_MEM:
17185 case X86::FP32_TO_INT32_IN_MEM:
17186 case X86::FP32_TO_INT64_IN_MEM:
17187 case X86::FP64_TO_INT16_IN_MEM:
17188 case X86::FP64_TO_INT32_IN_MEM:
17189 case X86::FP64_TO_INT64_IN_MEM:
17190 case X86::FP80_TO_INT16_IN_MEM:
17191 case X86::FP80_TO_INT32_IN_MEM:
17192 case X86::FP80_TO_INT64_IN_MEM: {
17193 MachineFunction *F = BB->getParent();
17194 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17195 DebugLoc DL = MI->getDebugLoc();
17197 // Change the floating point control register to use "round towards zero"
17198 // mode when truncating to an integer value.
17199 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17200 addFrameReference(BuildMI(*BB, MI, DL,
17201 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17203 // Load the old value of the high byte of the control word...
17205 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17206 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17209 // Set the high part to be round to zero...
17210 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17213 // Reload the modified control word now...
17214 addFrameReference(BuildMI(*BB, MI, DL,
17215 TII->get(X86::FLDCW16m)), CWFrameIdx);
17217 // Restore the memory image of control word to original value
17218 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17221 // Get the X86 opcode to use.
17223 switch (MI->getOpcode()) {
17224 default: llvm_unreachable("illegal opcode!");
17225 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17226 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17227 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17228 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17229 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17230 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17231 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17232 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17233 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17237 MachineOperand &Op = MI->getOperand(0);
17239 AM.BaseType = X86AddressMode::RegBase;
17240 AM.Base.Reg = Op.getReg();
17242 AM.BaseType = X86AddressMode::FrameIndexBase;
17243 AM.Base.FrameIndex = Op.getIndex();
17245 Op = MI->getOperand(1);
17247 AM.Scale = Op.getImm();
17248 Op = MI->getOperand(2);
17250 AM.IndexReg = Op.getImm();
17251 Op = MI->getOperand(3);
17252 if (Op.isGlobal()) {
17253 AM.GV = Op.getGlobal();
17255 AM.Disp = Op.getImm();
17257 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17258 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17260 // Reload the original control word now.
17261 addFrameReference(BuildMI(*BB, MI, DL,
17262 TII->get(X86::FLDCW16m)), CWFrameIdx);
17264 MI->eraseFromParent(); // The pseudo instruction is gone now.
17267 // String/text processing lowering.
17268 case X86::PCMPISTRM128REG:
17269 case X86::VPCMPISTRM128REG:
17270 case X86::PCMPISTRM128MEM:
17271 case X86::VPCMPISTRM128MEM:
17272 case X86::PCMPESTRM128REG:
17273 case X86::VPCMPESTRM128REG:
17274 case X86::PCMPESTRM128MEM:
17275 case X86::VPCMPESTRM128MEM:
17276 assert(Subtarget->hasSSE42() &&
17277 "Target must have SSE4.2 or AVX features enabled");
17278 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17280 // String/text processing lowering.
17281 case X86::PCMPISTRIREG:
17282 case X86::VPCMPISTRIREG:
17283 case X86::PCMPISTRIMEM:
17284 case X86::VPCMPISTRIMEM:
17285 case X86::PCMPESTRIREG:
17286 case X86::VPCMPESTRIREG:
17287 case X86::PCMPESTRIMEM:
17288 case X86::VPCMPESTRIMEM:
17289 assert(Subtarget->hasSSE42() &&
17290 "Target must have SSE4.2 or AVX features enabled");
17291 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17293 // Thread synchronization.
17295 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17299 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17301 // Atomic Lowering.
17302 case X86::ATOMAND8:
17303 case X86::ATOMAND16:
17304 case X86::ATOMAND32:
17305 case X86::ATOMAND64:
17308 case X86::ATOMOR16:
17309 case X86::ATOMOR32:
17310 case X86::ATOMOR64:
17312 case X86::ATOMXOR16:
17313 case X86::ATOMXOR8:
17314 case X86::ATOMXOR32:
17315 case X86::ATOMXOR64:
17317 case X86::ATOMNAND8:
17318 case X86::ATOMNAND16:
17319 case X86::ATOMNAND32:
17320 case X86::ATOMNAND64:
17322 case X86::ATOMMAX8:
17323 case X86::ATOMMAX16:
17324 case X86::ATOMMAX32:
17325 case X86::ATOMMAX64:
17327 case X86::ATOMMIN8:
17328 case X86::ATOMMIN16:
17329 case X86::ATOMMIN32:
17330 case X86::ATOMMIN64:
17332 case X86::ATOMUMAX8:
17333 case X86::ATOMUMAX16:
17334 case X86::ATOMUMAX32:
17335 case X86::ATOMUMAX64:
17337 case X86::ATOMUMIN8:
17338 case X86::ATOMUMIN16:
17339 case X86::ATOMUMIN32:
17340 case X86::ATOMUMIN64:
17341 return EmitAtomicLoadArith(MI, BB);
17343 // This group does 64-bit operations on a 32-bit host.
17344 case X86::ATOMAND6432:
17345 case X86::ATOMOR6432:
17346 case X86::ATOMXOR6432:
17347 case X86::ATOMNAND6432:
17348 case X86::ATOMADD6432:
17349 case X86::ATOMSUB6432:
17350 case X86::ATOMMAX6432:
17351 case X86::ATOMMIN6432:
17352 case X86::ATOMUMAX6432:
17353 case X86::ATOMUMIN6432:
17354 case X86::ATOMSWAP6432:
17355 return EmitAtomicLoadArith6432(MI, BB);
17357 case X86::VASTART_SAVE_XMM_REGS:
17358 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17360 case X86::VAARG_64:
17361 return EmitVAARG64WithCustomInserter(MI, BB);
17363 case X86::EH_SjLj_SetJmp32:
17364 case X86::EH_SjLj_SetJmp64:
17365 return emitEHSjLjSetJmp(MI, BB);
17367 case X86::EH_SjLj_LongJmp32:
17368 case X86::EH_SjLj_LongJmp64:
17369 return emitEHSjLjLongJmp(MI, BB);
17371 case TargetOpcode::STACKMAP:
17372 case TargetOpcode::PATCHPOINT:
17373 return emitPatchPoint(MI, BB);
17375 case X86::VFMADDPDr213r:
17376 case X86::VFMADDPSr213r:
17377 case X86::VFMADDSDr213r:
17378 case X86::VFMADDSSr213r:
17379 case X86::VFMSUBPDr213r:
17380 case X86::VFMSUBPSr213r:
17381 case X86::VFMSUBSDr213r:
17382 case X86::VFMSUBSSr213r:
17383 case X86::VFNMADDPDr213r:
17384 case X86::VFNMADDPSr213r:
17385 case X86::VFNMADDSDr213r:
17386 case X86::VFNMADDSSr213r:
17387 case X86::VFNMSUBPDr213r:
17388 case X86::VFNMSUBPSr213r:
17389 case X86::VFNMSUBSDr213r:
17390 case X86::VFNMSUBSSr213r:
17391 case X86::VFMADDPDr213rY:
17392 case X86::VFMADDPSr213rY:
17393 case X86::VFMSUBPDr213rY:
17394 case X86::VFMSUBPSr213rY:
17395 case X86::VFNMADDPDr213rY:
17396 case X86::VFNMADDPSr213rY:
17397 case X86::VFNMSUBPDr213rY:
17398 case X86::VFNMSUBPSr213rY:
17399 return emitFMA3Instr(MI, BB);
17403 //===----------------------------------------------------------------------===//
17404 // X86 Optimization Hooks
17405 //===----------------------------------------------------------------------===//
17407 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17410 const SelectionDAG &DAG,
17411 unsigned Depth) const {
17412 unsigned BitWidth = KnownZero.getBitWidth();
17413 unsigned Opc = Op.getOpcode();
17414 assert((Opc >= ISD::BUILTIN_OP_END ||
17415 Opc == ISD::INTRINSIC_WO_CHAIN ||
17416 Opc == ISD::INTRINSIC_W_CHAIN ||
17417 Opc == ISD::INTRINSIC_VOID) &&
17418 "Should use MaskedValueIsZero if you don't know whether Op"
17419 " is a target node!");
17421 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17435 // These nodes' second result is a boolean.
17436 if (Op.getResNo() == 0)
17439 case X86ISD::SETCC:
17440 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17442 case ISD::INTRINSIC_WO_CHAIN: {
17443 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17444 unsigned NumLoBits = 0;
17447 case Intrinsic::x86_sse_movmsk_ps:
17448 case Intrinsic::x86_avx_movmsk_ps_256:
17449 case Intrinsic::x86_sse2_movmsk_pd:
17450 case Intrinsic::x86_avx_movmsk_pd_256:
17451 case Intrinsic::x86_mmx_pmovmskb:
17452 case Intrinsic::x86_sse2_pmovmskb_128:
17453 case Intrinsic::x86_avx2_pmovmskb: {
17454 // High bits of movmskp{s|d}, pmovmskb are known zero.
17456 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17457 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17458 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17459 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17460 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17461 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17462 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17463 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17465 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17474 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17476 const SelectionDAG &,
17477 unsigned Depth) const {
17478 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17479 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17480 return Op.getValueType().getScalarType().getSizeInBits();
17486 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17487 /// node is a GlobalAddress + offset.
17488 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17489 const GlobalValue* &GA,
17490 int64_t &Offset) const {
17491 if (N->getOpcode() == X86ISD::Wrapper) {
17492 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17493 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17494 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17498 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17501 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17502 /// same as extracting the high 128-bit part of 256-bit vector and then
17503 /// inserting the result into the low part of a new 256-bit vector
17504 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17505 EVT VT = SVOp->getValueType(0);
17506 unsigned NumElems = VT.getVectorNumElements();
17508 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17509 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17510 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17511 SVOp->getMaskElt(j) >= 0)
17517 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17518 /// same as extracting the low 128-bit part of 256-bit vector and then
17519 /// inserting the result into the high part of a new 256-bit vector
17520 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17521 EVT VT = SVOp->getValueType(0);
17522 unsigned NumElems = VT.getVectorNumElements();
17524 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17525 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17526 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17527 SVOp->getMaskElt(j) >= 0)
17533 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17534 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17535 TargetLowering::DAGCombinerInfo &DCI,
17536 const X86Subtarget* Subtarget) {
17538 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17539 SDValue V1 = SVOp->getOperand(0);
17540 SDValue V2 = SVOp->getOperand(1);
17541 EVT VT = SVOp->getValueType(0);
17542 unsigned NumElems = VT.getVectorNumElements();
17544 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17545 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17549 // V UNDEF BUILD_VECTOR UNDEF
17551 // CONCAT_VECTOR CONCAT_VECTOR
17554 // RESULT: V + zero extended
17556 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17557 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17558 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17561 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17564 // To match the shuffle mask, the first half of the mask should
17565 // be exactly the first vector, and all the rest a splat with the
17566 // first element of the second one.
17567 for (unsigned i = 0; i != NumElems/2; ++i)
17568 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17569 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17572 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17573 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17574 if (Ld->hasNUsesOfValue(1, 0)) {
17575 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17576 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17578 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17580 Ld->getPointerInfo(),
17581 Ld->getAlignment(),
17582 false/*isVolatile*/, true/*ReadMem*/,
17583 false/*WriteMem*/);
17585 // Make sure the newly-created LOAD is in the same position as Ld in
17586 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17587 // and update uses of Ld's output chain to use the TokenFactor.
17588 if (Ld->hasAnyUseOfValue(1)) {
17589 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17590 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17591 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17592 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17593 SDValue(ResNode.getNode(), 1));
17596 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17600 // Emit a zeroed vector and insert the desired subvector on its
17602 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17603 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17604 return DCI.CombineTo(N, InsV);
17607 //===--------------------------------------------------------------------===//
17608 // Combine some shuffles into subvector extracts and inserts:
17611 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17612 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17613 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17614 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17615 return DCI.CombineTo(N, InsV);
17618 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17619 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17620 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17621 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17622 return DCI.CombineTo(N, InsV);
17628 /// PerformShuffleCombine - Performs several different shuffle combines.
17629 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17630 TargetLowering::DAGCombinerInfo &DCI,
17631 const X86Subtarget *Subtarget) {
17633 SDValue N0 = N->getOperand(0);
17634 SDValue N1 = N->getOperand(1);
17635 EVT VT = N->getValueType(0);
17637 // Don't create instructions with illegal types after legalize types has run.
17638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17639 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17642 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17643 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17644 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17645 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17647 // During Type Legalization, when promoting illegal vector types,
17648 // the backend might introduce new shuffle dag nodes and bitcasts.
17650 // This code performs the following transformation:
17651 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17652 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17654 // We do this only if both the bitcast and the BINOP dag nodes have
17655 // one use. Also, perform this transformation only if the new binary
17656 // operation is legal. This is to avoid introducing dag nodes that
17657 // potentially need to be further expanded (or custom lowered) into a
17658 // less optimal sequence of dag nodes.
17659 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17660 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17661 N0.getOpcode() == ISD::BITCAST) {
17662 SDValue BC0 = N0.getOperand(0);
17663 EVT SVT = BC0.getValueType();
17664 unsigned Opcode = BC0.getOpcode();
17665 unsigned NumElts = VT.getVectorNumElements();
17667 if (BC0.hasOneUse() && SVT.isVector() &&
17668 SVT.getVectorNumElements() * 2 == NumElts &&
17669 TLI.isOperationLegal(Opcode, VT)) {
17670 bool CanFold = false;
17682 unsigned SVTNumElts = SVT.getVectorNumElements();
17683 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17684 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17685 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17686 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17687 CanFold = SVOp->getMaskElt(i) < 0;
17690 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17691 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17692 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17693 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17698 // Only handle 128 wide vector from here on.
17699 if (!VT.is128BitVector())
17702 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17703 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17704 // consecutive, non-overlapping, and in the right order.
17705 SmallVector<SDValue, 16> Elts;
17706 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17707 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17709 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17712 /// PerformTruncateCombine - Converts truncate operation to
17713 /// a sequence of vector shuffle operations.
17714 /// It is possible when we truncate 256-bit vector to 128-bit vector
17715 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17716 TargetLowering::DAGCombinerInfo &DCI,
17717 const X86Subtarget *Subtarget) {
17721 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17722 /// specific shuffle of a load can be folded into a single element load.
17723 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17724 /// shuffles have been customed lowered so we need to handle those here.
17725 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17726 TargetLowering::DAGCombinerInfo &DCI) {
17727 if (DCI.isBeforeLegalizeOps())
17730 SDValue InVec = N->getOperand(0);
17731 SDValue EltNo = N->getOperand(1);
17733 if (!isa<ConstantSDNode>(EltNo))
17736 EVT VT = InVec.getValueType();
17738 bool HasShuffleIntoBitcast = false;
17739 if (InVec.getOpcode() == ISD::BITCAST) {
17740 // Don't duplicate a load with other uses.
17741 if (!InVec.hasOneUse())
17743 EVT BCVT = InVec.getOperand(0).getValueType();
17744 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17746 InVec = InVec.getOperand(0);
17747 HasShuffleIntoBitcast = true;
17750 if (!isTargetShuffle(InVec.getOpcode()))
17753 // Don't duplicate a load with other uses.
17754 if (!InVec.hasOneUse())
17757 SmallVector<int, 16> ShuffleMask;
17759 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17763 // Select the input vector, guarding against out of range extract vector.
17764 unsigned NumElems = VT.getVectorNumElements();
17765 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17766 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17767 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17768 : InVec.getOperand(1);
17770 // If inputs to shuffle are the same for both ops, then allow 2 uses
17771 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17773 if (LdNode.getOpcode() == ISD::BITCAST) {
17774 // Don't duplicate a load with other uses.
17775 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17778 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17779 LdNode = LdNode.getOperand(0);
17782 if (!ISD::isNormalLoad(LdNode.getNode()))
17785 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17787 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17790 if (HasShuffleIntoBitcast) {
17791 // If there's a bitcast before the shuffle, check if the load type and
17792 // alignment is valid.
17793 unsigned Align = LN0->getAlignment();
17794 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17795 unsigned NewAlign = TLI.getDataLayout()->
17796 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17798 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17802 // All checks match so transform back to vector_shuffle so that DAG combiner
17803 // can finish the job
17806 // Create shuffle node taking into account the case that its a unary shuffle
17807 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17808 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17809 InVec.getOperand(0), Shuffle,
17811 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17812 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17816 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17817 /// generation and convert it from being a bunch of shuffles and extracts
17818 /// to a simple store and scalar loads to extract the elements.
17819 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17820 TargetLowering::DAGCombinerInfo &DCI) {
17821 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17822 if (NewOp.getNode())
17825 SDValue InputVector = N->getOperand(0);
17827 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17828 // from mmx to v2i32 has a single usage.
17829 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17830 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17831 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17832 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17833 N->getValueType(0),
17834 InputVector.getNode()->getOperand(0));
17836 // Only operate on vectors of 4 elements, where the alternative shuffling
17837 // gets to be more expensive.
17838 if (InputVector.getValueType() != MVT::v4i32)
17841 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17842 // single use which is a sign-extend or zero-extend, and all elements are
17844 SmallVector<SDNode *, 4> Uses;
17845 unsigned ExtractedElements = 0;
17846 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17847 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17848 if (UI.getUse().getResNo() != InputVector.getResNo())
17851 SDNode *Extract = *UI;
17852 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17855 if (Extract->getValueType(0) != MVT::i32)
17857 if (!Extract->hasOneUse())
17859 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17860 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17862 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17865 // Record which element was extracted.
17866 ExtractedElements |=
17867 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17869 Uses.push_back(Extract);
17872 // If not all the elements were used, this may not be worthwhile.
17873 if (ExtractedElements != 15)
17876 // Ok, we've now decided to do the transformation.
17877 SDLoc dl(InputVector);
17879 // Store the value to a temporary stack slot.
17880 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17881 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17882 MachinePointerInfo(), false, false, 0);
17884 // Replace each use (extract) with a load of the appropriate element.
17885 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17886 UE = Uses.end(); UI != UE; ++UI) {
17887 SDNode *Extract = *UI;
17889 // cOMpute the element's address.
17890 SDValue Idx = Extract->getOperand(1);
17892 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17893 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17894 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17895 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17897 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17898 StackPtr, OffsetVal);
17900 // Load the scalar.
17901 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17902 ScalarAddr, MachinePointerInfo(),
17903 false, false, false, 0);
17905 // Replace the exact with the load.
17906 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17909 // The replacement was made in place; don't return anything.
17913 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17914 static std::pair<unsigned, bool>
17915 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17916 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17917 if (!VT.isVector())
17918 return std::make_pair(0, false);
17920 bool NeedSplit = false;
17921 switch (VT.getSimpleVT().SimpleTy) {
17922 default: return std::make_pair(0, false);
17926 if (!Subtarget->hasAVX2())
17928 if (!Subtarget->hasAVX())
17929 return std::make_pair(0, false);
17934 if (!Subtarget->hasSSE2())
17935 return std::make_pair(0, false);
17938 // SSE2 has only a small subset of the operations.
17939 bool hasUnsigned = Subtarget->hasSSE41() ||
17940 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17941 bool hasSigned = Subtarget->hasSSE41() ||
17942 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17944 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17947 // Check for x CC y ? x : y.
17948 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17949 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17954 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17957 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17960 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17963 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17965 // Check for x CC y ? y : x -- a min/max with reversed arms.
17966 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17967 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17972 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17975 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17978 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17981 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17985 return std::make_pair(Opc, NeedSplit);
17989 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17990 const X86Subtarget *Subtarget) {
17992 SDValue Cond = N->getOperand(0);
17993 SDValue LHS = N->getOperand(1);
17994 SDValue RHS = N->getOperand(2);
17996 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17997 SDValue CondSrc = Cond->getOperand(0);
17998 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17999 Cond = CondSrc->getOperand(0);
18002 MVT VT = N->getSimpleValueType(0);
18003 MVT EltVT = VT.getVectorElementType();
18004 unsigned NumElems = VT.getVectorNumElements();
18005 // There is no blend with immediate in AVX-512.
18006 if (VT.is512BitVector())
18009 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18011 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18014 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18017 unsigned MaskValue = 0;
18018 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18021 SmallVector<int, 8> ShuffleMask(NumElems, -1);
18022 for (unsigned i = 0; i < NumElems; ++i) {
18023 // Be sure we emit undef where we can.
18024 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18025 ShuffleMask[i] = -1;
18027 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18030 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18033 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18035 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18036 TargetLowering::DAGCombinerInfo &DCI,
18037 const X86Subtarget *Subtarget) {
18039 SDValue Cond = N->getOperand(0);
18040 // Get the LHS/RHS of the select.
18041 SDValue LHS = N->getOperand(1);
18042 SDValue RHS = N->getOperand(2);
18043 EVT VT = LHS.getValueType();
18044 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18046 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18047 // instructions match the semantics of the common C idiom x<y?x:y but not
18048 // x<=y?x:y, because of how they handle negative zero (which can be
18049 // ignored in unsafe-math mode).
18050 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18051 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18052 (Subtarget->hasSSE2() ||
18053 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18054 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18056 unsigned Opcode = 0;
18057 // Check for x CC y ? x : y.
18058 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18059 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18063 // Converting this to a min would handle NaNs incorrectly, and swapping
18064 // the operands would cause it to handle comparisons between positive
18065 // and negative zero incorrectly.
18066 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18067 if (!DAG.getTarget().Options.UnsafeFPMath &&
18068 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18070 std::swap(LHS, RHS);
18072 Opcode = X86ISD::FMIN;
18075 // Converting this to a min would handle comparisons between positive
18076 // and negative zero incorrectly.
18077 if (!DAG.getTarget().Options.UnsafeFPMath &&
18078 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18080 Opcode = X86ISD::FMIN;
18083 // Converting this to a min would handle both negative zeros and NaNs
18084 // incorrectly, but we can swap the operands to fix both.
18085 std::swap(LHS, RHS);
18089 Opcode = X86ISD::FMIN;
18093 // Converting this to a max would handle comparisons between positive
18094 // and negative zero incorrectly.
18095 if (!DAG.getTarget().Options.UnsafeFPMath &&
18096 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18098 Opcode = X86ISD::FMAX;
18101 // Converting this to a max would handle NaNs incorrectly, and swapping
18102 // the operands would cause it to handle comparisons between positive
18103 // and negative zero incorrectly.
18104 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18105 if (!DAG.getTarget().Options.UnsafeFPMath &&
18106 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18108 std::swap(LHS, RHS);
18110 Opcode = X86ISD::FMAX;
18113 // Converting this to a max would handle both negative zeros and NaNs
18114 // incorrectly, but we can swap the operands to fix both.
18115 std::swap(LHS, RHS);
18119 Opcode = X86ISD::FMAX;
18122 // Check for x CC y ? y : x -- a min/max with reversed arms.
18123 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18124 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18128 // Converting this to a min would handle comparisons between positive
18129 // and negative zero incorrectly, and swapping the operands would
18130 // cause it to handle NaNs incorrectly.
18131 if (!DAG.getTarget().Options.UnsafeFPMath &&
18132 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18133 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18135 std::swap(LHS, RHS);
18137 Opcode = X86ISD::FMIN;
18140 // Converting this to a min would handle NaNs incorrectly.
18141 if (!DAG.getTarget().Options.UnsafeFPMath &&
18142 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18144 Opcode = X86ISD::FMIN;
18147 // Converting this to a min would handle both negative zeros and NaNs
18148 // incorrectly, but we can swap the operands to fix both.
18149 std::swap(LHS, RHS);
18153 Opcode = X86ISD::FMIN;
18157 // Converting this to a max would handle NaNs incorrectly.
18158 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18160 Opcode = X86ISD::FMAX;
18163 // Converting this to a max would handle comparisons between positive
18164 // and negative zero incorrectly, and swapping the operands would
18165 // cause it to handle NaNs incorrectly.
18166 if (!DAG.getTarget().Options.UnsafeFPMath &&
18167 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18168 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18170 std::swap(LHS, RHS);
18172 Opcode = X86ISD::FMAX;
18175 // Converting this to a max would handle both negative zeros and NaNs
18176 // incorrectly, but we can swap the operands to fix both.
18177 std::swap(LHS, RHS);
18181 Opcode = X86ISD::FMAX;
18187 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18190 EVT CondVT = Cond.getValueType();
18191 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18192 CondVT.getVectorElementType() == MVT::i1) {
18193 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18194 // lowering on AVX-512. In this case we convert it to
18195 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18196 // The same situation for all 128 and 256-bit vectors of i8 and i16
18197 EVT OpVT = LHS.getValueType();
18198 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18199 (OpVT.getVectorElementType() == MVT::i8 ||
18200 OpVT.getVectorElementType() == MVT::i16)) {
18201 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18202 DCI.AddToWorklist(Cond.getNode());
18203 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18206 // If this is a select between two integer constants, try to do some
18208 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18209 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18210 // Don't do this for crazy integer types.
18211 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18212 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18213 // so that TrueC (the true value) is larger than FalseC.
18214 bool NeedsCondInvert = false;
18216 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18217 // Efficiently invertible.
18218 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18219 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18220 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18221 NeedsCondInvert = true;
18222 std::swap(TrueC, FalseC);
18225 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18226 if (FalseC->getAPIntValue() == 0 &&
18227 TrueC->getAPIntValue().isPowerOf2()) {
18228 if (NeedsCondInvert) // Invert the condition if needed.
18229 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18230 DAG.getConstant(1, Cond.getValueType()));
18232 // Zero extend the condition if needed.
18233 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18235 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18236 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18237 DAG.getConstant(ShAmt, MVT::i8));
18240 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18241 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18242 if (NeedsCondInvert) // Invert the condition if needed.
18243 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18244 DAG.getConstant(1, Cond.getValueType()));
18246 // Zero extend the condition if needed.
18247 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18248 FalseC->getValueType(0), Cond);
18249 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18250 SDValue(FalseC, 0));
18253 // Optimize cases that will turn into an LEA instruction. This requires
18254 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18255 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18256 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18257 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18259 bool isFastMultiplier = false;
18261 switch ((unsigned char)Diff) {
18263 case 1: // result = add base, cond
18264 case 2: // result = lea base( , cond*2)
18265 case 3: // result = lea base(cond, cond*2)
18266 case 4: // result = lea base( , cond*4)
18267 case 5: // result = lea base(cond, cond*4)
18268 case 8: // result = lea base( , cond*8)
18269 case 9: // result = lea base(cond, cond*8)
18270 isFastMultiplier = true;
18275 if (isFastMultiplier) {
18276 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18277 if (NeedsCondInvert) // Invert the condition if needed.
18278 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18279 DAG.getConstant(1, Cond.getValueType()));
18281 // Zero extend the condition if needed.
18282 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18284 // Scale the condition by the difference.
18286 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18287 DAG.getConstant(Diff, Cond.getValueType()));
18289 // Add the base if non-zero.
18290 if (FalseC->getAPIntValue() != 0)
18291 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18292 SDValue(FalseC, 0));
18299 // Canonicalize max and min:
18300 // (x > y) ? x : y -> (x >= y) ? x : y
18301 // (x < y) ? x : y -> (x <= y) ? x : y
18302 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18303 // the need for an extra compare
18304 // against zero. e.g.
18305 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18307 // testl %edi, %edi
18309 // cmovgl %edi, %eax
18313 // cmovsl %eax, %edi
18314 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18315 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18316 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18317 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18322 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18323 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18324 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18325 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18330 // Early exit check
18331 if (!TLI.isTypeLegal(VT))
18334 // Match VSELECTs into subs with unsigned saturation.
18335 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18336 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18337 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18338 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18339 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18341 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18342 // left side invert the predicate to simplify logic below.
18344 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18346 CC = ISD::getSetCCInverse(CC, true);
18347 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18351 if (Other.getNode() && Other->getNumOperands() == 2 &&
18352 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18353 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18354 SDValue CondRHS = Cond->getOperand(1);
18356 // Look for a general sub with unsigned saturation first.
18357 // x >= y ? x-y : 0 --> subus x, y
18358 // x > y ? x-y : 0 --> subus x, y
18359 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18360 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18361 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18363 // If the RHS is a constant we have to reverse the const canonicalization.
18364 // x > C-1 ? x+-C : 0 --> subus x, C
18365 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18366 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18367 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18368 if (CondRHS.getConstantOperandVal(0) == -A-1)
18369 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18370 DAG.getConstant(-A, VT));
18373 // Another special case: If C was a sign bit, the sub has been
18374 // canonicalized into a xor.
18375 // FIXME: Would it be better to use computeKnownBits to determine whether
18376 // it's safe to decanonicalize the xor?
18377 // x s< 0 ? x^C : 0 --> subus x, C
18378 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18379 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18380 isSplatVector(OpRHS.getNode())) {
18381 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18383 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18388 // Try to match a min/max vector operation.
18389 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18390 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18391 unsigned Opc = ret.first;
18392 bool NeedSplit = ret.second;
18394 if (Opc && NeedSplit) {
18395 unsigned NumElems = VT.getVectorNumElements();
18396 // Extract the LHS vectors
18397 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18398 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18400 // Extract the RHS vectors
18401 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18402 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18404 // Create min/max for each subvector
18405 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18406 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18408 // Merge the result
18409 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18411 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18414 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18415 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18416 // Check if SETCC has already been promoted
18417 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18418 // Check that condition value type matches vselect operand type
18421 assert(Cond.getValueType().isVector() &&
18422 "vector select expects a vector selector!");
18424 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18425 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18427 if (!TValIsAllOnes && !FValIsAllZeros) {
18428 // Try invert the condition if true value is not all 1s and false value
18430 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18431 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18433 if (TValIsAllZeros || FValIsAllOnes) {
18434 SDValue CC = Cond.getOperand(2);
18435 ISD::CondCode NewCC =
18436 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18437 Cond.getOperand(0).getValueType().isInteger());
18438 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18439 std::swap(LHS, RHS);
18440 TValIsAllOnes = FValIsAllOnes;
18441 FValIsAllZeros = TValIsAllZeros;
18445 if (TValIsAllOnes || FValIsAllZeros) {
18448 if (TValIsAllOnes && FValIsAllZeros)
18450 else if (TValIsAllOnes)
18451 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18452 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18453 else if (FValIsAllZeros)
18454 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18455 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18457 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18461 // Try to fold this VSELECT into a MOVSS/MOVSD
18462 if (N->getOpcode() == ISD::VSELECT &&
18463 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18464 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18465 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18466 bool CanFold = false;
18467 unsigned NumElems = Cond.getNumOperands();
18471 if (isZero(Cond.getOperand(0))) {
18474 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18475 // fold (vselect <0,-1> -> (movsd A, B)
18476 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18477 CanFold = isAllOnes(Cond.getOperand(i));
18478 } else if (isAllOnes(Cond.getOperand(0))) {
18482 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18483 // fold (vselect <-1,0> -> (movsd B, A)
18484 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18485 CanFold = isZero(Cond.getOperand(i));
18489 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18490 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18491 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18494 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18495 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18496 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18497 // (v2i64 (bitcast B)))))
18499 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18500 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18501 // (v2f64 (bitcast B)))))
18503 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18504 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18505 // (v2i64 (bitcast A)))))
18507 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18508 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18509 // (v2f64 (bitcast A)))))
18511 CanFold = (isZero(Cond.getOperand(0)) &&
18512 isZero(Cond.getOperand(1)) &&
18513 isAllOnes(Cond.getOperand(2)) &&
18514 isAllOnes(Cond.getOperand(3)));
18516 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18517 isAllOnes(Cond.getOperand(1)) &&
18518 isZero(Cond.getOperand(2)) &&
18519 isZero(Cond.getOperand(3))) {
18521 std::swap(LHS, RHS);
18525 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18526 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18527 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18528 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18530 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18536 // If we know that this node is legal then we know that it is going to be
18537 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18538 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18539 // to simplify previous instructions.
18540 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18541 !DCI.isBeforeLegalize() &&
18542 // We explicitly check against v8i16 and v16i16 because, although
18543 // they're marked as Custom, they might only be legal when Cond is a
18544 // build_vector of constants. This will be taken care in a later
18546 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18547 VT != MVT::v8i16)) {
18548 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18550 // Don't optimize vector selects that map to mask-registers.
18554 // Check all uses of that condition operand to check whether it will be
18555 // consumed by non-BLEND instructions, which may depend on all bits are set
18557 for (SDNode::use_iterator I = Cond->use_begin(),
18558 E = Cond->use_end(); I != E; ++I)
18559 if (I->getOpcode() != ISD::VSELECT)
18560 // TODO: Add other opcodes eventually lowered into BLEND.
18563 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18564 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18566 APInt KnownZero, KnownOne;
18567 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18568 DCI.isBeforeLegalizeOps());
18569 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18570 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18571 DCI.CommitTargetLoweringOpt(TLO);
18574 // We should generate an X86ISD::BLENDI from a vselect if its argument
18575 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18576 // constants. This specific pattern gets generated when we split a
18577 // selector for a 512 bit vector in a machine without AVX512 (but with
18578 // 256-bit vectors), during legalization:
18580 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18582 // Iff we find this pattern and the build_vectors are built from
18583 // constants, we translate the vselect into a shuffle_vector that we
18584 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18585 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18586 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18587 if (Shuffle.getNode())
18594 // Check whether a boolean test is testing a boolean value generated by
18595 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18598 // Simplify the following patterns:
18599 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18600 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18601 // to (Op EFLAGS Cond)
18603 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18604 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18605 // to (Op EFLAGS !Cond)
18607 // where Op could be BRCOND or CMOV.
18609 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18610 // Quit if not CMP and SUB with its value result used.
18611 if (Cmp.getOpcode() != X86ISD::CMP &&
18612 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18615 // Quit if not used as a boolean value.
18616 if (CC != X86::COND_E && CC != X86::COND_NE)
18619 // Check CMP operands. One of them should be 0 or 1 and the other should be
18620 // an SetCC or extended from it.
18621 SDValue Op1 = Cmp.getOperand(0);
18622 SDValue Op2 = Cmp.getOperand(1);
18625 const ConstantSDNode* C = nullptr;
18626 bool needOppositeCond = (CC == X86::COND_E);
18627 bool checkAgainstTrue = false; // Is it a comparison against 1?
18629 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18631 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18633 else // Quit if all operands are not constants.
18636 if (C->getZExtValue() == 1) {
18637 needOppositeCond = !needOppositeCond;
18638 checkAgainstTrue = true;
18639 } else if (C->getZExtValue() != 0)
18640 // Quit if the constant is neither 0 or 1.
18643 bool truncatedToBoolWithAnd = false;
18644 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18645 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18646 SetCC.getOpcode() == ISD::TRUNCATE ||
18647 SetCC.getOpcode() == ISD::AND) {
18648 if (SetCC.getOpcode() == ISD::AND) {
18650 ConstantSDNode *CS;
18651 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18652 CS->getZExtValue() == 1)
18654 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18655 CS->getZExtValue() == 1)
18659 SetCC = SetCC.getOperand(OpIdx);
18660 truncatedToBoolWithAnd = true;
18662 SetCC = SetCC.getOperand(0);
18665 switch (SetCC.getOpcode()) {
18666 case X86ISD::SETCC_CARRY:
18667 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18668 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18669 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18670 // truncated to i1 using 'and'.
18671 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18673 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18674 "Invalid use of SETCC_CARRY!");
18676 case X86ISD::SETCC:
18677 // Set the condition code or opposite one if necessary.
18678 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18679 if (needOppositeCond)
18680 CC = X86::GetOppositeBranchCondition(CC);
18681 return SetCC.getOperand(1);
18682 case X86ISD::CMOV: {
18683 // Check whether false/true value has canonical one, i.e. 0 or 1.
18684 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18685 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18686 // Quit if true value is not a constant.
18689 // Quit if false value is not a constant.
18691 SDValue Op = SetCC.getOperand(0);
18692 // Skip 'zext' or 'trunc' node.
18693 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18694 Op.getOpcode() == ISD::TRUNCATE)
18695 Op = Op.getOperand(0);
18696 // A special case for rdrand/rdseed, where 0 is set if false cond is
18698 if ((Op.getOpcode() != X86ISD::RDRAND &&
18699 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18702 // Quit if false value is not the constant 0 or 1.
18703 bool FValIsFalse = true;
18704 if (FVal && FVal->getZExtValue() != 0) {
18705 if (FVal->getZExtValue() != 1)
18707 // If FVal is 1, opposite cond is needed.
18708 needOppositeCond = !needOppositeCond;
18709 FValIsFalse = false;
18711 // Quit if TVal is not the constant opposite of FVal.
18712 if (FValIsFalse && TVal->getZExtValue() != 1)
18714 if (!FValIsFalse && TVal->getZExtValue() != 0)
18716 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18717 if (needOppositeCond)
18718 CC = X86::GetOppositeBranchCondition(CC);
18719 return SetCC.getOperand(3);
18726 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18727 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18728 TargetLowering::DAGCombinerInfo &DCI,
18729 const X86Subtarget *Subtarget) {
18732 // If the flag operand isn't dead, don't touch this CMOV.
18733 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18736 SDValue FalseOp = N->getOperand(0);
18737 SDValue TrueOp = N->getOperand(1);
18738 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18739 SDValue Cond = N->getOperand(3);
18741 if (CC == X86::COND_E || CC == X86::COND_NE) {
18742 switch (Cond.getOpcode()) {
18746 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18747 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18748 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18754 Flags = checkBoolTestSetCCCombine(Cond, CC);
18755 if (Flags.getNode() &&
18756 // Extra check as FCMOV only supports a subset of X86 cond.
18757 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18758 SDValue Ops[] = { FalseOp, TrueOp,
18759 DAG.getConstant(CC, MVT::i8), Flags };
18760 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18763 // If this is a select between two integer constants, try to do some
18764 // optimizations. Note that the operands are ordered the opposite of SELECT
18766 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18767 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18768 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18769 // larger than FalseC (the false value).
18770 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18771 CC = X86::GetOppositeBranchCondition(CC);
18772 std::swap(TrueC, FalseC);
18773 std::swap(TrueOp, FalseOp);
18776 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18777 // This is efficient for any integer data type (including i8/i16) and
18779 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18780 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18781 DAG.getConstant(CC, MVT::i8), Cond);
18783 // Zero extend the condition if needed.
18784 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18786 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18787 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18788 DAG.getConstant(ShAmt, MVT::i8));
18789 if (N->getNumValues() == 2) // Dead flag value?
18790 return DCI.CombineTo(N, Cond, SDValue());
18794 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18795 // for any integer data type, including i8/i16.
18796 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18797 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18798 DAG.getConstant(CC, MVT::i8), Cond);
18800 // Zero extend the condition if needed.
18801 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18802 FalseC->getValueType(0), Cond);
18803 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18804 SDValue(FalseC, 0));
18806 if (N->getNumValues() == 2) // Dead flag value?
18807 return DCI.CombineTo(N, Cond, SDValue());
18811 // Optimize cases that will turn into an LEA instruction. This requires
18812 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18813 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18814 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18815 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18817 bool isFastMultiplier = false;
18819 switch ((unsigned char)Diff) {
18821 case 1: // result = add base, cond
18822 case 2: // result = lea base( , cond*2)
18823 case 3: // result = lea base(cond, cond*2)
18824 case 4: // result = lea base( , cond*4)
18825 case 5: // result = lea base(cond, cond*4)
18826 case 8: // result = lea base( , cond*8)
18827 case 9: // result = lea base(cond, cond*8)
18828 isFastMultiplier = true;
18833 if (isFastMultiplier) {
18834 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18835 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18836 DAG.getConstant(CC, MVT::i8), Cond);
18837 // Zero extend the condition if needed.
18838 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18840 // Scale the condition by the difference.
18842 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18843 DAG.getConstant(Diff, Cond.getValueType()));
18845 // Add the base if non-zero.
18846 if (FalseC->getAPIntValue() != 0)
18847 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18848 SDValue(FalseC, 0));
18849 if (N->getNumValues() == 2) // Dead flag value?
18850 return DCI.CombineTo(N, Cond, SDValue());
18857 // Handle these cases:
18858 // (select (x != c), e, c) -> select (x != c), e, x),
18859 // (select (x == c), c, e) -> select (x == c), x, e)
18860 // where the c is an integer constant, and the "select" is the combination
18861 // of CMOV and CMP.
18863 // The rationale for this change is that the conditional-move from a constant
18864 // needs two instructions, however, conditional-move from a register needs
18865 // only one instruction.
18867 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18868 // some instruction-combining opportunities. This opt needs to be
18869 // postponed as late as possible.
18871 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18872 // the DCI.xxxx conditions are provided to postpone the optimization as
18873 // late as possible.
18875 ConstantSDNode *CmpAgainst = nullptr;
18876 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18877 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18878 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18880 if (CC == X86::COND_NE &&
18881 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18882 CC = X86::GetOppositeBranchCondition(CC);
18883 std::swap(TrueOp, FalseOp);
18886 if (CC == X86::COND_E &&
18887 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18888 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18889 DAG.getConstant(CC, MVT::i8), Cond };
18890 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18898 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18899 const X86Subtarget *Subtarget) {
18900 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18902 default: return SDValue();
18903 // SSE/AVX/AVX2 blend intrinsics.
18904 case Intrinsic::x86_avx2_pblendvb:
18905 case Intrinsic::x86_avx2_pblendw:
18906 case Intrinsic::x86_avx2_pblendd_128:
18907 case Intrinsic::x86_avx2_pblendd_256:
18908 // Don't try to simplify this intrinsic if we don't have AVX2.
18909 if (!Subtarget->hasAVX2())
18912 case Intrinsic::x86_avx_blend_pd_256:
18913 case Intrinsic::x86_avx_blend_ps_256:
18914 case Intrinsic::x86_avx_blendv_pd_256:
18915 case Intrinsic::x86_avx_blendv_ps_256:
18916 // Don't try to simplify this intrinsic if we don't have AVX.
18917 if (!Subtarget->hasAVX())
18920 case Intrinsic::x86_sse41_pblendw:
18921 case Intrinsic::x86_sse41_blendpd:
18922 case Intrinsic::x86_sse41_blendps:
18923 case Intrinsic::x86_sse41_blendvps:
18924 case Intrinsic::x86_sse41_blendvpd:
18925 case Intrinsic::x86_sse41_pblendvb: {
18926 SDValue Op0 = N->getOperand(1);
18927 SDValue Op1 = N->getOperand(2);
18928 SDValue Mask = N->getOperand(3);
18930 // Don't try to simplify this intrinsic if we don't have SSE4.1.
18931 if (!Subtarget->hasSSE41())
18934 // fold (blend A, A, Mask) -> A
18937 // fold (blend A, B, allZeros) -> A
18938 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18940 // fold (blend A, B, allOnes) -> B
18941 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18944 // Simplify the case where the mask is a constant i32 value.
18945 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18946 if (C->isNullValue())
18948 if (C->isAllOnesValue())
18953 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18954 case Intrinsic::x86_sse2_psrai_w:
18955 case Intrinsic::x86_sse2_psrai_d:
18956 case Intrinsic::x86_avx2_psrai_w:
18957 case Intrinsic::x86_avx2_psrai_d:
18958 case Intrinsic::x86_sse2_psra_w:
18959 case Intrinsic::x86_sse2_psra_d:
18960 case Intrinsic::x86_avx2_psra_w:
18961 case Intrinsic::x86_avx2_psra_d: {
18962 SDValue Op0 = N->getOperand(1);
18963 SDValue Op1 = N->getOperand(2);
18964 EVT VT = Op0.getValueType();
18965 assert(VT.isVector() && "Expected a vector type!");
18967 if (isa<BuildVectorSDNode>(Op1))
18968 Op1 = Op1.getOperand(0);
18970 if (!isa<ConstantSDNode>(Op1))
18973 EVT SVT = VT.getVectorElementType();
18974 unsigned SVTBits = SVT.getSizeInBits();
18976 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18977 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18978 uint64_t ShAmt = C.getZExtValue();
18980 // Don't try to convert this shift into a ISD::SRA if the shift
18981 // count is bigger than or equal to the element size.
18982 if (ShAmt >= SVTBits)
18985 // Trivial case: if the shift count is zero, then fold this
18986 // into the first operand.
18990 // Replace this packed shift intrinsic with a target independent
18992 SDValue Splat = DAG.getConstant(C, VT);
18993 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18998 /// PerformMulCombine - Optimize a single multiply with constant into two
18999 /// in order to implement it with two cheaper instructions, e.g.
19000 /// LEA + SHL, LEA + LEA.
19001 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19002 TargetLowering::DAGCombinerInfo &DCI) {
19003 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19006 EVT VT = N->getValueType(0);
19007 if (VT != MVT::i64)
19010 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19013 uint64_t MulAmt = C->getZExtValue();
19014 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19017 uint64_t MulAmt1 = 0;
19018 uint64_t MulAmt2 = 0;
19019 if ((MulAmt % 9) == 0) {
19021 MulAmt2 = MulAmt / 9;
19022 } else if ((MulAmt % 5) == 0) {
19024 MulAmt2 = MulAmt / 5;
19025 } else if ((MulAmt % 3) == 0) {
19027 MulAmt2 = MulAmt / 3;
19030 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19033 if (isPowerOf2_64(MulAmt2) &&
19034 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19035 // If second multiplifer is pow2, issue it first. We want the multiply by
19036 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19038 std::swap(MulAmt1, MulAmt2);
19041 if (isPowerOf2_64(MulAmt1))
19042 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19043 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19045 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19046 DAG.getConstant(MulAmt1, VT));
19048 if (isPowerOf2_64(MulAmt2))
19049 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19050 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19052 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19053 DAG.getConstant(MulAmt2, VT));
19055 // Do not add new nodes to DAG combiner worklist.
19056 DCI.CombineTo(N, NewMul, false);
19061 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19062 SDValue N0 = N->getOperand(0);
19063 SDValue N1 = N->getOperand(1);
19064 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19065 EVT VT = N0.getValueType();
19067 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19068 // since the result of setcc_c is all zero's or all ones.
19069 if (VT.isInteger() && !VT.isVector() &&
19070 N1C && N0.getOpcode() == ISD::AND &&
19071 N0.getOperand(1).getOpcode() == ISD::Constant) {
19072 SDValue N00 = N0.getOperand(0);
19073 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19074 ((N00.getOpcode() == ISD::ANY_EXTEND ||
19075 N00.getOpcode() == ISD::ZERO_EXTEND) &&
19076 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19077 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19078 APInt ShAmt = N1C->getAPIntValue();
19079 Mask = Mask.shl(ShAmt);
19081 return DAG.getNode(ISD::AND, SDLoc(N), VT,
19082 N00, DAG.getConstant(Mask, VT));
19086 // Hardware support for vector shifts is sparse which makes us scalarize the
19087 // vector operations in many cases. Also, on sandybridge ADD is faster than
19089 // (shl V, 1) -> add V,V
19090 if (isSplatVector(N1.getNode())) {
19091 assert(N0.getValueType().isVector() && "Invalid vector shift type");
19092 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19093 // We shift all of the values by one. In many cases we do not have
19094 // hardware support for this operation. This is better expressed as an ADD
19096 if (N1C && (1 == N1C->getZExtValue())) {
19097 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19104 /// \brief Returns a vector of 0s if the node in input is a vector logical
19105 /// shift by a constant amount which is known to be bigger than or equal
19106 /// to the vector element size in bits.
19107 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19108 const X86Subtarget *Subtarget) {
19109 EVT VT = N->getValueType(0);
19111 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19112 (!Subtarget->hasInt256() ||
19113 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19116 SDValue Amt = N->getOperand(1);
19118 if (isSplatVector(Amt.getNode())) {
19119 SDValue SclrAmt = Amt->getOperand(0);
19120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19121 APInt ShiftAmt = C->getAPIntValue();
19122 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19124 // SSE2/AVX2 logical shifts always return a vector of 0s
19125 // if the shift amount is bigger than or equal to
19126 // the element size. The constant shift amount will be
19127 // encoded as a 8-bit immediate.
19128 if (ShiftAmt.trunc(8).uge(MaxAmount))
19129 return getZeroVector(VT, Subtarget, DAG, DL);
19136 /// PerformShiftCombine - Combine shifts.
19137 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19138 TargetLowering::DAGCombinerInfo &DCI,
19139 const X86Subtarget *Subtarget) {
19140 if (N->getOpcode() == ISD::SHL) {
19141 SDValue V = PerformSHLCombine(N, DAG);
19142 if (V.getNode()) return V;
19145 if (N->getOpcode() != ISD::SRA) {
19146 // Try to fold this logical shift into a zero vector.
19147 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19148 if (V.getNode()) return V;
19154 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19155 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19156 // and friends. Likewise for OR -> CMPNEQSS.
19157 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19158 TargetLowering::DAGCombinerInfo &DCI,
19159 const X86Subtarget *Subtarget) {
19162 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19163 // we're requiring SSE2 for both.
19164 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19165 SDValue N0 = N->getOperand(0);
19166 SDValue N1 = N->getOperand(1);
19167 SDValue CMP0 = N0->getOperand(1);
19168 SDValue CMP1 = N1->getOperand(1);
19171 // The SETCCs should both refer to the same CMP.
19172 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19175 SDValue CMP00 = CMP0->getOperand(0);
19176 SDValue CMP01 = CMP0->getOperand(1);
19177 EVT VT = CMP00.getValueType();
19179 if (VT == MVT::f32 || VT == MVT::f64) {
19180 bool ExpectingFlags = false;
19181 // Check for any users that want flags:
19182 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19183 !ExpectingFlags && UI != UE; ++UI)
19184 switch (UI->getOpcode()) {
19189 ExpectingFlags = true;
19191 case ISD::CopyToReg:
19192 case ISD::SIGN_EXTEND:
19193 case ISD::ZERO_EXTEND:
19194 case ISD::ANY_EXTEND:
19198 if (!ExpectingFlags) {
19199 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19200 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19202 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19203 X86::CondCode tmp = cc0;
19208 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19209 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19210 // FIXME: need symbolic constants for these magic numbers.
19211 // See X86ATTInstPrinter.cpp:printSSECC().
19212 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19213 if (Subtarget->hasAVX512()) {
19214 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19215 CMP01, DAG.getConstant(x86cc, MVT::i8));
19216 if (N->getValueType(0) != MVT::i1)
19217 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19221 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19222 CMP00.getValueType(), CMP00, CMP01,
19223 DAG.getConstant(x86cc, MVT::i8));
19225 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19226 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19228 if (is64BitFP && !Subtarget->is64Bit()) {
19229 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19230 // 64-bit integer, since that's not a legal type. Since
19231 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19232 // bits, but can do this little dance to extract the lowest 32 bits
19233 // and work with those going forward.
19234 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19236 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19238 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19239 Vector32, DAG.getIntPtrConstant(0));
19243 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19244 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19245 DAG.getConstant(1, IntVT));
19246 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19247 return OneBitOfTruth;
19255 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19256 /// so it can be folded inside ANDNP.
19257 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19258 EVT VT = N->getValueType(0);
19260 // Match direct AllOnes for 128 and 256-bit vectors
19261 if (ISD::isBuildVectorAllOnes(N))
19264 // Look through a bit convert.
19265 if (N->getOpcode() == ISD::BITCAST)
19266 N = N->getOperand(0).getNode();
19268 // Sometimes the operand may come from a insert_subvector building a 256-bit
19270 if (VT.is256BitVector() &&
19271 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19272 SDValue V1 = N->getOperand(0);
19273 SDValue V2 = N->getOperand(1);
19275 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19276 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19277 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19278 ISD::isBuildVectorAllOnes(V2.getNode()))
19285 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19286 // register. In most cases we actually compare or select YMM-sized registers
19287 // and mixing the two types creates horrible code. This method optimizes
19288 // some of the transition sequences.
19289 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19290 TargetLowering::DAGCombinerInfo &DCI,
19291 const X86Subtarget *Subtarget) {
19292 EVT VT = N->getValueType(0);
19293 if (!VT.is256BitVector())
19296 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19297 N->getOpcode() == ISD::ZERO_EXTEND ||
19298 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19300 SDValue Narrow = N->getOperand(0);
19301 EVT NarrowVT = Narrow->getValueType(0);
19302 if (!NarrowVT.is128BitVector())
19305 if (Narrow->getOpcode() != ISD::XOR &&
19306 Narrow->getOpcode() != ISD::AND &&
19307 Narrow->getOpcode() != ISD::OR)
19310 SDValue N0 = Narrow->getOperand(0);
19311 SDValue N1 = Narrow->getOperand(1);
19314 // The Left side has to be a trunc.
19315 if (N0.getOpcode() != ISD::TRUNCATE)
19318 // The type of the truncated inputs.
19319 EVT WideVT = N0->getOperand(0)->getValueType(0);
19323 // The right side has to be a 'trunc' or a constant vector.
19324 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19325 bool RHSConst = (isSplatVector(N1.getNode()) &&
19326 isa<ConstantSDNode>(N1->getOperand(0)));
19327 if (!RHSTrunc && !RHSConst)
19330 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19332 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19335 // Set N0 and N1 to hold the inputs to the new wide operation.
19336 N0 = N0->getOperand(0);
19338 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19339 N1->getOperand(0));
19340 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19341 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19342 } else if (RHSTrunc) {
19343 N1 = N1->getOperand(0);
19346 // Generate the wide operation.
19347 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19348 unsigned Opcode = N->getOpcode();
19350 case ISD::ANY_EXTEND:
19352 case ISD::ZERO_EXTEND: {
19353 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19354 APInt Mask = APInt::getAllOnesValue(InBits);
19355 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19356 return DAG.getNode(ISD::AND, DL, VT,
19357 Op, DAG.getConstant(Mask, VT));
19359 case ISD::SIGN_EXTEND:
19360 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19361 Op, DAG.getValueType(NarrowVT));
19363 llvm_unreachable("Unexpected opcode");
19367 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19368 TargetLowering::DAGCombinerInfo &DCI,
19369 const X86Subtarget *Subtarget) {
19370 EVT VT = N->getValueType(0);
19371 if (DCI.isBeforeLegalizeOps())
19374 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19378 // Create BEXTR instructions
19379 // BEXTR is ((X >> imm) & (2**size-1))
19380 if (VT == MVT::i32 || VT == MVT::i64) {
19381 SDValue N0 = N->getOperand(0);
19382 SDValue N1 = N->getOperand(1);
19385 // Check for BEXTR.
19386 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19387 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19388 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19389 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19390 if (MaskNode && ShiftNode) {
19391 uint64_t Mask = MaskNode->getZExtValue();
19392 uint64_t Shift = ShiftNode->getZExtValue();
19393 if (isMask_64(Mask)) {
19394 uint64_t MaskSize = CountPopulation_64(Mask);
19395 if (Shift + MaskSize <= VT.getSizeInBits())
19396 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19397 DAG.getConstant(Shift | (MaskSize << 8), VT));
19405 // Want to form ANDNP nodes:
19406 // 1) In the hopes of then easily combining them with OR and AND nodes
19407 // to form PBLEND/PSIGN.
19408 // 2) To match ANDN packed intrinsics
19409 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19412 SDValue N0 = N->getOperand(0);
19413 SDValue N1 = N->getOperand(1);
19416 // Check LHS for vnot
19417 if (N0.getOpcode() == ISD::XOR &&
19418 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19419 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19420 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19422 // Check RHS for vnot
19423 if (N1.getOpcode() == ISD::XOR &&
19424 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19425 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19426 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19431 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19432 TargetLowering::DAGCombinerInfo &DCI,
19433 const X86Subtarget *Subtarget) {
19434 if (DCI.isBeforeLegalizeOps())
19437 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19441 SDValue N0 = N->getOperand(0);
19442 SDValue N1 = N->getOperand(1);
19443 EVT VT = N->getValueType(0);
19445 // look for psign/blend
19446 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19447 if (!Subtarget->hasSSSE3() ||
19448 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19451 // Canonicalize pandn to RHS
19452 if (N0.getOpcode() == X86ISD::ANDNP)
19454 // or (and (m, y), (pandn m, x))
19455 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19456 SDValue Mask = N1.getOperand(0);
19457 SDValue X = N1.getOperand(1);
19459 if (N0.getOperand(0) == Mask)
19460 Y = N0.getOperand(1);
19461 if (N0.getOperand(1) == Mask)
19462 Y = N0.getOperand(0);
19464 // Check to see if the mask appeared in both the AND and ANDNP and
19468 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19469 // Look through mask bitcast.
19470 if (Mask.getOpcode() == ISD::BITCAST)
19471 Mask = Mask.getOperand(0);
19472 if (X.getOpcode() == ISD::BITCAST)
19473 X = X.getOperand(0);
19474 if (Y.getOpcode() == ISD::BITCAST)
19475 Y = Y.getOperand(0);
19477 EVT MaskVT = Mask.getValueType();
19479 // Validate that the Mask operand is a vector sra node.
19480 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19481 // there is no psrai.b
19482 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19483 unsigned SraAmt = ~0;
19484 if (Mask.getOpcode() == ISD::SRA) {
19485 SDValue Amt = Mask.getOperand(1);
19486 if (isSplatVector(Amt.getNode())) {
19487 SDValue SclrAmt = Amt->getOperand(0);
19488 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19489 SraAmt = C->getZExtValue();
19491 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19492 SDValue SraC = Mask.getOperand(1);
19493 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19495 if ((SraAmt + 1) != EltBits)
19500 // Now we know we at least have a plendvb with the mask val. See if
19501 // we can form a psignb/w/d.
19502 // psign = x.type == y.type == mask.type && y = sub(0, x);
19503 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19504 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19505 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19506 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19507 "Unsupported VT for PSIGN");
19508 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19509 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19511 // PBLENDVB only available on SSE 4.1
19512 if (!Subtarget->hasSSE41())
19515 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19517 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19518 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19519 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19520 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19521 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19525 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19528 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19529 MachineFunction &MF = DAG.getMachineFunction();
19530 bool OptForSize = MF.getFunction()->getAttributes().
19531 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19533 // SHLD/SHRD instructions have lower register pressure, but on some
19534 // platforms they have higher latency than the equivalent
19535 // series of shifts/or that would otherwise be generated.
19536 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19537 // have higher latencies and we are not optimizing for size.
19538 if (!OptForSize && Subtarget->isSHLDSlow())
19541 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19543 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19545 if (!N0.hasOneUse() || !N1.hasOneUse())
19548 SDValue ShAmt0 = N0.getOperand(1);
19549 if (ShAmt0.getValueType() != MVT::i8)
19551 SDValue ShAmt1 = N1.getOperand(1);
19552 if (ShAmt1.getValueType() != MVT::i8)
19554 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19555 ShAmt0 = ShAmt0.getOperand(0);
19556 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19557 ShAmt1 = ShAmt1.getOperand(0);
19560 unsigned Opc = X86ISD::SHLD;
19561 SDValue Op0 = N0.getOperand(0);
19562 SDValue Op1 = N1.getOperand(0);
19563 if (ShAmt0.getOpcode() == ISD::SUB) {
19564 Opc = X86ISD::SHRD;
19565 std::swap(Op0, Op1);
19566 std::swap(ShAmt0, ShAmt1);
19569 unsigned Bits = VT.getSizeInBits();
19570 if (ShAmt1.getOpcode() == ISD::SUB) {
19571 SDValue Sum = ShAmt1.getOperand(0);
19572 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19573 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19574 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19575 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19576 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19577 return DAG.getNode(Opc, DL, VT,
19579 DAG.getNode(ISD::TRUNCATE, DL,
19582 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19583 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19585 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19586 return DAG.getNode(Opc, DL, VT,
19587 N0.getOperand(0), N1.getOperand(0),
19588 DAG.getNode(ISD::TRUNCATE, DL,
19595 // Generate NEG and CMOV for integer abs.
19596 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19597 EVT VT = N->getValueType(0);
19599 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19600 // 8-bit integer abs to NEG and CMOV.
19601 if (VT.isInteger() && VT.getSizeInBits() == 8)
19604 SDValue N0 = N->getOperand(0);
19605 SDValue N1 = N->getOperand(1);
19608 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19609 // and change it to SUB and CMOV.
19610 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19611 N0.getOpcode() == ISD::ADD &&
19612 N0.getOperand(1) == N1 &&
19613 N1.getOpcode() == ISD::SRA &&
19614 N1.getOperand(0) == N0.getOperand(0))
19615 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19616 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19617 // Generate SUB & CMOV.
19618 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19619 DAG.getConstant(0, VT), N0.getOperand(0));
19621 SDValue Ops[] = { N0.getOperand(0), Neg,
19622 DAG.getConstant(X86::COND_GE, MVT::i8),
19623 SDValue(Neg.getNode(), 1) };
19624 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19629 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19630 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19631 TargetLowering::DAGCombinerInfo &DCI,
19632 const X86Subtarget *Subtarget) {
19633 if (DCI.isBeforeLegalizeOps())
19636 if (Subtarget->hasCMov()) {
19637 SDValue RV = performIntegerAbsCombine(N, DAG);
19645 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19646 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19647 TargetLowering::DAGCombinerInfo &DCI,
19648 const X86Subtarget *Subtarget) {
19649 LoadSDNode *Ld = cast<LoadSDNode>(N);
19650 EVT RegVT = Ld->getValueType(0);
19651 EVT MemVT = Ld->getMemoryVT();
19653 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19654 unsigned RegSz = RegVT.getSizeInBits();
19656 // On Sandybridge unaligned 256bit loads are inefficient.
19657 ISD::LoadExtType Ext = Ld->getExtensionType();
19658 unsigned Alignment = Ld->getAlignment();
19659 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19660 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19661 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19662 unsigned NumElems = RegVT.getVectorNumElements();
19666 SDValue Ptr = Ld->getBasePtr();
19667 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19669 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19671 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19672 Ld->getPointerInfo(), Ld->isVolatile(),
19673 Ld->isNonTemporal(), Ld->isInvariant(),
19675 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19676 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19677 Ld->getPointerInfo(), Ld->isVolatile(),
19678 Ld->isNonTemporal(), Ld->isInvariant(),
19679 std::min(16U, Alignment));
19680 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19682 Load2.getValue(1));
19684 SDValue NewVec = DAG.getUNDEF(RegVT);
19685 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19686 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19687 return DCI.CombineTo(N, NewVec, TF, true);
19690 // If this is a vector EXT Load then attempt to optimize it using a
19691 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19692 // expansion is still better than scalar code.
19693 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19694 // emit a shuffle and a arithmetic shift.
19695 // TODO: It is possible to support ZExt by zeroing the undef values
19696 // during the shuffle phase or after the shuffle.
19697 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19698 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19699 assert(MemVT != RegVT && "Cannot extend to the same type");
19700 assert(MemVT.isVector() && "Must load a vector from memory");
19702 unsigned NumElems = RegVT.getVectorNumElements();
19703 unsigned MemSz = MemVT.getSizeInBits();
19704 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19706 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19709 // All sizes must be a power of two.
19710 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19713 // Attempt to load the original value using scalar loads.
19714 // Find the largest scalar type that divides the total loaded size.
19715 MVT SclrLoadTy = MVT::i8;
19716 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19717 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19718 MVT Tp = (MVT::SimpleValueType)tp;
19719 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19724 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19725 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19727 SclrLoadTy = MVT::f64;
19729 // Calculate the number of scalar loads that we need to perform
19730 // in order to load our vector from memory.
19731 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19732 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19735 unsigned loadRegZize = RegSz;
19736 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19739 // Represent our vector as a sequence of elements which are the
19740 // largest scalar that we can load.
19741 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19742 loadRegZize/SclrLoadTy.getSizeInBits());
19744 // Represent the data using the same element type that is stored in
19745 // memory. In practice, we ''widen'' MemVT.
19747 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19748 loadRegZize/MemVT.getScalarType().getSizeInBits());
19750 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19751 "Invalid vector type");
19753 // We can't shuffle using an illegal type.
19754 if (!TLI.isTypeLegal(WideVecVT))
19757 SmallVector<SDValue, 8> Chains;
19758 SDValue Ptr = Ld->getBasePtr();
19759 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19760 TLI.getPointerTy());
19761 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19763 for (unsigned i = 0; i < NumLoads; ++i) {
19764 // Perform a single load.
19765 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19766 Ptr, Ld->getPointerInfo(),
19767 Ld->isVolatile(), Ld->isNonTemporal(),
19768 Ld->isInvariant(), Ld->getAlignment());
19769 Chains.push_back(ScalarLoad.getValue(1));
19770 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19771 // another round of DAGCombining.
19773 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19775 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19776 ScalarLoad, DAG.getIntPtrConstant(i));
19778 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19781 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19783 // Bitcast the loaded value to a vector of the original element type, in
19784 // the size of the target vector type.
19785 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19786 unsigned SizeRatio = RegSz/MemSz;
19788 if (Ext == ISD::SEXTLOAD) {
19789 // If we have SSE4.1 we can directly emit a VSEXT node.
19790 if (Subtarget->hasSSE41()) {
19791 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19792 return DCI.CombineTo(N, Sext, TF, true);
19795 // Otherwise we'll shuffle the small elements in the high bits of the
19796 // larger type and perform an arithmetic shift. If the shift is not legal
19797 // it's better to scalarize.
19798 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19801 // Redistribute the loaded elements into the different locations.
19802 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19803 for (unsigned i = 0; i != NumElems; ++i)
19804 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19806 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19807 DAG.getUNDEF(WideVecVT),
19810 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19812 // Build the arithmetic shift.
19813 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19814 MemVT.getVectorElementType().getSizeInBits();
19815 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19816 DAG.getConstant(Amt, RegVT));
19818 return DCI.CombineTo(N, Shuff, TF, true);
19821 // Redistribute the loaded elements into the different locations.
19822 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19823 for (unsigned i = 0; i != NumElems; ++i)
19824 ShuffleVec[i*SizeRatio] = i;
19826 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19827 DAG.getUNDEF(WideVecVT),
19830 // Bitcast to the requested type.
19831 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19832 // Replace the original load with the new sequence
19833 // and return the new chain.
19834 return DCI.CombineTo(N, Shuff, TF, true);
19840 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19841 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19842 const X86Subtarget *Subtarget) {
19843 StoreSDNode *St = cast<StoreSDNode>(N);
19844 EVT VT = St->getValue().getValueType();
19845 EVT StVT = St->getMemoryVT();
19847 SDValue StoredVal = St->getOperand(1);
19848 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19850 // If we are saving a concatenation of two XMM registers, perform two stores.
19851 // On Sandy Bridge, 256-bit memory operations are executed by two
19852 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19853 // memory operation.
19854 unsigned Alignment = St->getAlignment();
19855 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19856 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19857 StVT == VT && !IsAligned) {
19858 unsigned NumElems = VT.getVectorNumElements();
19862 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19863 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19865 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19866 SDValue Ptr0 = St->getBasePtr();
19867 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19869 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19870 St->getPointerInfo(), St->isVolatile(),
19871 St->isNonTemporal(), Alignment);
19872 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19873 St->getPointerInfo(), St->isVolatile(),
19874 St->isNonTemporal(),
19875 std::min(16U, Alignment));
19876 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19879 // Optimize trunc store (of multiple scalars) to shuffle and store.
19880 // First, pack all of the elements in one place. Next, store to memory
19881 // in fewer chunks.
19882 if (St->isTruncatingStore() && VT.isVector()) {
19883 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19884 unsigned NumElems = VT.getVectorNumElements();
19885 assert(StVT != VT && "Cannot truncate to the same type");
19886 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19887 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19889 // From, To sizes and ElemCount must be pow of two
19890 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19891 // We are going to use the original vector elt for storing.
19892 // Accumulated smaller vector elements must be a multiple of the store size.
19893 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19895 unsigned SizeRatio = FromSz / ToSz;
19897 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19899 // Create a type on which we perform the shuffle
19900 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19901 StVT.getScalarType(), NumElems*SizeRatio);
19903 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19905 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19906 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19907 for (unsigned i = 0; i != NumElems; ++i)
19908 ShuffleVec[i] = i * SizeRatio;
19910 // Can't shuffle using an illegal type.
19911 if (!TLI.isTypeLegal(WideVecVT))
19914 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19915 DAG.getUNDEF(WideVecVT),
19917 // At this point all of the data is stored at the bottom of the
19918 // register. We now need to save it to mem.
19920 // Find the largest store unit
19921 MVT StoreType = MVT::i8;
19922 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19923 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19924 MVT Tp = (MVT::SimpleValueType)tp;
19925 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19929 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19930 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19931 (64 <= NumElems * ToSz))
19932 StoreType = MVT::f64;
19934 // Bitcast the original vector into a vector of store-size units
19935 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19936 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19937 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19938 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19939 SmallVector<SDValue, 8> Chains;
19940 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19941 TLI.getPointerTy());
19942 SDValue Ptr = St->getBasePtr();
19944 // Perform one or more big stores into memory.
19945 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19946 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19947 StoreType, ShuffWide,
19948 DAG.getIntPtrConstant(i));
19949 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19950 St->getPointerInfo(), St->isVolatile(),
19951 St->isNonTemporal(), St->getAlignment());
19952 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19953 Chains.push_back(Ch);
19956 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19959 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19960 // the FP state in cases where an emms may be missing.
19961 // A preferable solution to the general problem is to figure out the right
19962 // places to insert EMMS. This qualifies as a quick hack.
19964 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19965 if (VT.getSizeInBits() != 64)
19968 const Function *F = DAG.getMachineFunction().getFunction();
19969 bool NoImplicitFloatOps = F->getAttributes().
19970 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19971 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19972 && Subtarget->hasSSE2();
19973 if ((VT.isVector() ||
19974 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19975 isa<LoadSDNode>(St->getValue()) &&
19976 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19977 St->getChain().hasOneUse() && !St->isVolatile()) {
19978 SDNode* LdVal = St->getValue().getNode();
19979 LoadSDNode *Ld = nullptr;
19980 int TokenFactorIndex = -1;
19981 SmallVector<SDValue, 8> Ops;
19982 SDNode* ChainVal = St->getChain().getNode();
19983 // Must be a store of a load. We currently handle two cases: the load
19984 // is a direct child, and it's under an intervening TokenFactor. It is
19985 // possible to dig deeper under nested TokenFactors.
19986 if (ChainVal == LdVal)
19987 Ld = cast<LoadSDNode>(St->getChain());
19988 else if (St->getValue().hasOneUse() &&
19989 ChainVal->getOpcode() == ISD::TokenFactor) {
19990 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19991 if (ChainVal->getOperand(i).getNode() == LdVal) {
19992 TokenFactorIndex = i;
19993 Ld = cast<LoadSDNode>(St->getValue());
19995 Ops.push_back(ChainVal->getOperand(i));
19999 if (!Ld || !ISD::isNormalLoad(Ld))
20002 // If this is not the MMX case, i.e. we are just turning i64 load/store
20003 // into f64 load/store, avoid the transformation if there are multiple
20004 // uses of the loaded value.
20005 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20010 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20011 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20013 if (Subtarget->is64Bit() || F64IsLegal) {
20014 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20015 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20016 Ld->getPointerInfo(), Ld->isVolatile(),
20017 Ld->isNonTemporal(), Ld->isInvariant(),
20018 Ld->getAlignment());
20019 SDValue NewChain = NewLd.getValue(1);
20020 if (TokenFactorIndex != -1) {
20021 Ops.push_back(NewChain);
20022 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20024 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20025 St->getPointerInfo(),
20026 St->isVolatile(), St->isNonTemporal(),
20027 St->getAlignment());
20030 // Otherwise, lower to two pairs of 32-bit loads / stores.
20031 SDValue LoAddr = Ld->getBasePtr();
20032 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20033 DAG.getConstant(4, MVT::i32));
20035 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20036 Ld->getPointerInfo(),
20037 Ld->isVolatile(), Ld->isNonTemporal(),
20038 Ld->isInvariant(), Ld->getAlignment());
20039 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20040 Ld->getPointerInfo().getWithOffset(4),
20041 Ld->isVolatile(), Ld->isNonTemporal(),
20043 MinAlign(Ld->getAlignment(), 4));
20045 SDValue NewChain = LoLd.getValue(1);
20046 if (TokenFactorIndex != -1) {
20047 Ops.push_back(LoLd);
20048 Ops.push_back(HiLd);
20049 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20052 LoAddr = St->getBasePtr();
20053 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20054 DAG.getConstant(4, MVT::i32));
20056 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20057 St->getPointerInfo(),
20058 St->isVolatile(), St->isNonTemporal(),
20059 St->getAlignment());
20060 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20061 St->getPointerInfo().getWithOffset(4),
20063 St->isNonTemporal(),
20064 MinAlign(St->getAlignment(), 4));
20065 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20070 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20071 /// and return the operands for the horizontal operation in LHS and RHS. A
20072 /// horizontal operation performs the binary operation on successive elements
20073 /// of its first operand, then on successive elements of its second operand,
20074 /// returning the resulting values in a vector. For example, if
20075 /// A = < float a0, float a1, float a2, float a3 >
20077 /// B = < float b0, float b1, float b2, float b3 >
20078 /// then the result of doing a horizontal operation on A and B is
20079 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20080 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20081 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20082 /// set to A, RHS to B, and the routine returns 'true'.
20083 /// Note that the binary operation should have the property that if one of the
20084 /// operands is UNDEF then the result is UNDEF.
20085 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20086 // Look for the following pattern: if
20087 // A = < float a0, float a1, float a2, float a3 >
20088 // B = < float b0, float b1, float b2, float b3 >
20090 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20091 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20092 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20093 // which is A horizontal-op B.
20095 // At least one of the operands should be a vector shuffle.
20096 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20097 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20100 MVT VT = LHS.getSimpleValueType();
20102 assert((VT.is128BitVector() || VT.is256BitVector()) &&
20103 "Unsupported vector type for horizontal add/sub");
20105 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20106 // operate independently on 128-bit lanes.
20107 unsigned NumElts = VT.getVectorNumElements();
20108 unsigned NumLanes = VT.getSizeInBits()/128;
20109 unsigned NumLaneElts = NumElts / NumLanes;
20110 assert((NumLaneElts % 2 == 0) &&
20111 "Vector type should have an even number of elements in each lane");
20112 unsigned HalfLaneElts = NumLaneElts/2;
20114 // View LHS in the form
20115 // LHS = VECTOR_SHUFFLE A, B, LMask
20116 // If LHS is not a shuffle then pretend it is the shuffle
20117 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20118 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20121 SmallVector<int, 16> LMask(NumElts);
20122 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20123 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20124 A = LHS.getOperand(0);
20125 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20126 B = LHS.getOperand(1);
20127 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20128 std::copy(Mask.begin(), Mask.end(), LMask.begin());
20130 if (LHS.getOpcode() != ISD::UNDEF)
20132 for (unsigned i = 0; i != NumElts; ++i)
20136 // Likewise, view RHS in the form
20137 // RHS = VECTOR_SHUFFLE C, D, RMask
20139 SmallVector<int, 16> RMask(NumElts);
20140 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20141 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20142 C = RHS.getOperand(0);
20143 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20144 D = RHS.getOperand(1);
20145 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20146 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20148 if (RHS.getOpcode() != ISD::UNDEF)
20150 for (unsigned i = 0; i != NumElts; ++i)
20154 // Check that the shuffles are both shuffling the same vectors.
20155 if (!(A == C && B == D) && !(A == D && B == C))
20158 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20159 if (!A.getNode() && !B.getNode())
20162 // If A and B occur in reverse order in RHS, then "swap" them (which means
20163 // rewriting the mask).
20165 CommuteVectorShuffleMask(RMask, NumElts);
20167 // At this point LHS and RHS are equivalent to
20168 // LHS = VECTOR_SHUFFLE A, B, LMask
20169 // RHS = VECTOR_SHUFFLE A, B, RMask
20170 // Check that the masks correspond to performing a horizontal operation.
20171 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20172 for (unsigned i = 0; i != NumLaneElts; ++i) {
20173 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20175 // Ignore any UNDEF components.
20176 if (LIdx < 0 || RIdx < 0 ||
20177 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20178 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20181 // Check that successive elements are being operated on. If not, this is
20182 // not a horizontal operation.
20183 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20184 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20185 if (!(LIdx == Index && RIdx == Index + 1) &&
20186 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20191 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20192 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20196 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20197 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20198 const X86Subtarget *Subtarget) {
20199 EVT VT = N->getValueType(0);
20200 SDValue LHS = N->getOperand(0);
20201 SDValue RHS = N->getOperand(1);
20203 // Try to synthesize horizontal adds from adds of shuffles.
20204 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20205 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20206 isHorizontalBinOp(LHS, RHS, true))
20207 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20211 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20212 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20213 const X86Subtarget *Subtarget) {
20214 EVT VT = N->getValueType(0);
20215 SDValue LHS = N->getOperand(0);
20216 SDValue RHS = N->getOperand(1);
20218 // Try to synthesize horizontal subs from subs of shuffles.
20219 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20220 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20221 isHorizontalBinOp(LHS, RHS, false))
20222 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20226 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20227 /// X86ISD::FXOR nodes.
20228 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20229 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20230 // F[X]OR(0.0, x) -> x
20231 // F[X]OR(x, 0.0) -> x
20232 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20233 if (C->getValueAPF().isPosZero())
20234 return N->getOperand(1);
20235 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20236 if (C->getValueAPF().isPosZero())
20237 return N->getOperand(0);
20241 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20242 /// X86ISD::FMAX nodes.
20243 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20244 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20246 // Only perform optimizations if UnsafeMath is used.
20247 if (!DAG.getTarget().Options.UnsafeFPMath)
20250 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20251 // into FMINC and FMAXC, which are Commutative operations.
20252 unsigned NewOp = 0;
20253 switch (N->getOpcode()) {
20254 default: llvm_unreachable("unknown opcode");
20255 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20256 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20259 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20260 N->getOperand(0), N->getOperand(1));
20263 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20264 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20265 // FAND(0.0, x) -> 0.0
20266 // FAND(x, 0.0) -> 0.0
20267 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20268 if (C->getValueAPF().isPosZero())
20269 return N->getOperand(0);
20270 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20271 if (C->getValueAPF().isPosZero())
20272 return N->getOperand(1);
20276 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20277 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20278 // FANDN(x, 0.0) -> 0.0
20279 // FANDN(0.0, x) -> x
20280 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20281 if (C->getValueAPF().isPosZero())
20282 return N->getOperand(1);
20283 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20284 if (C->getValueAPF().isPosZero())
20285 return N->getOperand(1);
20289 static SDValue PerformBTCombine(SDNode *N,
20291 TargetLowering::DAGCombinerInfo &DCI) {
20292 // BT ignores high bits in the bit index operand.
20293 SDValue Op1 = N->getOperand(1);
20294 if (Op1.hasOneUse()) {
20295 unsigned BitWidth = Op1.getValueSizeInBits();
20296 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20297 APInt KnownZero, KnownOne;
20298 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20299 !DCI.isBeforeLegalizeOps());
20300 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20301 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20302 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20303 DCI.CommitTargetLoweringOpt(TLO);
20308 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20309 SDValue Op = N->getOperand(0);
20310 if (Op.getOpcode() == ISD::BITCAST)
20311 Op = Op.getOperand(0);
20312 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20313 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20314 VT.getVectorElementType().getSizeInBits() ==
20315 OpVT.getVectorElementType().getSizeInBits()) {
20316 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20321 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20322 const X86Subtarget *Subtarget) {
20323 EVT VT = N->getValueType(0);
20324 if (!VT.isVector())
20327 SDValue N0 = N->getOperand(0);
20328 SDValue N1 = N->getOperand(1);
20329 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20332 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20333 // both SSE and AVX2 since there is no sign-extended shift right
20334 // operation on a vector with 64-bit elements.
20335 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20336 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20337 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20338 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20339 SDValue N00 = N0.getOperand(0);
20341 // EXTLOAD has a better solution on AVX2,
20342 // it may be replaced with X86ISD::VSEXT node.
20343 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20344 if (!ISD::isNormalLoad(N00.getNode()))
20347 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20348 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20350 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20356 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20357 TargetLowering::DAGCombinerInfo &DCI,
20358 const X86Subtarget *Subtarget) {
20359 if (!DCI.isBeforeLegalizeOps())
20362 if (!Subtarget->hasFp256())
20365 EVT VT = N->getValueType(0);
20366 if (VT.isVector() && VT.getSizeInBits() == 256) {
20367 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20375 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20376 const X86Subtarget* Subtarget) {
20378 EVT VT = N->getValueType(0);
20380 // Let legalize expand this if it isn't a legal type yet.
20381 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20384 EVT ScalarVT = VT.getScalarType();
20385 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20386 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20389 SDValue A = N->getOperand(0);
20390 SDValue B = N->getOperand(1);
20391 SDValue C = N->getOperand(2);
20393 bool NegA = (A.getOpcode() == ISD::FNEG);
20394 bool NegB = (B.getOpcode() == ISD::FNEG);
20395 bool NegC = (C.getOpcode() == ISD::FNEG);
20397 // Negative multiplication when NegA xor NegB
20398 bool NegMul = (NegA != NegB);
20400 A = A.getOperand(0);
20402 B = B.getOperand(0);
20404 C = C.getOperand(0);
20408 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20410 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20412 return DAG.getNode(Opcode, dl, VT, A, B, C);
20415 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20416 TargetLowering::DAGCombinerInfo &DCI,
20417 const X86Subtarget *Subtarget) {
20418 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20419 // (and (i32 x86isd::setcc_carry), 1)
20420 // This eliminates the zext. This transformation is necessary because
20421 // ISD::SETCC is always legalized to i8.
20423 SDValue N0 = N->getOperand(0);
20424 EVT VT = N->getValueType(0);
20426 if (N0.getOpcode() == ISD::AND &&
20428 N0.getOperand(0).hasOneUse()) {
20429 SDValue N00 = N0.getOperand(0);
20430 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20431 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20432 if (!C || C->getZExtValue() != 1)
20434 return DAG.getNode(ISD::AND, dl, VT,
20435 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20436 N00.getOperand(0), N00.getOperand(1)),
20437 DAG.getConstant(1, VT));
20441 if (N0.getOpcode() == ISD::TRUNCATE &&
20443 N0.getOperand(0).hasOneUse()) {
20444 SDValue N00 = N0.getOperand(0);
20445 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20446 return DAG.getNode(ISD::AND, dl, VT,
20447 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20448 N00.getOperand(0), N00.getOperand(1)),
20449 DAG.getConstant(1, VT));
20452 if (VT.is256BitVector()) {
20453 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20461 // Optimize x == -y --> x+y == 0
20462 // x != -y --> x+y != 0
20463 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20464 const X86Subtarget* Subtarget) {
20465 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20466 SDValue LHS = N->getOperand(0);
20467 SDValue RHS = N->getOperand(1);
20468 EVT VT = N->getValueType(0);
20471 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20473 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20474 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20475 LHS.getValueType(), RHS, LHS.getOperand(1));
20476 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20477 addV, DAG.getConstant(0, addV.getValueType()), CC);
20479 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20481 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20482 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20483 RHS.getValueType(), LHS, RHS.getOperand(1));
20484 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20485 addV, DAG.getConstant(0, addV.getValueType()), CC);
20488 if (VT.getScalarType() == MVT::i1) {
20489 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20490 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20491 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20492 if (!IsSEXT0 && !IsVZero0)
20494 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20495 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20496 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20498 if (!IsSEXT1 && !IsVZero1)
20501 if (IsSEXT0 && IsVZero1) {
20502 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20503 if (CC == ISD::SETEQ)
20504 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20505 return LHS.getOperand(0);
20507 if (IsSEXT1 && IsVZero0) {
20508 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20509 if (CC == ISD::SETEQ)
20510 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20511 return RHS.getOperand(0);
20518 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20519 const X86Subtarget *Subtarget) {
20521 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20522 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20523 "X86insertps is only defined for v4x32");
20525 SDValue Ld = N->getOperand(1);
20526 if (MayFoldLoad(Ld)) {
20527 // Extract the countS bits from the immediate so we can get the proper
20528 // address when narrowing the vector load to a specific element.
20529 // When the second source op is a memory address, interps doesn't use
20530 // countS and just gets an f32 from that address.
20531 unsigned DestIndex =
20532 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20533 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20537 // Create this as a scalar to vector to match the instruction pattern.
20538 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20539 // countS bits are ignored when loading from memory on insertps, which
20540 // means we don't need to explicitly set them to 0.
20541 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20542 LoadScalarToVector, N->getOperand(2));
20545 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20546 // as "sbb reg,reg", since it can be extended without zext and produces
20547 // an all-ones bit which is more useful than 0/1 in some cases.
20548 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20551 return DAG.getNode(ISD::AND, DL, VT,
20552 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20553 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20554 DAG.getConstant(1, VT));
20555 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20556 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20557 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20558 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20561 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20562 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20563 TargetLowering::DAGCombinerInfo &DCI,
20564 const X86Subtarget *Subtarget) {
20566 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20567 SDValue EFLAGS = N->getOperand(1);
20569 if (CC == X86::COND_A) {
20570 // Try to convert COND_A into COND_B in an attempt to facilitate
20571 // materializing "setb reg".
20573 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20574 // cannot take an immediate as its first operand.
20576 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20577 EFLAGS.getValueType().isInteger() &&
20578 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20579 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20580 EFLAGS.getNode()->getVTList(),
20581 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20582 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20583 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20587 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20588 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20590 if (CC == X86::COND_B)
20591 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20595 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20596 if (Flags.getNode()) {
20597 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20598 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20604 // Optimize branch condition evaluation.
20606 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20607 TargetLowering::DAGCombinerInfo &DCI,
20608 const X86Subtarget *Subtarget) {
20610 SDValue Chain = N->getOperand(0);
20611 SDValue Dest = N->getOperand(1);
20612 SDValue EFLAGS = N->getOperand(3);
20613 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20617 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20618 if (Flags.getNode()) {
20619 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20620 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20627 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20628 const X86TargetLowering *XTLI) {
20629 SDValue Op0 = N->getOperand(0);
20630 EVT InVT = Op0->getValueType(0);
20632 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20633 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20635 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20636 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20637 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20640 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20641 // a 32-bit target where SSE doesn't support i64->FP operations.
20642 if (Op0.getOpcode() == ISD::LOAD) {
20643 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20644 EVT VT = Ld->getValueType(0);
20645 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20646 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20647 !XTLI->getSubtarget()->is64Bit() &&
20649 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20650 Ld->getChain(), Op0, DAG);
20651 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20658 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20659 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20660 X86TargetLowering::DAGCombinerInfo &DCI) {
20661 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20662 // the result is either zero or one (depending on the input carry bit).
20663 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20664 if (X86::isZeroNode(N->getOperand(0)) &&
20665 X86::isZeroNode(N->getOperand(1)) &&
20666 // We don't have a good way to replace an EFLAGS use, so only do this when
20668 SDValue(N, 1).use_empty()) {
20670 EVT VT = N->getValueType(0);
20671 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20672 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20673 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20674 DAG.getConstant(X86::COND_B,MVT::i8),
20676 DAG.getConstant(1, VT));
20677 return DCI.CombineTo(N, Res1, CarryOut);
20683 // fold (add Y, (sete X, 0)) -> adc 0, Y
20684 // (add Y, (setne X, 0)) -> sbb -1, Y
20685 // (sub (sete X, 0), Y) -> sbb 0, Y
20686 // (sub (setne X, 0), Y) -> adc -1, Y
20687 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20690 // Look through ZExts.
20691 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20692 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20695 SDValue SetCC = Ext.getOperand(0);
20696 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20699 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20700 if (CC != X86::COND_E && CC != X86::COND_NE)
20703 SDValue Cmp = SetCC.getOperand(1);
20704 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20705 !X86::isZeroNode(Cmp.getOperand(1)) ||
20706 !Cmp.getOperand(0).getValueType().isInteger())
20709 SDValue CmpOp0 = Cmp.getOperand(0);
20710 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20711 DAG.getConstant(1, CmpOp0.getValueType()));
20713 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20714 if (CC == X86::COND_NE)
20715 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20716 DL, OtherVal.getValueType(), OtherVal,
20717 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20718 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20719 DL, OtherVal.getValueType(), OtherVal,
20720 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20723 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20724 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20725 const X86Subtarget *Subtarget) {
20726 EVT VT = N->getValueType(0);
20727 SDValue Op0 = N->getOperand(0);
20728 SDValue Op1 = N->getOperand(1);
20730 // Try to synthesize horizontal adds from adds of shuffles.
20731 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20732 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20733 isHorizontalBinOp(Op0, Op1, true))
20734 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20736 return OptimizeConditionalInDecrement(N, DAG);
20739 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20740 const X86Subtarget *Subtarget) {
20741 SDValue Op0 = N->getOperand(0);
20742 SDValue Op1 = N->getOperand(1);
20744 // X86 can't encode an immediate LHS of a sub. See if we can push the
20745 // negation into a preceding instruction.
20746 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20747 // If the RHS of the sub is a XOR with one use and a constant, invert the
20748 // immediate. Then add one to the LHS of the sub so we can turn
20749 // X-Y -> X+~Y+1, saving one register.
20750 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20751 isa<ConstantSDNode>(Op1.getOperand(1))) {
20752 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20753 EVT VT = Op0.getValueType();
20754 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20756 DAG.getConstant(~XorC, VT));
20757 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20758 DAG.getConstant(C->getAPIntValue()+1, VT));
20762 // Try to synthesize horizontal adds from adds of shuffles.
20763 EVT VT = N->getValueType(0);
20764 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20765 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20766 isHorizontalBinOp(Op0, Op1, true))
20767 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20769 return OptimizeConditionalInDecrement(N, DAG);
20772 /// performVZEXTCombine - Performs build vector combines
20773 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20774 TargetLowering::DAGCombinerInfo &DCI,
20775 const X86Subtarget *Subtarget) {
20776 // (vzext (bitcast (vzext (x)) -> (vzext x)
20777 SDValue In = N->getOperand(0);
20778 while (In.getOpcode() == ISD::BITCAST)
20779 In = In.getOperand(0);
20781 if (In.getOpcode() != X86ISD::VZEXT)
20784 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20788 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20789 DAGCombinerInfo &DCI) const {
20790 SelectionDAG &DAG = DCI.DAG;
20791 switch (N->getOpcode()) {
20793 case ISD::EXTRACT_VECTOR_ELT:
20794 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20796 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20797 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20798 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20799 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20800 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20801 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20804 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20805 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20806 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20807 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20808 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20809 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20810 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20811 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20812 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20814 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20816 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20817 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20818 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20819 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20820 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20821 case ISD::ANY_EXTEND:
20822 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20823 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20824 case ISD::SIGN_EXTEND_INREG:
20825 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20826 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20827 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20828 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20829 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20830 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20831 case X86ISD::SHUFP: // Handle all target specific shuffles
20832 case X86ISD::PALIGNR:
20833 case X86ISD::UNPCKH:
20834 case X86ISD::UNPCKL:
20835 case X86ISD::MOVHLPS:
20836 case X86ISD::MOVLHPS:
20837 case X86ISD::PSHUFD:
20838 case X86ISD::PSHUFHW:
20839 case X86ISD::PSHUFLW:
20840 case X86ISD::MOVSS:
20841 case X86ISD::MOVSD:
20842 case X86ISD::VPERMILP:
20843 case X86ISD::VPERM2X128:
20844 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20845 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20846 case ISD::INTRINSIC_WO_CHAIN:
20847 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20848 case X86ISD::INSERTPS:
20849 return PerformINSERTPSCombine(N, DAG, Subtarget);
20850 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
20856 /// isTypeDesirableForOp - Return true if the target has native support for
20857 /// the specified value type and it is 'desirable' to use the type for the
20858 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20859 /// instruction encodings are longer and some i16 instructions are slow.
20860 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20861 if (!isTypeLegal(VT))
20863 if (VT != MVT::i16)
20870 case ISD::SIGN_EXTEND:
20871 case ISD::ZERO_EXTEND:
20872 case ISD::ANY_EXTEND:
20885 /// IsDesirableToPromoteOp - This method query the target whether it is
20886 /// beneficial for dag combiner to promote the specified node. If true, it
20887 /// should return the desired promotion type by reference.
20888 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20889 EVT VT = Op.getValueType();
20890 if (VT != MVT::i16)
20893 bool Promote = false;
20894 bool Commute = false;
20895 switch (Op.getOpcode()) {
20898 LoadSDNode *LD = cast<LoadSDNode>(Op);
20899 // If the non-extending load has a single use and it's not live out, then it
20900 // might be folded.
20901 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20902 Op.hasOneUse()*/) {
20903 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20904 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20905 // The only case where we'd want to promote LOAD (rather then it being
20906 // promoted as an operand is when it's only use is liveout.
20907 if (UI->getOpcode() != ISD::CopyToReg)
20914 case ISD::SIGN_EXTEND:
20915 case ISD::ZERO_EXTEND:
20916 case ISD::ANY_EXTEND:
20921 SDValue N0 = Op.getOperand(0);
20922 // Look out for (store (shl (load), x)).
20923 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20936 SDValue N0 = Op.getOperand(0);
20937 SDValue N1 = Op.getOperand(1);
20938 if (!Commute && MayFoldLoad(N1))
20940 // Avoid disabling potential load folding opportunities.
20941 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20943 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20953 //===----------------------------------------------------------------------===//
20954 // X86 Inline Assembly Support
20955 //===----------------------------------------------------------------------===//
20958 // Helper to match a string separated by whitespace.
20959 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20960 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20962 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20963 StringRef piece(*args[i]);
20964 if (!s.startswith(piece)) // Check if the piece matches.
20967 s = s.substr(piece.size());
20968 StringRef::size_type pos = s.find_first_not_of(" \t");
20969 if (pos == 0) // We matched a prefix.
20977 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20980 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20982 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20983 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20984 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20985 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20987 if (AsmPieces.size() == 3)
20989 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20996 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20997 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20999 std::string AsmStr = IA->getAsmString();
21001 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21002 if (!Ty || Ty->getBitWidth() % 16 != 0)
21005 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21006 SmallVector<StringRef, 4> AsmPieces;
21007 SplitString(AsmStr, AsmPieces, ";\n");
21009 switch (AsmPieces.size()) {
21010 default: return false;
21012 // FIXME: this should verify that we are targeting a 486 or better. If not,
21013 // we will turn this bswap into something that will be lowered to logical
21014 // ops instead of emitting the bswap asm. For now, we don't support 486 or
21015 // lower so don't worry about this.
21017 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21018 matchAsm(AsmPieces[0], "bswapl", "$0") ||
21019 matchAsm(AsmPieces[0], "bswapq", "$0") ||
21020 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21021 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21022 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21023 // No need to check constraints, nothing other than the equivalent of
21024 // "=r,0" would be valid here.
21025 return IntrinsicLowering::LowerToByteSwap(CI);
21028 // rorw $$8, ${0:w} --> llvm.bswap.i16
21029 if (CI->getType()->isIntegerTy(16) &&
21030 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21031 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21032 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21034 const std::string &ConstraintsStr = IA->getConstraintString();
21035 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21036 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21037 if (clobbersFlagRegisters(AsmPieces))
21038 return IntrinsicLowering::LowerToByteSwap(CI);
21042 if (CI->getType()->isIntegerTy(32) &&
21043 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21044 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21045 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21046 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21048 const std::string &ConstraintsStr = IA->getConstraintString();
21049 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21050 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21051 if (clobbersFlagRegisters(AsmPieces))
21052 return IntrinsicLowering::LowerToByteSwap(CI);
21055 if (CI->getType()->isIntegerTy(64)) {
21056 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21057 if (Constraints.size() >= 2 &&
21058 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21059 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21060 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
21061 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21062 matchAsm(AsmPieces[1], "bswap", "%edx") &&
21063 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21064 return IntrinsicLowering::LowerToByteSwap(CI);
21072 /// getConstraintType - Given a constraint letter, return the type of
21073 /// constraint it is for this target.
21074 X86TargetLowering::ConstraintType
21075 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21076 if (Constraint.size() == 1) {
21077 switch (Constraint[0]) {
21088 return C_RegisterClass;
21112 return TargetLowering::getConstraintType(Constraint);
21115 /// Examine constraint type and operand type and determine a weight value.
21116 /// This object must already have been set up with the operand type
21117 /// and the current alternative constraint selected.
21118 TargetLowering::ConstraintWeight
21119 X86TargetLowering::getSingleConstraintMatchWeight(
21120 AsmOperandInfo &info, const char *constraint) const {
21121 ConstraintWeight weight = CW_Invalid;
21122 Value *CallOperandVal = info.CallOperandVal;
21123 // If we don't have a value, we can't do a match,
21124 // but allow it at the lowest weight.
21125 if (!CallOperandVal)
21127 Type *type = CallOperandVal->getType();
21128 // Look at the constraint type.
21129 switch (*constraint) {
21131 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21142 if (CallOperandVal->getType()->isIntegerTy())
21143 weight = CW_SpecificReg;
21148 if (type->isFloatingPointTy())
21149 weight = CW_SpecificReg;
21152 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21153 weight = CW_SpecificReg;
21157 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21158 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21159 weight = CW_Register;
21162 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21163 if (C->getZExtValue() <= 31)
21164 weight = CW_Constant;
21168 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21169 if (C->getZExtValue() <= 63)
21170 weight = CW_Constant;
21174 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21175 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21176 weight = CW_Constant;
21180 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21181 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21182 weight = CW_Constant;
21186 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21187 if (C->getZExtValue() <= 3)
21188 weight = CW_Constant;
21192 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21193 if (C->getZExtValue() <= 0xff)
21194 weight = CW_Constant;
21199 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21200 weight = CW_Constant;
21204 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21205 if ((C->getSExtValue() >= -0x80000000LL) &&
21206 (C->getSExtValue() <= 0x7fffffffLL))
21207 weight = CW_Constant;
21211 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21212 if (C->getZExtValue() <= 0xffffffff)
21213 weight = CW_Constant;
21220 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21221 /// with another that has more specific requirements based on the type of the
21222 /// corresponding operand.
21223 const char *X86TargetLowering::
21224 LowerXConstraint(EVT ConstraintVT) const {
21225 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21226 // 'f' like normal targets.
21227 if (ConstraintVT.isFloatingPoint()) {
21228 if (Subtarget->hasSSE2())
21230 if (Subtarget->hasSSE1())
21234 return TargetLowering::LowerXConstraint(ConstraintVT);
21237 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21238 /// vector. If it is invalid, don't add anything to Ops.
21239 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21240 std::string &Constraint,
21241 std::vector<SDValue>&Ops,
21242 SelectionDAG &DAG) const {
21245 // Only support length 1 constraints for now.
21246 if (Constraint.length() > 1) return;
21248 char ConstraintLetter = Constraint[0];
21249 switch (ConstraintLetter) {
21252 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21253 if (C->getZExtValue() <= 31) {
21254 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21260 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21261 if (C->getZExtValue() <= 63) {
21262 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21268 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21269 if (isInt<8>(C->getSExtValue())) {
21270 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21277 if (C->getZExtValue() <= 255) {
21278 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21284 // 32-bit signed value
21285 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21286 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21287 C->getSExtValue())) {
21288 // Widen to 64 bits here to get it sign extended.
21289 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21292 // FIXME gcc accepts some relocatable values here too, but only in certain
21293 // memory models; it's complicated.
21298 // 32-bit unsigned value
21299 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21300 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21301 C->getZExtValue())) {
21302 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21306 // FIXME gcc accepts some relocatable values here too, but only in certain
21307 // memory models; it's complicated.
21311 // Literal immediates are always ok.
21312 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21313 // Widen to 64 bits here to get it sign extended.
21314 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21318 // In any sort of PIC mode addresses need to be computed at runtime by
21319 // adding in a register or some sort of table lookup. These can't
21320 // be used as immediates.
21321 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21324 // If we are in non-pic codegen mode, we allow the address of a global (with
21325 // an optional displacement) to be used with 'i'.
21326 GlobalAddressSDNode *GA = nullptr;
21327 int64_t Offset = 0;
21329 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21331 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21332 Offset += GA->getOffset();
21334 } else if (Op.getOpcode() == ISD::ADD) {
21335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21336 Offset += C->getZExtValue();
21337 Op = Op.getOperand(0);
21340 } else if (Op.getOpcode() == ISD::SUB) {
21341 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21342 Offset += -C->getZExtValue();
21343 Op = Op.getOperand(0);
21348 // Otherwise, this isn't something we can handle, reject it.
21352 const GlobalValue *GV = GA->getGlobal();
21353 // If we require an extra load to get this address, as in PIC mode, we
21354 // can't accept it.
21355 if (isGlobalStubReference(
21356 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21359 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21360 GA->getValueType(0), Offset);
21365 if (Result.getNode()) {
21366 Ops.push_back(Result);
21369 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21372 std::pair<unsigned, const TargetRegisterClass*>
21373 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21375 // First, see if this is a constraint that directly corresponds to an LLVM
21377 if (Constraint.size() == 1) {
21378 // GCC Constraint Letters
21379 switch (Constraint[0]) {
21381 // TODO: Slight differences here in allocation order and leaving
21382 // RIP in the class. Do they matter any more here than they do
21383 // in the normal allocation?
21384 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21385 if (Subtarget->is64Bit()) {
21386 if (VT == MVT::i32 || VT == MVT::f32)
21387 return std::make_pair(0U, &X86::GR32RegClass);
21388 if (VT == MVT::i16)
21389 return std::make_pair(0U, &X86::GR16RegClass);
21390 if (VT == MVT::i8 || VT == MVT::i1)
21391 return std::make_pair(0U, &X86::GR8RegClass);
21392 if (VT == MVT::i64 || VT == MVT::f64)
21393 return std::make_pair(0U, &X86::GR64RegClass);
21396 // 32-bit fallthrough
21397 case 'Q': // Q_REGS
21398 if (VT == MVT::i32 || VT == MVT::f32)
21399 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21400 if (VT == MVT::i16)
21401 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21402 if (VT == MVT::i8 || VT == MVT::i1)
21403 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21404 if (VT == MVT::i64)
21405 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21407 case 'r': // GENERAL_REGS
21408 case 'l': // INDEX_REGS
21409 if (VT == MVT::i8 || VT == MVT::i1)
21410 return std::make_pair(0U, &X86::GR8RegClass);
21411 if (VT == MVT::i16)
21412 return std::make_pair(0U, &X86::GR16RegClass);
21413 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21414 return std::make_pair(0U, &X86::GR32RegClass);
21415 return std::make_pair(0U, &X86::GR64RegClass);
21416 case 'R': // LEGACY_REGS
21417 if (VT == MVT::i8 || VT == MVT::i1)
21418 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21419 if (VT == MVT::i16)
21420 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21421 if (VT == MVT::i32 || !Subtarget->is64Bit())
21422 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21423 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21424 case 'f': // FP Stack registers.
21425 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21426 // value to the correct fpstack register class.
21427 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21428 return std::make_pair(0U, &X86::RFP32RegClass);
21429 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21430 return std::make_pair(0U, &X86::RFP64RegClass);
21431 return std::make_pair(0U, &X86::RFP80RegClass);
21432 case 'y': // MMX_REGS if MMX allowed.
21433 if (!Subtarget->hasMMX()) break;
21434 return std::make_pair(0U, &X86::VR64RegClass);
21435 case 'Y': // SSE_REGS if SSE2 allowed
21436 if (!Subtarget->hasSSE2()) break;
21438 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21439 if (!Subtarget->hasSSE1()) break;
21441 switch (VT.SimpleTy) {
21443 // Scalar SSE types.
21446 return std::make_pair(0U, &X86::FR32RegClass);
21449 return std::make_pair(0U, &X86::FR64RegClass);
21457 return std::make_pair(0U, &X86::VR128RegClass);
21465 return std::make_pair(0U, &X86::VR256RegClass);
21470 return std::make_pair(0U, &X86::VR512RegClass);
21476 // Use the default implementation in TargetLowering to convert the register
21477 // constraint into a member of a register class.
21478 std::pair<unsigned, const TargetRegisterClass*> Res;
21479 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21481 // Not found as a standard register?
21483 // Map st(0) -> st(7) -> ST0
21484 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21485 tolower(Constraint[1]) == 's' &&
21486 tolower(Constraint[2]) == 't' &&
21487 Constraint[3] == '(' &&
21488 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21489 Constraint[5] == ')' &&
21490 Constraint[6] == '}') {
21492 Res.first = X86::ST0+Constraint[4]-'0';
21493 Res.second = &X86::RFP80RegClass;
21497 // GCC allows "st(0)" to be called just plain "st".
21498 if (StringRef("{st}").equals_lower(Constraint)) {
21499 Res.first = X86::ST0;
21500 Res.second = &X86::RFP80RegClass;
21505 if (StringRef("{flags}").equals_lower(Constraint)) {
21506 Res.first = X86::EFLAGS;
21507 Res.second = &X86::CCRRegClass;
21511 // 'A' means EAX + EDX.
21512 if (Constraint == "A") {
21513 Res.first = X86::EAX;
21514 Res.second = &X86::GR32_ADRegClass;
21520 // Otherwise, check to see if this is a register class of the wrong value
21521 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21522 // turn into {ax},{dx}.
21523 if (Res.second->hasType(VT))
21524 return Res; // Correct type already, nothing to do.
21526 // All of the single-register GCC register classes map their values onto
21527 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21528 // really want an 8-bit or 32-bit register, map to the appropriate register
21529 // class and return the appropriate register.
21530 if (Res.second == &X86::GR16RegClass) {
21531 if (VT == MVT::i8 || VT == MVT::i1) {
21532 unsigned DestReg = 0;
21533 switch (Res.first) {
21535 case X86::AX: DestReg = X86::AL; break;
21536 case X86::DX: DestReg = X86::DL; break;
21537 case X86::CX: DestReg = X86::CL; break;
21538 case X86::BX: DestReg = X86::BL; break;
21541 Res.first = DestReg;
21542 Res.second = &X86::GR8RegClass;
21544 } else if (VT == MVT::i32 || VT == MVT::f32) {
21545 unsigned DestReg = 0;
21546 switch (Res.first) {
21548 case X86::AX: DestReg = X86::EAX; break;
21549 case X86::DX: DestReg = X86::EDX; break;
21550 case X86::CX: DestReg = X86::ECX; break;
21551 case X86::BX: DestReg = X86::EBX; break;
21552 case X86::SI: DestReg = X86::ESI; break;
21553 case X86::DI: DestReg = X86::EDI; break;
21554 case X86::BP: DestReg = X86::EBP; break;
21555 case X86::SP: DestReg = X86::ESP; break;
21558 Res.first = DestReg;
21559 Res.second = &X86::GR32RegClass;
21561 } else if (VT == MVT::i64 || VT == MVT::f64) {
21562 unsigned DestReg = 0;
21563 switch (Res.first) {
21565 case X86::AX: DestReg = X86::RAX; break;
21566 case X86::DX: DestReg = X86::RDX; break;
21567 case X86::CX: DestReg = X86::RCX; break;
21568 case X86::BX: DestReg = X86::RBX; break;
21569 case X86::SI: DestReg = X86::RSI; break;
21570 case X86::DI: DestReg = X86::RDI; break;
21571 case X86::BP: DestReg = X86::RBP; break;
21572 case X86::SP: DestReg = X86::RSP; break;
21575 Res.first = DestReg;
21576 Res.second = &X86::GR64RegClass;
21579 } else if (Res.second == &X86::FR32RegClass ||
21580 Res.second == &X86::FR64RegClass ||
21581 Res.second == &X86::VR128RegClass ||
21582 Res.second == &X86::VR256RegClass ||
21583 Res.second == &X86::FR32XRegClass ||
21584 Res.second == &X86::FR64XRegClass ||
21585 Res.second == &X86::VR128XRegClass ||
21586 Res.second == &X86::VR256XRegClass ||
21587 Res.second == &X86::VR512RegClass) {
21588 // Handle references to XMM physical registers that got mapped into the
21589 // wrong class. This can happen with constraints like {xmm0} where the
21590 // target independent register mapper will just pick the first match it can
21591 // find, ignoring the required type.
21593 if (VT == MVT::f32 || VT == MVT::i32)
21594 Res.second = &X86::FR32RegClass;
21595 else if (VT == MVT::f64 || VT == MVT::i64)
21596 Res.second = &X86::FR64RegClass;
21597 else if (X86::VR128RegClass.hasType(VT))
21598 Res.second = &X86::VR128RegClass;
21599 else if (X86::VR256RegClass.hasType(VT))
21600 Res.second = &X86::VR256RegClass;
21601 else if (X86::VR512RegClass.hasType(VT))
21602 Res.second = &X86::VR512RegClass;
21608 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21610 // Scaling factors are not free at all.
21611 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21612 // will take 2 allocations in the out of order engine instead of 1
21613 // for plain addressing mode, i.e. inst (reg1).
21615 // vaddps (%rsi,%drx), %ymm0, %ymm1
21616 // Requires two allocations (one for the load, one for the computation)
21618 // vaddps (%rsi), %ymm0, %ymm1
21619 // Requires just 1 allocation, i.e., freeing allocations for other operations
21620 // and having less micro operations to execute.
21622 // For some X86 architectures, this is even worse because for instance for
21623 // stores, the complex addressing mode forces the instruction to use the
21624 // "load" ports instead of the dedicated "store" port.
21625 // E.g., on Haswell:
21626 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21627 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21628 if (isLegalAddressingMode(AM, Ty))
21629 // Scale represents reg2 * scale, thus account for 1
21630 // as soon as we use a second register.
21631 return AM.Scale != 0;
21635 bool X86TargetLowering::isTargetFTOL() const {
21636 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();