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(X86TargetMachine &TM) {
182 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
183 bool is64Bit = Subtarget->is64Bit();
185 if (Subtarget->isTargetMacho()) {
187 return new X86_64MachoTargetObjectFile();
188 return new TargetLoweringObjectFileMachO();
191 if (Subtarget->isTargetLinux())
192 return new X86LinuxTargetObjectFile();
193 if (Subtarget->isTargetELF())
194 return new TargetLoweringObjectFileELF();
195 if (Subtarget->isTargetKnownWindowsMSVC())
196 return new X86WindowsTargetObjectFile();
197 if (Subtarget->isTargetCOFF())
198 return new TargetLoweringObjectFileCOFF();
199 llvm_unreachable("unknown subtarget type");
202 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
203 : TargetLowering(TM, createTLOF(TM)) {
204 Subtarget = &TM.getSubtarget<X86Subtarget>();
205 X86ScalarSSEf64 = Subtarget->hasSSE2();
206 X86ScalarSSEf32 = Subtarget->hasSSE1();
207 TD = getDataLayout();
209 resetOperationActions();
212 void X86TargetLowering::resetOperationActions() {
213 const TargetMachine &TM = getTargetMachine();
214 static bool FirstTimeThrough = true;
216 // If none of the target options have changed, then we don't need to reset the
217 // operation actions.
218 if (!FirstTimeThrough && TO == TM.Options) return;
220 if (!FirstTimeThrough) {
221 // Reinitialize the actions.
223 FirstTimeThrough = false;
228 // Set up the TargetLowering object.
229 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
231 // X86 is weird, it always uses i8 for shift amounts and setcc results.
232 setBooleanContents(ZeroOrOneBooleanContent);
233 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
234 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
236 // For 64-bit since we have so many registers use the ILP scheduler, for
237 // 32-bit code use the register pressure specific scheduling.
238 // For Atom, always use ILP scheduling.
239 if (Subtarget->isAtom())
240 setSchedulingPreference(Sched::ILP);
241 else if (Subtarget->is64Bit())
242 setSchedulingPreference(Sched::ILP);
244 setSchedulingPreference(Sched::RegPressure);
245 const X86RegisterInfo *RegInfo =
246 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
247 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
249 // Bypass expensive divides on Atom when compiling with O2
250 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
251 addBypassSlowDiv(32, 8);
252 if (Subtarget->is64Bit())
253 addBypassSlowDiv(64, 16);
256 if (Subtarget->isTargetKnownWindowsMSVC()) {
257 // Setup Windows compiler runtime calls.
258 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
259 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
260 setLibcallName(RTLIB::SREM_I64, "_allrem");
261 setLibcallName(RTLIB::UREM_I64, "_aullrem");
262 setLibcallName(RTLIB::MUL_I64, "_allmul");
263 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
266 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
267 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
269 // The _ftol2 runtime function has an unusual calling conv, which
270 // is modeled by a special pseudo-instruction.
271 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
273 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
274 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
277 if (Subtarget->isTargetDarwin()) {
278 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
279 setUseUnderscoreSetJmp(false);
280 setUseUnderscoreLongJmp(false);
281 } else if (Subtarget->isTargetWindowsGNU()) {
282 // MS runtime is weird: it exports _setjmp, but longjmp!
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(false);
286 setUseUnderscoreSetJmp(true);
287 setUseUnderscoreLongJmp(true);
290 // Set up the register classes.
291 addRegisterClass(MVT::i8, &X86::GR8RegClass);
292 addRegisterClass(MVT::i16, &X86::GR16RegClass);
293 addRegisterClass(MVT::i32, &X86::GR32RegClass);
294 if (Subtarget->is64Bit())
295 addRegisterClass(MVT::i64, &X86::GR64RegClass);
297 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
299 // We don't accept any truncstore of integer registers.
300 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
301 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
304 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
305 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
307 // SETOEQ and SETUNE require checking two conditions.
308 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
315 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
317 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
318 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
319 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
323 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
324 } else if (!TM.Options.UseSoftFloat) {
325 // We have an algorithm for SSE2->double, and we turn this into a
326 // 64-bit FILD followed by conditional FADD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
328 // We have an algorithm for SSE2, and we turn this into a 64-bit
329 // FILD for other targets.
330 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
333 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
335 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
336 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
338 if (!TM.Options.UseSoftFloat) {
339 // SSE has no i16 to fp conversion, only i32
340 if (X86ScalarSSEf32) {
341 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
342 // f32 and f64 cases are Legal, f80 case is not
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
345 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
350 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
353 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
354 // are Legal, f80 is custom lowered.
355 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
356 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
358 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
360 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
361 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
363 if (X86ScalarSSEf32) {
364 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
365 // f32 and f64 cases are Legal, f80 case is not
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
368 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
369 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
372 // Handle FP_TO_UINT by promoting the destination to a larger signed
374 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
375 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
376 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
378 if (Subtarget->is64Bit()) {
379 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
380 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
381 } else if (!TM.Options.UseSoftFloat) {
382 // Since AVX is a superset of SSE3, only check for SSE here.
383 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384 // Expand FP_TO_UINT into a select.
385 // FIXME: We would like to use a Custom expander here eventually to do
386 // the optimal thing for SSE vs. the default expansion in the legalizer.
387 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
389 // With SSE3 we can use fisttpll to convert to a signed i64; without
390 // SSE, we're stuck with a fistpll.
391 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
394 if (isTargetFTOL()) {
395 // Use the _ftol2 runtime function, which has a pseudo-instruction
396 // to handle its weird calling convention.
397 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
400 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401 if (!X86ScalarSSEf64) {
402 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
403 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
404 if (Subtarget->is64Bit()) {
405 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
406 // Without SSE, i64->f64 goes through memory.
407 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
411 // Scalar integer divide and remainder are lowered to use operations that
412 // produce two results, to match the available instructions. This exposes
413 // the two-result form to trivial CSE, which is able to combine x/y and x%y
414 // into a single instruction.
416 // Scalar integer multiply-high is also lowered to use two-result
417 // operations, to match the available instructions. However, plain multiply
418 // (low) operations are left as Legal, as there are single-result
419 // instructions for this in x86. Using the two-result multiply instructions
420 // when both high and low results are needed must be arranged by dagcombine.
421 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
423 setOperationAction(ISD::MULHS, VT, Expand);
424 setOperationAction(ISD::MULHU, VT, Expand);
425 setOperationAction(ISD::SDIV, VT, Expand);
426 setOperationAction(ISD::UDIV, VT, Expand);
427 setOperationAction(ISD::SREM, VT, Expand);
428 setOperationAction(ISD::UREM, VT, Expand);
430 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431 setOperationAction(ISD::ADDC, VT, Custom);
432 setOperationAction(ISD::ADDE, VT, Custom);
433 setOperationAction(ISD::SUBC, VT, Custom);
434 setOperationAction(ISD::SUBE, VT, Custom);
437 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
438 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
439 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
440 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
441 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
444 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
445 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
446 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
447 if (Subtarget->is64Bit())
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
450 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
451 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
452 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
453 setOperationAction(ISD::FREM , MVT::f32 , Expand);
454 setOperationAction(ISD::FREM , MVT::f64 , Expand);
455 setOperationAction(ISD::FREM , MVT::f80 , Expand);
456 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
458 // Promote the i8 variants and force them on up to i32 which has a shorter
460 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
463 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
464 if (Subtarget->hasBMI()) {
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
467 if (Subtarget->is64Bit())
468 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
470 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
471 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
472 if (Subtarget->is64Bit())
473 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
476 if (Subtarget->hasLZCNT()) {
477 // When promoting the i8 variants, force them to i32 for a shorter
479 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
482 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
492 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
494 if (Subtarget->is64Bit()) {
495 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
500 if (Subtarget->hasPOPCNT()) {
501 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
503 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
504 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
505 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
506 if (Subtarget->is64Bit())
507 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
510 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
512 if (!Subtarget->hasMOVBE())
513 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
515 // These should be promoted to a larger select which is supported.
516 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
517 // X86 wants to expand cmov itself.
518 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
519 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
520 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
522 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
523 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
526 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
528 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
530 if (Subtarget->is64Bit()) {
531 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
532 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
534 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
535 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537 // support continuation, user-level threading, and etc.. As a result, no
538 // other SjLj exception interfaces are implemented and please don't build
539 // your own exception handling based on them.
540 // LLVM/Clang supports zero-cost DWARF exception handling.
541 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
545 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
546 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
547 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
548 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
549 if (Subtarget->is64Bit())
550 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
551 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
552 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
553 if (Subtarget->is64Bit()) {
554 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
555 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
556 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
557 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
558 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
560 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
561 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
562 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
563 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
566 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
567 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
570 if (Subtarget->hasSSE1())
571 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
573 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
575 // Expand certain atomics
576 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
578 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
579 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
580 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
583 if (!Subtarget->is64Bit()) {
584 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
594 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
595 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
598 if (Subtarget->hasCmpxchg16b()) {
599 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
602 // FIXME - use subtarget debug flags
603 if (!Subtarget->isTargetDarwin() &&
604 !Subtarget->isTargetELF() &&
605 !Subtarget->isTargetCygMing()) {
606 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
609 if (Subtarget->is64Bit()) {
610 setExceptionPointerRegister(X86::RAX);
611 setExceptionSelectorRegister(X86::RDX);
613 setExceptionPointerRegister(X86::EAX);
614 setExceptionSelectorRegister(X86::EDX);
616 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
617 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
619 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
620 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
622 setOperationAction(ISD::TRAP, MVT::Other, Legal);
623 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
625 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
626 setOperationAction(ISD::VASTART , MVT::Other, Custom);
627 setOperationAction(ISD::VAEND , MVT::Other, Expand);
628 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
629 // TargetInfo::X86_64ABIBuiltinVaList
630 setOperationAction(ISD::VAARG , MVT::Other, Custom);
631 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
633 // TargetInfo::CharPtrBuiltinVaList
634 setOperationAction(ISD::VAARG , MVT::Other, Expand);
635 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
638 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
639 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
641 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642 MVT::i64 : MVT::i32, Custom);
644 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645 // f32 and f64 use SSE.
646 // Set up the FP register classes.
647 addRegisterClass(MVT::f32, &X86::FR32RegClass);
648 addRegisterClass(MVT::f64, &X86::FR64RegClass);
650 // Use ANDPD to simulate FABS.
651 setOperationAction(ISD::FABS , MVT::f64, Custom);
652 setOperationAction(ISD::FABS , MVT::f32, Custom);
654 // Use XORP to simulate FNEG.
655 setOperationAction(ISD::FNEG , MVT::f64, Custom);
656 setOperationAction(ISD::FNEG , MVT::f32, Custom);
658 // Use ANDPD and ORPD to simulate FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
662 // Lower this to FGETSIGNx86 plus an AND.
663 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
666 // We don't support sin/cos/fmod
667 setOperationAction(ISD::FSIN , MVT::f64, Expand);
668 setOperationAction(ISD::FCOS , MVT::f64, Expand);
669 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670 setOperationAction(ISD::FSIN , MVT::f32, Expand);
671 setOperationAction(ISD::FCOS , MVT::f32, Expand);
672 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
674 // Expand FP immediates into loads from the stack, except for the special
676 addLegalFPImmediate(APFloat(+0.0)); // xorpd
677 addLegalFPImmediate(APFloat(+0.0f)); // xorps
678 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679 // Use SSE for f32, x87 for f64.
680 // Set up the FP register classes.
681 addRegisterClass(MVT::f32, &X86::FR32RegClass);
682 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
684 // Use ANDPS to simulate FABS.
685 setOperationAction(ISD::FABS , MVT::f32, Custom);
687 // Use XORP to simulate FNEG.
688 setOperationAction(ISD::FNEG , MVT::f32, Custom);
690 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
692 // Use ANDPS and ORPS to simulate FCOPYSIGN.
693 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
696 // We don't support sin/cos/fmod
697 setOperationAction(ISD::FSIN , MVT::f32, Expand);
698 setOperationAction(ISD::FCOS , MVT::f32, Expand);
699 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
701 // Special cases we handle for FP constants.
702 addLegalFPImmediate(APFloat(+0.0f)); // xorps
703 addLegalFPImmediate(APFloat(+0.0)); // FLD0
704 addLegalFPImmediate(APFloat(+1.0)); // FLD1
705 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
708 if (!TM.Options.UnsafeFPMath) {
709 setOperationAction(ISD::FSIN , MVT::f64, Expand);
710 setOperationAction(ISD::FCOS , MVT::f64, Expand);
711 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
713 } else if (!TM.Options.UseSoftFloat) {
714 // f32 and f64 in x87.
715 // Set up the FP register classes.
716 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
719 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
720 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
721 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
724 if (!TM.Options.UnsafeFPMath) {
725 setOperationAction(ISD::FSIN , MVT::f64, Expand);
726 setOperationAction(ISD::FSIN , MVT::f32, Expand);
727 setOperationAction(ISD::FCOS , MVT::f64, Expand);
728 setOperationAction(ISD::FCOS , MVT::f32, Expand);
729 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
732 addLegalFPImmediate(APFloat(+0.0)); // FLD0
733 addLegalFPImmediate(APFloat(+1.0)); // FLD1
734 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
742 // We don't support FMA.
743 setOperationAction(ISD::FMA, MVT::f64, Expand);
744 setOperationAction(ISD::FMA, MVT::f32, Expand);
746 // Long double always uses X87.
747 if (!TM.Options.UseSoftFloat) {
748 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
750 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
752 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753 addLegalFPImmediate(TmpFlt); // FLD0
755 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
758 APFloat TmpFlt2(+1.0);
759 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
761 addLegalFPImmediate(TmpFlt2); // FLD1
762 TmpFlt2.changeSign();
763 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
766 if (!TM.Options.UnsafeFPMath) {
767 setOperationAction(ISD::FSIN , MVT::f80, Expand);
768 setOperationAction(ISD::FCOS , MVT::f80, Expand);
769 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
772 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
774 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775 setOperationAction(ISD::FRINT, MVT::f80, Expand);
776 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777 setOperationAction(ISD::FMA, MVT::f80, Expand);
780 // Always use a library call for pow.
781 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
782 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
783 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
785 setOperationAction(ISD::FLOG, MVT::f80, Expand);
786 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788 setOperationAction(ISD::FEXP, MVT::f80, Expand);
789 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
791 // First set operation action for all vector types to either promote
792 // (for widening) or expand (for scalarization). Then we will selectively
793 // turn on ones that can be effectively codegen'd.
794 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796 MVT VT = (MVT::SimpleValueType)i;
797 setOperationAction(ISD::ADD , VT, Expand);
798 setOperationAction(ISD::SUB , VT, Expand);
799 setOperationAction(ISD::FADD, VT, Expand);
800 setOperationAction(ISD::FNEG, VT, Expand);
801 setOperationAction(ISD::FSUB, VT, Expand);
802 setOperationAction(ISD::MUL , VT, Expand);
803 setOperationAction(ISD::FMUL, VT, Expand);
804 setOperationAction(ISD::SDIV, VT, Expand);
805 setOperationAction(ISD::UDIV, VT, Expand);
806 setOperationAction(ISD::FDIV, VT, Expand);
807 setOperationAction(ISD::SREM, VT, Expand);
808 setOperationAction(ISD::UREM, VT, Expand);
809 setOperationAction(ISD::LOAD, VT, Expand);
810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815 setOperationAction(ISD::FABS, VT, Expand);
816 setOperationAction(ISD::FSIN, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FCOS, VT, Expand);
819 setOperationAction(ISD::FSINCOS, VT, Expand);
820 setOperationAction(ISD::FREM, VT, Expand);
821 setOperationAction(ISD::FMA, VT, Expand);
822 setOperationAction(ISD::FPOWI, VT, Expand);
823 setOperationAction(ISD::FSQRT, VT, Expand);
824 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825 setOperationAction(ISD::FFLOOR, VT, Expand);
826 setOperationAction(ISD::FCEIL, VT, Expand);
827 setOperationAction(ISD::FTRUNC, VT, Expand);
828 setOperationAction(ISD::FRINT, VT, Expand);
829 setOperationAction(ISD::FNEARBYINT, VT, Expand);
830 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831 setOperationAction(ISD::MULHS, VT, Expand);
832 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833 setOperationAction(ISD::MULHU, VT, Expand);
834 setOperationAction(ISD::SDIVREM, VT, Expand);
835 setOperationAction(ISD::UDIVREM, VT, Expand);
836 setOperationAction(ISD::FPOW, VT, Expand);
837 setOperationAction(ISD::CTPOP, VT, Expand);
838 setOperationAction(ISD::CTTZ, VT, Expand);
839 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::CTLZ, VT, Expand);
841 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842 setOperationAction(ISD::SHL, VT, Expand);
843 setOperationAction(ISD::SRA, VT, Expand);
844 setOperationAction(ISD::SRL, VT, Expand);
845 setOperationAction(ISD::ROTL, VT, Expand);
846 setOperationAction(ISD::ROTR, VT, Expand);
847 setOperationAction(ISD::BSWAP, VT, Expand);
848 setOperationAction(ISD::SETCC, VT, Expand);
849 setOperationAction(ISD::FLOG, VT, Expand);
850 setOperationAction(ISD::FLOG2, VT, Expand);
851 setOperationAction(ISD::FLOG10, VT, Expand);
852 setOperationAction(ISD::FEXP, VT, Expand);
853 setOperationAction(ISD::FEXP2, VT, Expand);
854 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859 setOperationAction(ISD::TRUNCATE, VT, Expand);
860 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863 setOperationAction(ISD::VSELECT, VT, Expand);
864 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866 setTruncStoreAction(VT,
867 (MVT::SimpleValueType)InnerVT, Expand);
868 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
873 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874 // with -msoft-float, disable use of MMX as well.
875 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877 // No operations on x86mmx supported, everything uses intrinsics.
880 // MMX-sized vectors (other than x86mmx) are expected to be expanded
881 // into smaller operations.
882 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
883 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
884 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
885 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
886 setOperationAction(ISD::AND, MVT::v8i8, Expand);
887 setOperationAction(ISD::AND, MVT::v4i16, Expand);
888 setOperationAction(ISD::AND, MVT::v2i32, Expand);
889 setOperationAction(ISD::AND, MVT::v1i64, Expand);
890 setOperationAction(ISD::OR, MVT::v8i8, Expand);
891 setOperationAction(ISD::OR, MVT::v4i16, Expand);
892 setOperationAction(ISD::OR, MVT::v2i32, Expand);
893 setOperationAction(ISD::OR, MVT::v1i64, Expand);
894 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
895 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
896 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
897 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
902 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
903 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
904 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
905 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
906 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
910 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
912 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
915 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
916 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
917 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
918 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
919 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
920 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
921 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
922 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
923 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
924 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
925 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
929 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
932 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933 // registers cannot be used even for integer operations.
934 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
939 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
940 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
941 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
942 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
943 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
944 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
945 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
946 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
947 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
948 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
949 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
950 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
951 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
952 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
953 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
954 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
956 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
957 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
958 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
959 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
960 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
962 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
963 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
964 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
965 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
967 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
968 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
970 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
971 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
973 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
974 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
975 MVT VT = (MVT::SimpleValueType)i;
976 // Do not attempt to custom lower non-power-of-2 vectors
977 if (!isPowerOf2_32(VT.getVectorNumElements()))
979 // Do not attempt to custom lower non-128-bit vectors
980 if (!VT.is128BitVector())
982 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
983 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
984 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
987 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
988 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
990 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
994 if (Subtarget->is64Bit()) {
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
999 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1000 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to promote non-128-bit vectors
1004 if (!VT.is128BitVector())
1007 setOperationAction(ISD::AND, VT, Promote);
1008 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1009 setOperationAction(ISD::OR, VT, Promote);
1010 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1011 setOperationAction(ISD::XOR, VT, Promote);
1012 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1013 setOperationAction(ISD::LOAD, VT, Promote);
1014 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1015 setOperationAction(ISD::SELECT, VT, Promote);
1016 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1019 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1021 // Custom lower v2i64 and v2f64 selects.
1022 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1023 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1024 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1025 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1027 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1028 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1031 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1032 // As there is no 64-bit GPR available, we need build a special custom
1033 // sequence to convert from v2i32 to v2f32.
1034 if (!Subtarget->is64Bit())
1035 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1037 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1038 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1040 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1042 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1043 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1044 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1047 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1048 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1049 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1050 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1051 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1052 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1053 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1054 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1055 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1056 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1057 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1059 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1060 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1061 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1062 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1063 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1064 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1065 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1066 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1067 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1068 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1070 // FIXME: Do we need to handle scalar-to-vector here?
1071 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1073 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1074 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1075 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1076 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1077 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1078 // There is no BLENDI for byte vectors. We don't need to custom lower
1079 // some vselects for now.
1080 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1082 // i8 and i16 vectors are custom , because the source register and source
1083 // source memory operand types are not the same width. f32 vectors are
1084 // custom since the immediate controlling the insert encodes additional
1086 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1087 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1088 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1089 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1092 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1093 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1094 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1096 // FIXME: these should be Legal but thats only for the case where
1097 // the index is constant. For now custom expand to deal with that.
1098 if (Subtarget->is64Bit()) {
1099 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1100 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1104 if (Subtarget->hasSSE2()) {
1105 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1106 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1108 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1109 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1111 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1112 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1114 // In the customized shift lowering, the legal cases in AVX2 will be
1116 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1117 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1119 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1120 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1122 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1125 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1126 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1127 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1128 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1129 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1130 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1131 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1133 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1134 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1135 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1137 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1148 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1150 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1161 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1163 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1164 // even though v8i16 is a legal type.
1165 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1166 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1167 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1169 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1170 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1171 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1173 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1174 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1176 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1178 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1184 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1185 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1187 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1188 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1189 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1190 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1192 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1193 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1194 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1196 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1197 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1198 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1199 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1201 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1202 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1203 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1204 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1205 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1206 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1207 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1208 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1209 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1210 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1211 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1212 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1214 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1215 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1216 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1217 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1218 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1219 setOperationAction(ISD::FMA, MVT::f32, Legal);
1220 setOperationAction(ISD::FMA, MVT::f64, Legal);
1223 if (Subtarget->hasInt256()) {
1224 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1225 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1226 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1227 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1229 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1230 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1231 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1232 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1234 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1235 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1236 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1237 // Don't lower v32i8 because there is no 128-bit byte mul
1239 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1240 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1241 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1242 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1244 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1245 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1247 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1248 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1249 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1250 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1252 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1253 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1254 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1255 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1257 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1258 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1259 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1260 // Don't lower v32i8 because there is no 128-bit byte mul
1263 // In the customized shift lowering, the legal cases in AVX2 will be
1265 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1266 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1268 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1269 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1271 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1273 // Custom lower several nodes for 256-bit types.
1274 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1275 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1276 MVT VT = (MVT::SimpleValueType)i;
1278 // Extract subvector is special because the value type
1279 // (result) is 128-bit but the source is 256-bit wide.
1280 if (VT.is128BitVector())
1281 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1283 // Do not attempt to custom lower other non-256-bit vectors
1284 if (!VT.is256BitVector())
1287 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1288 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1289 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1290 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1291 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1292 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1293 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1296 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1297 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1298 MVT VT = (MVT::SimpleValueType)i;
1300 // Do not attempt to promote non-256-bit vectors
1301 if (!VT.is256BitVector())
1304 setOperationAction(ISD::AND, VT, Promote);
1305 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1306 setOperationAction(ISD::OR, VT, Promote);
1307 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1308 setOperationAction(ISD::XOR, VT, Promote);
1309 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1310 setOperationAction(ISD::LOAD, VT, Promote);
1311 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1312 setOperationAction(ISD::SELECT, VT, Promote);
1313 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1317 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1318 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1319 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1320 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1321 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1323 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1324 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1325 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1327 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1328 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1329 setOperationAction(ISD::XOR, MVT::i1, Legal);
1330 setOperationAction(ISD::OR, MVT::i1, Legal);
1331 setOperationAction(ISD::AND, MVT::i1, Legal);
1332 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1333 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1334 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1335 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1336 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1337 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1339 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1340 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1341 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1342 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1343 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1344 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1346 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1347 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1348 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1349 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1350 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1351 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1352 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1355 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1356 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1357 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1358 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1359 if (Subtarget->is64Bit()) {
1360 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1361 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1362 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1363 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1365 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1366 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1367 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1368 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1369 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1370 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1371 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1372 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1373 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1374 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1376 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1377 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1378 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1379 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1380 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1381 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1382 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1383 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1384 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1385 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1386 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1387 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1388 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1390 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1391 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1392 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1393 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1394 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1395 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1397 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1398 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1400 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1402 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1403 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1404 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1405 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1406 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1407 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1408 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1409 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1410 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1412 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1413 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1415 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1416 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1418 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1420 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1421 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1423 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1424 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1426 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1427 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1429 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1430 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1431 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1432 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1433 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1434 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1436 // Custom lower several nodes.
1437 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1438 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1439 MVT VT = (MVT::SimpleValueType)i;
1441 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1442 // Extract subvector is special because the value type
1443 // (result) is 256/128-bit but the source is 512-bit wide.
1444 if (VT.is128BitVector() || VT.is256BitVector())
1445 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1447 if (VT.getVectorElementType() == MVT::i1)
1448 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1450 // Do not attempt to custom lower other non-512-bit vectors
1451 if (!VT.is512BitVector())
1454 if ( EltSize >= 32) {
1455 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1456 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1457 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1458 setOperationAction(ISD::VSELECT, VT, Legal);
1459 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1460 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1461 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1464 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1465 MVT VT = (MVT::SimpleValueType)i;
1467 // Do not attempt to promote non-256-bit vectors
1468 if (!VT.is512BitVector())
1471 setOperationAction(ISD::SELECT, VT, Promote);
1472 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1476 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1477 // of this type with custom code.
1478 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1479 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1480 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1484 // We want to custom lower some of our intrinsics.
1485 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1486 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1487 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1488 if (!Subtarget->is64Bit())
1489 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1491 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1492 // handle type legalization for these operations here.
1494 // FIXME: We really should do custom legalization for addition and
1495 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1496 // than generic legalization for 64-bit multiplication-with-overflow, though.
1497 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1498 // Add/Sub/Mul with overflow operations are custom lowered.
1500 setOperationAction(ISD::SADDO, VT, Custom);
1501 setOperationAction(ISD::UADDO, VT, Custom);
1502 setOperationAction(ISD::SSUBO, VT, Custom);
1503 setOperationAction(ISD::USUBO, VT, Custom);
1504 setOperationAction(ISD::SMULO, VT, Custom);
1505 setOperationAction(ISD::UMULO, VT, Custom);
1508 // There are no 8-bit 3-address imul/mul instructions
1509 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1510 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1512 if (!Subtarget->is64Bit()) {
1513 // These libcalls are not available in 32-bit.
1514 setLibcallName(RTLIB::SHL_I128, nullptr);
1515 setLibcallName(RTLIB::SRL_I128, nullptr);
1516 setLibcallName(RTLIB::SRA_I128, nullptr);
1519 // Combine sin / cos into one node or libcall if possible.
1520 if (Subtarget->hasSinCos()) {
1521 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1522 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1523 if (Subtarget->isTargetDarwin()) {
1524 // For MacOSX, we don't want to the normal expansion of a libcall to
1525 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1527 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1528 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1532 if (Subtarget->isTargetWin64()) {
1533 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1534 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1535 setOperationAction(ISD::SREM, MVT::i128, Custom);
1536 setOperationAction(ISD::UREM, MVT::i128, Custom);
1537 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1538 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1541 // We have target-specific dag combine patterns for the following nodes:
1542 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1543 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1544 setTargetDAGCombine(ISD::VSELECT);
1545 setTargetDAGCombine(ISD::SELECT);
1546 setTargetDAGCombine(ISD::SHL);
1547 setTargetDAGCombine(ISD::SRA);
1548 setTargetDAGCombine(ISD::SRL);
1549 setTargetDAGCombine(ISD::OR);
1550 setTargetDAGCombine(ISD::AND);
1551 setTargetDAGCombine(ISD::ADD);
1552 setTargetDAGCombine(ISD::FADD);
1553 setTargetDAGCombine(ISD::FSUB);
1554 setTargetDAGCombine(ISD::FMA);
1555 setTargetDAGCombine(ISD::SUB);
1556 setTargetDAGCombine(ISD::LOAD);
1557 setTargetDAGCombine(ISD::STORE);
1558 setTargetDAGCombine(ISD::ZERO_EXTEND);
1559 setTargetDAGCombine(ISD::ANY_EXTEND);
1560 setTargetDAGCombine(ISD::SIGN_EXTEND);
1561 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1562 setTargetDAGCombine(ISD::TRUNCATE);
1563 setTargetDAGCombine(ISD::SINT_TO_FP);
1564 setTargetDAGCombine(ISD::SETCC);
1565 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1566 if (Subtarget->is64Bit())
1567 setTargetDAGCombine(ISD::MUL);
1568 setTargetDAGCombine(ISD::XOR);
1570 computeRegisterProperties();
1572 // On Darwin, -Os means optimize for size without hurting performance,
1573 // do not reduce the limit.
1574 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1575 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1576 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1577 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1578 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1579 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1580 setPrefLoopAlignment(4); // 2^4 bytes.
1582 // Predictable cmov don't hurt on atom because it's in-order.
1583 PredictableSelectIsExpensive = !Subtarget->isAtom();
1585 setPrefFunctionAlignment(4); // 2^4 bytes.
1588 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1590 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1592 if (Subtarget->hasAVX512())
1593 switch(VT.getVectorNumElements()) {
1594 case 8: return MVT::v8i1;
1595 case 16: return MVT::v16i1;
1598 return VT.changeVectorElementTypeToInteger();
1601 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1602 /// the desired ByVal argument alignment.
1603 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1606 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1607 if (VTy->getBitWidth() == 128)
1609 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1610 unsigned EltAlign = 0;
1611 getMaxByValAlign(ATy->getElementType(), EltAlign);
1612 if (EltAlign > MaxAlign)
1613 MaxAlign = EltAlign;
1614 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1615 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1616 unsigned EltAlign = 0;
1617 getMaxByValAlign(STy->getElementType(i), EltAlign);
1618 if (EltAlign > MaxAlign)
1619 MaxAlign = EltAlign;
1626 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1627 /// function arguments in the caller parameter area. For X86, aggregates
1628 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1629 /// are at 4-byte boundaries.
1630 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1631 if (Subtarget->is64Bit()) {
1632 // Max of 8 and alignment of type.
1633 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1640 if (Subtarget->hasSSE1())
1641 getMaxByValAlign(Ty, Align);
1645 /// getOptimalMemOpType - Returns the target specific optimal type for load
1646 /// and store operations as a result of memset, memcpy, and memmove
1647 /// lowering. If DstAlign is zero that means it's safe to destination
1648 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1649 /// means there isn't a need to check it against alignment requirement,
1650 /// probably because the source does not need to be loaded. If 'IsMemset' is
1651 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1652 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1653 /// source is constant so it does not need to be loaded.
1654 /// It returns EVT::Other if the type should be determined using generic
1655 /// target-independent logic.
1657 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1658 unsigned DstAlign, unsigned SrcAlign,
1659 bool IsMemset, bool ZeroMemset,
1661 MachineFunction &MF) const {
1662 const Function *F = MF.getFunction();
1663 if ((!IsMemset || ZeroMemset) &&
1664 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1665 Attribute::NoImplicitFloat)) {
1667 (Subtarget->isUnalignedMemAccessFast() ||
1668 ((DstAlign == 0 || DstAlign >= 16) &&
1669 (SrcAlign == 0 || SrcAlign >= 16)))) {
1671 if (Subtarget->hasInt256())
1673 if (Subtarget->hasFp256())
1676 if (Subtarget->hasSSE2())
1678 if (Subtarget->hasSSE1())
1680 } else if (!MemcpyStrSrc && Size >= 8 &&
1681 !Subtarget->is64Bit() &&
1682 Subtarget->hasSSE2()) {
1683 // Do not use f64 to lower memcpy if source is string constant. It's
1684 // better to use i32 to avoid the loads.
1688 if (Subtarget->is64Bit() && Size >= 8)
1693 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1695 return X86ScalarSSEf32;
1696 else if (VT == MVT::f64)
1697 return X86ScalarSSEf64;
1702 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1706 *Fast = Subtarget->isUnalignedMemAccessFast();
1710 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1711 /// current function. The returned value is a member of the
1712 /// MachineJumpTableInfo::JTEntryKind enum.
1713 unsigned X86TargetLowering::getJumpTableEncoding() const {
1714 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1716 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1717 Subtarget->isPICStyleGOT())
1718 return MachineJumpTableInfo::EK_Custom32;
1720 // Otherwise, use the normal jump table encoding heuristics.
1721 return TargetLowering::getJumpTableEncoding();
1725 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1726 const MachineBasicBlock *MBB,
1727 unsigned uid,MCContext &Ctx) const{
1728 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1729 Subtarget->isPICStyleGOT());
1730 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1732 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1733 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1736 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1738 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1739 SelectionDAG &DAG) const {
1740 if (!Subtarget->is64Bit())
1741 // This doesn't have SDLoc associated with it, but is not really the
1742 // same as a Register.
1743 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1747 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1748 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1750 const MCExpr *X86TargetLowering::
1751 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1752 MCContext &Ctx) const {
1753 // X86-64 uses RIP relative addressing based on the jump table label.
1754 if (Subtarget->isPICStyleRIPRel())
1755 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1757 // Otherwise, the reference is relative to the PIC base.
1758 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1761 // FIXME: Why this routine is here? Move to RegInfo!
1762 std::pair<const TargetRegisterClass*, uint8_t>
1763 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1764 const TargetRegisterClass *RRC = nullptr;
1766 switch (VT.SimpleTy) {
1768 return TargetLowering::findRepresentativeClass(VT);
1769 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1770 RRC = Subtarget->is64Bit() ?
1771 (const TargetRegisterClass*)&X86::GR64RegClass :
1772 (const TargetRegisterClass*)&X86::GR32RegClass;
1775 RRC = &X86::VR64RegClass;
1777 case MVT::f32: case MVT::f64:
1778 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1779 case MVT::v4f32: case MVT::v2f64:
1780 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1782 RRC = &X86::VR128RegClass;
1785 return std::make_pair(RRC, Cost);
1788 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1789 unsigned &Offset) const {
1790 if (!Subtarget->isTargetLinux())
1793 if (Subtarget->is64Bit()) {
1794 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1796 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1808 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1809 unsigned DestAS) const {
1810 assert(SrcAS != DestAS && "Expected different address spaces!");
1812 return SrcAS < 256 && DestAS < 256;
1815 //===----------------------------------------------------------------------===//
1816 // Return Value Calling Convention Implementation
1817 //===----------------------------------------------------------------------===//
1819 #include "X86GenCallingConv.inc"
1822 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1823 MachineFunction &MF, bool isVarArg,
1824 const SmallVectorImpl<ISD::OutputArg> &Outs,
1825 LLVMContext &Context) const {
1826 SmallVector<CCValAssign, 16> RVLocs;
1827 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1829 return CCInfo.CheckReturn(Outs, RetCC_X86);
1832 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1833 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1838 X86TargetLowering::LowerReturn(SDValue Chain,
1839 CallingConv::ID CallConv, bool isVarArg,
1840 const SmallVectorImpl<ISD::OutputArg> &Outs,
1841 const SmallVectorImpl<SDValue> &OutVals,
1842 SDLoc dl, SelectionDAG &DAG) const {
1843 MachineFunction &MF = DAG.getMachineFunction();
1844 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1846 SmallVector<CCValAssign, 16> RVLocs;
1847 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1848 RVLocs, *DAG.getContext());
1849 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1852 SmallVector<SDValue, 6> RetOps;
1853 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1854 // Operand #1 = Bytes To Pop
1855 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1858 // Copy the result values into the output registers.
1859 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1860 CCValAssign &VA = RVLocs[i];
1861 assert(VA.isRegLoc() && "Can only return in registers!");
1862 SDValue ValToCopy = OutVals[i];
1863 EVT ValVT = ValToCopy.getValueType();
1865 // Promote values to the appropriate types
1866 if (VA.getLocInfo() == CCValAssign::SExt)
1867 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1868 else if (VA.getLocInfo() == CCValAssign::ZExt)
1869 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1870 else if (VA.getLocInfo() == CCValAssign::AExt)
1871 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1872 else if (VA.getLocInfo() == CCValAssign::BCvt)
1873 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1875 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1876 "Unexpected FP-extend for return value.");
1878 // If this is x86-64, and we disabled SSE, we can't return FP values,
1879 // or SSE or MMX vectors.
1880 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1881 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1882 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1883 report_fatal_error("SSE register return with SSE disabled");
1885 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1886 // llvm-gcc has never done it right and no one has noticed, so this
1887 // should be OK for now.
1888 if (ValVT == MVT::f64 &&
1889 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1890 report_fatal_error("SSE2 register return with SSE2 disabled");
1892 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1893 // the RET instruction and handled by the FP Stackifier.
1894 if (VA.getLocReg() == X86::ST0 ||
1895 VA.getLocReg() == X86::ST1) {
1896 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1897 // change the value to the FP stack register class.
1898 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1899 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1900 RetOps.push_back(ValToCopy);
1901 // Don't emit a copytoreg.
1905 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1906 // which is returned in RAX / RDX.
1907 if (Subtarget->is64Bit()) {
1908 if (ValVT == MVT::x86mmx) {
1909 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1910 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1911 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1913 // If we don't have SSE2 available, convert to v4f32 so the generated
1914 // register is legal.
1915 if (!Subtarget->hasSSE2())
1916 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1921 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1922 Flag = Chain.getValue(1);
1923 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1926 // The x86-64 ABIs require that for returning structs by value we copy
1927 // the sret argument into %rax/%eax (depending on ABI) for the return.
1928 // Win32 requires us to put the sret argument to %eax as well.
1929 // We saved the argument into a virtual register in the entry block,
1930 // so now we copy the value out and into %rax/%eax.
1931 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1932 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1933 MachineFunction &MF = DAG.getMachineFunction();
1934 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1935 unsigned Reg = FuncInfo->getSRetReturnReg();
1937 "SRetReturnReg should have been set in LowerFormalArguments().");
1938 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1941 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1942 X86::RAX : X86::EAX;
1943 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1944 Flag = Chain.getValue(1);
1946 // RAX/EAX now acts like a return value.
1947 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1950 RetOps[0] = Chain; // Update chain.
1952 // Add the flag if we have it.
1954 RetOps.push_back(Flag);
1956 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1959 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1960 if (N->getNumValues() != 1)
1962 if (!N->hasNUsesOfValue(1, 0))
1965 SDValue TCChain = Chain;
1966 SDNode *Copy = *N->use_begin();
1967 if (Copy->getOpcode() == ISD::CopyToReg) {
1968 // If the copy has a glue operand, we conservatively assume it isn't safe to
1969 // perform a tail call.
1970 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1972 TCChain = Copy->getOperand(0);
1973 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1976 bool HasRet = false;
1977 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1979 if (UI->getOpcode() != X86ISD::RET_FLAG)
1992 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1993 ISD::NodeType ExtendKind) const {
1995 // TODO: Is this also valid on 32-bit?
1996 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1997 ReturnMVT = MVT::i8;
1999 ReturnMVT = MVT::i32;
2001 MVT MinVT = getRegisterType(ReturnMVT);
2002 return VT.bitsLT(MinVT) ? MinVT : VT;
2005 /// LowerCallResult - Lower the result values of a call into the
2006 /// appropriate copies out of appropriate physical registers.
2009 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2010 CallingConv::ID CallConv, bool isVarArg,
2011 const SmallVectorImpl<ISD::InputArg> &Ins,
2012 SDLoc dl, SelectionDAG &DAG,
2013 SmallVectorImpl<SDValue> &InVals) const {
2015 // Assign locations to each value returned by this call.
2016 SmallVector<CCValAssign, 16> RVLocs;
2017 bool Is64Bit = Subtarget->is64Bit();
2018 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2019 getTargetMachine(), RVLocs, *DAG.getContext());
2020 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2022 // Copy all of the result registers out of their specified physreg.
2023 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2024 CCValAssign &VA = RVLocs[i];
2025 EVT CopyVT = VA.getValVT();
2027 // If this is x86-64, and we disabled SSE, we can't return FP values
2028 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2029 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2030 report_fatal_error("SSE register return with SSE disabled");
2035 // If this is a call to a function that returns an fp value on the floating
2036 // point stack, we must guarantee the value is popped from the stack, so
2037 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2038 // if the return value is not used. We use the FpPOP_RETVAL instruction
2040 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2041 // If we prefer to use the value in xmm registers, copy it out as f80 and
2042 // use a truncate to move it from fp stack reg to xmm reg.
2043 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2044 SDValue Ops[] = { Chain, InFlag };
2045 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2046 MVT::Other, MVT::Glue, Ops), 1);
2047 Val = Chain.getValue(0);
2049 // Round the f80 to the right size, which also moves it to the appropriate
2051 if (CopyVT != VA.getValVT())
2052 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2053 // This truncation won't change the value.
2054 DAG.getIntPtrConstant(1));
2056 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2057 CopyVT, InFlag).getValue(1);
2058 Val = Chain.getValue(0);
2060 InFlag = Chain.getValue(2);
2061 InVals.push_back(Val);
2067 //===----------------------------------------------------------------------===//
2068 // C & StdCall & Fast Calling Convention implementation
2069 //===----------------------------------------------------------------------===//
2070 // StdCall calling convention seems to be standard for many Windows' API
2071 // routines and around. It differs from C calling convention just a little:
2072 // callee should clean up the stack, not caller. Symbols should be also
2073 // decorated in some fancy way :) It doesn't support any vector arguments.
2074 // For info on fast calling convention see Fast Calling Convention (tail call)
2075 // implementation LowerX86_32FastCCCallTo.
2077 /// CallIsStructReturn - Determines whether a call uses struct return
2079 enum StructReturnType {
2084 static StructReturnType
2085 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2087 return NotStructReturn;
2089 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2090 if (!Flags.isSRet())
2091 return NotStructReturn;
2092 if (Flags.isInReg())
2093 return RegStructReturn;
2094 return StackStructReturn;
2097 /// ArgsAreStructReturn - Determines whether a function uses struct
2098 /// return semantics.
2099 static StructReturnType
2100 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2102 return NotStructReturn;
2104 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2105 if (!Flags.isSRet())
2106 return NotStructReturn;
2107 if (Flags.isInReg())
2108 return RegStructReturn;
2109 return StackStructReturn;
2112 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2113 /// by "Src" to address "Dst" with size and alignment information specified by
2114 /// the specific parameter attribute. The copy will be passed as a byval
2115 /// function parameter.
2117 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2118 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2120 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2122 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2123 /*isVolatile*/false, /*AlwaysInline=*/true,
2124 MachinePointerInfo(), MachinePointerInfo());
2127 /// IsTailCallConvention - Return true if the calling convention is one that
2128 /// supports tail call optimization.
2129 static bool IsTailCallConvention(CallingConv::ID CC) {
2130 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2131 CC == CallingConv::HiPE);
2134 /// \brief Return true if the calling convention is a C calling convention.
2135 static bool IsCCallConvention(CallingConv::ID CC) {
2136 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2137 CC == CallingConv::X86_64_SysV);
2140 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2141 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2145 CallingConv::ID CalleeCC = CS.getCallingConv();
2146 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2152 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2153 /// a tailcall target by changing its ABI.
2154 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2155 bool GuaranteedTailCallOpt) {
2156 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2160 X86TargetLowering::LowerMemArgument(SDValue Chain,
2161 CallingConv::ID CallConv,
2162 const SmallVectorImpl<ISD::InputArg> &Ins,
2163 SDLoc dl, SelectionDAG &DAG,
2164 const CCValAssign &VA,
2165 MachineFrameInfo *MFI,
2167 // Create the nodes corresponding to a load from this parameter slot.
2168 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2169 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2170 getTargetMachine().Options.GuaranteedTailCallOpt);
2171 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2174 // If value is passed by pointer we have address passed instead of the value
2176 if (VA.getLocInfo() == CCValAssign::Indirect)
2177 ValVT = VA.getLocVT();
2179 ValVT = VA.getValVT();
2181 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2182 // changed with more analysis.
2183 // In case of tail call optimization mark all arguments mutable. Since they
2184 // could be overwritten by lowering of arguments in case of a tail call.
2185 if (Flags.isByVal()) {
2186 unsigned Bytes = Flags.getByValSize();
2187 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2188 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2189 return DAG.getFrameIndex(FI, getPointerTy());
2191 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2192 VA.getLocMemOffset(), isImmutable);
2193 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2194 return DAG.getLoad(ValVT, dl, Chain, FIN,
2195 MachinePointerInfo::getFixedStack(FI),
2196 false, false, false, 0);
2201 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2202 CallingConv::ID CallConv,
2204 const SmallVectorImpl<ISD::InputArg> &Ins,
2207 SmallVectorImpl<SDValue> &InVals)
2209 MachineFunction &MF = DAG.getMachineFunction();
2210 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2212 const Function* Fn = MF.getFunction();
2213 if (Fn->hasExternalLinkage() &&
2214 Subtarget->isTargetCygMing() &&
2215 Fn->getName() == "main")
2216 FuncInfo->setForceFramePointer(true);
2218 MachineFrameInfo *MFI = MF.getFrameInfo();
2219 bool Is64Bit = Subtarget->is64Bit();
2220 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2222 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2223 "Var args not supported with calling convention fastcc, ghc or hipe");
2225 // Assign locations to all of the incoming arguments.
2226 SmallVector<CCValAssign, 16> ArgLocs;
2227 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2228 ArgLocs, *DAG.getContext());
2230 // Allocate shadow area for Win64
2232 CCInfo.AllocateStack(32, 8);
2234 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2236 unsigned LastVal = ~0U;
2238 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2239 CCValAssign &VA = ArgLocs[i];
2240 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2242 assert(VA.getValNo() != LastVal &&
2243 "Don't support value assigned to multiple locs yet");
2245 LastVal = VA.getValNo();
2247 if (VA.isRegLoc()) {
2248 EVT RegVT = VA.getLocVT();
2249 const TargetRegisterClass *RC;
2250 if (RegVT == MVT::i32)
2251 RC = &X86::GR32RegClass;
2252 else if (Is64Bit && RegVT == MVT::i64)
2253 RC = &X86::GR64RegClass;
2254 else if (RegVT == MVT::f32)
2255 RC = &X86::FR32RegClass;
2256 else if (RegVT == MVT::f64)
2257 RC = &X86::FR64RegClass;
2258 else if (RegVT.is512BitVector())
2259 RC = &X86::VR512RegClass;
2260 else if (RegVT.is256BitVector())
2261 RC = &X86::VR256RegClass;
2262 else if (RegVT.is128BitVector())
2263 RC = &X86::VR128RegClass;
2264 else if (RegVT == MVT::x86mmx)
2265 RC = &X86::VR64RegClass;
2266 else if (RegVT == MVT::i1)
2267 RC = &X86::VK1RegClass;
2268 else if (RegVT == MVT::v8i1)
2269 RC = &X86::VK8RegClass;
2270 else if (RegVT == MVT::v16i1)
2271 RC = &X86::VK16RegClass;
2273 llvm_unreachable("Unknown argument type!");
2275 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2276 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2278 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2279 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2281 if (VA.getLocInfo() == CCValAssign::SExt)
2282 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2283 DAG.getValueType(VA.getValVT()));
2284 else if (VA.getLocInfo() == CCValAssign::ZExt)
2285 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2286 DAG.getValueType(VA.getValVT()));
2287 else if (VA.getLocInfo() == CCValAssign::BCvt)
2288 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2290 if (VA.isExtInLoc()) {
2291 // Handle MMX values passed in XMM regs.
2292 if (RegVT.isVector())
2293 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2295 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2298 assert(VA.isMemLoc());
2299 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2302 // If value is passed via pointer - do a load.
2303 if (VA.getLocInfo() == CCValAssign::Indirect)
2304 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2305 MachinePointerInfo(), false, false, false, 0);
2307 InVals.push_back(ArgValue);
2310 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2311 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2312 // The x86-64 ABIs require that for returning structs by value we copy
2313 // the sret argument into %rax/%eax (depending on ABI) for the return.
2314 // Win32 requires us to put the sret argument to %eax as well.
2315 // Save the argument into a virtual register so that we can access it
2316 // from the return points.
2317 if (Ins[i].Flags.isSRet()) {
2318 unsigned Reg = FuncInfo->getSRetReturnReg();
2320 MVT PtrTy = getPointerTy();
2321 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2322 FuncInfo->setSRetReturnReg(Reg);
2324 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2325 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2331 unsigned StackSize = CCInfo.getNextStackOffset();
2332 // Align stack specially for tail calls.
2333 if (FuncIsMadeTailCallSafe(CallConv,
2334 MF.getTarget().Options.GuaranteedTailCallOpt))
2335 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2337 // If the function takes variable number of arguments, make a frame index for
2338 // the start of the first vararg value... for expansion of llvm.va_start.
2340 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2341 CallConv != CallingConv::X86_ThisCall)) {
2342 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2345 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2347 // FIXME: We should really autogenerate these arrays
2348 static const MCPhysReg GPR64ArgRegsWin64[] = {
2349 X86::RCX, X86::RDX, X86::R8, X86::R9
2351 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2352 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2354 static const MCPhysReg XMMArgRegs64Bit[] = {
2355 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2356 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2358 const MCPhysReg *GPR64ArgRegs;
2359 unsigned NumXMMRegs = 0;
2362 // The XMM registers which might contain var arg parameters are shadowed
2363 // in their paired GPR. So we only need to save the GPR to their home
2365 TotalNumIntRegs = 4;
2366 GPR64ArgRegs = GPR64ArgRegsWin64;
2368 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2369 GPR64ArgRegs = GPR64ArgRegs64Bit;
2371 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2374 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2377 bool NoImplicitFloatOps = Fn->getAttributes().
2378 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2379 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2380 "SSE register cannot be used when SSE is disabled!");
2381 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2382 NoImplicitFloatOps) &&
2383 "SSE register cannot be used when SSE is disabled!");
2384 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2385 !Subtarget->hasSSE1())
2386 // Kernel mode asks for SSE to be disabled, so don't push them
2388 TotalNumXMMRegs = 0;
2391 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2392 // Get to the caller-allocated home save location. Add 8 to account
2393 // for the return address.
2394 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2395 FuncInfo->setRegSaveFrameIndex(
2396 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2397 // Fixup to set vararg frame on shadow area (4 x i64).
2399 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2401 // For X86-64, if there are vararg parameters that are passed via
2402 // registers, then we must store them to their spots on the stack so
2403 // they may be loaded by deferencing the result of va_next.
2404 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2405 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2406 FuncInfo->setRegSaveFrameIndex(
2407 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2411 // Store the integer parameter registers.
2412 SmallVector<SDValue, 8> MemOps;
2413 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2415 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2416 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2417 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2418 DAG.getIntPtrConstant(Offset));
2419 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2420 &X86::GR64RegClass);
2421 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2423 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2424 MachinePointerInfo::getFixedStack(
2425 FuncInfo->getRegSaveFrameIndex(), Offset),
2427 MemOps.push_back(Store);
2431 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2432 // Now store the XMM (fp + vector) parameter registers.
2433 SmallVector<SDValue, 11> SaveXMMOps;
2434 SaveXMMOps.push_back(Chain);
2436 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2437 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2438 SaveXMMOps.push_back(ALVal);
2440 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2441 FuncInfo->getRegSaveFrameIndex()));
2442 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2443 FuncInfo->getVarArgsFPOffset()));
2445 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2446 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2447 &X86::VR128RegClass);
2448 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2449 SaveXMMOps.push_back(Val);
2451 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2452 MVT::Other, SaveXMMOps));
2455 if (!MemOps.empty())
2456 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2460 // Some CCs need callee pop.
2461 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2462 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2463 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2465 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2466 // If this is an sret function, the return should pop the hidden pointer.
2467 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2468 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2469 argsAreStructReturn(Ins) == StackStructReturn)
2470 FuncInfo->setBytesToPopOnReturn(4);
2474 // RegSaveFrameIndex is X86-64 only.
2475 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2476 if (CallConv == CallingConv::X86_FastCall ||
2477 CallConv == CallingConv::X86_ThisCall)
2478 // fastcc functions can't have varargs.
2479 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2482 FuncInfo->setArgumentStackSize(StackSize);
2488 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2489 SDValue StackPtr, SDValue Arg,
2490 SDLoc dl, SelectionDAG &DAG,
2491 const CCValAssign &VA,
2492 ISD::ArgFlagsTy Flags) const {
2493 unsigned LocMemOffset = VA.getLocMemOffset();
2494 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2495 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2496 if (Flags.isByVal())
2497 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2499 return DAG.getStore(Chain, dl, Arg, PtrOff,
2500 MachinePointerInfo::getStack(LocMemOffset),
2504 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2505 /// optimization is performed and it is required.
2507 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2508 SDValue &OutRetAddr, SDValue Chain,
2509 bool IsTailCall, bool Is64Bit,
2510 int FPDiff, SDLoc dl) const {
2511 // Adjust the Return address stack slot.
2512 EVT VT = getPointerTy();
2513 OutRetAddr = getReturnAddressFrameIndex(DAG);
2515 // Load the "old" Return address.
2516 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2517 false, false, false, 0);
2518 return SDValue(OutRetAddr.getNode(), 1);
2521 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2522 /// optimization is performed and it is required (FPDiff!=0).
2523 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2524 SDValue Chain, SDValue RetAddrFrIdx,
2525 EVT PtrVT, unsigned SlotSize,
2526 int FPDiff, SDLoc dl) {
2527 // Store the return address to the appropriate stack slot.
2528 if (!FPDiff) return Chain;
2529 // Calculate the new stack slot for the return address.
2530 int NewReturnAddrFI =
2531 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2533 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2534 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2535 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2541 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2542 SmallVectorImpl<SDValue> &InVals) const {
2543 SelectionDAG &DAG = CLI.DAG;
2545 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2546 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2547 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2548 SDValue Chain = CLI.Chain;
2549 SDValue Callee = CLI.Callee;
2550 CallingConv::ID CallConv = CLI.CallConv;
2551 bool &isTailCall = CLI.IsTailCall;
2552 bool isVarArg = CLI.IsVarArg;
2554 MachineFunction &MF = DAG.getMachineFunction();
2555 bool Is64Bit = Subtarget->is64Bit();
2556 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2557 StructReturnType SR = callIsStructReturn(Outs);
2558 bool IsSibcall = false;
2560 if (MF.getTarget().Options.DisableTailCalls)
2563 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2565 // Force this to be a tail call. The verifier rules are enough to ensure
2566 // that we can lower this successfully without moving the return address
2569 } else if (isTailCall) {
2570 // Check if it's really possible to do a tail call.
2571 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2572 isVarArg, SR != NotStructReturn,
2573 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2574 Outs, OutVals, Ins, DAG);
2576 // Sibcalls are automatically detected tailcalls which do not require
2578 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2585 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2586 "Var args not supported with calling convention fastcc, ghc or hipe");
2588 // Analyze operands of the call, assigning locations to each operand.
2589 SmallVector<CCValAssign, 16> ArgLocs;
2590 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2591 ArgLocs, *DAG.getContext());
2593 // Allocate shadow area for Win64
2595 CCInfo.AllocateStack(32, 8);
2597 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2599 // Get a count of how many bytes are to be pushed on the stack.
2600 unsigned NumBytes = CCInfo.getNextStackOffset();
2602 // This is a sibcall. The memory operands are available in caller's
2603 // own caller's stack.
2605 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2606 IsTailCallConvention(CallConv))
2607 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2610 if (isTailCall && !IsSibcall && !IsMustTail) {
2611 // Lower arguments at fp - stackoffset + fpdiff.
2612 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2613 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2615 FPDiff = NumBytesCallerPushed - NumBytes;
2617 // Set the delta of movement of the returnaddr stackslot.
2618 // But only set if delta is greater than previous delta.
2619 if (FPDiff < X86Info->getTCReturnAddrDelta())
2620 X86Info->setTCReturnAddrDelta(FPDiff);
2623 unsigned NumBytesToPush = NumBytes;
2624 unsigned NumBytesToPop = NumBytes;
2626 // If we have an inalloca argument, all stack space has already been allocated
2627 // for us and be right at the top of the stack. We don't support multiple
2628 // arguments passed in memory when using inalloca.
2629 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2631 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2632 "an inalloca argument must be the only memory argument");
2636 Chain = DAG.getCALLSEQ_START(
2637 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2639 SDValue RetAddrFrIdx;
2640 // Load return address for tail calls.
2641 if (isTailCall && FPDiff)
2642 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2643 Is64Bit, FPDiff, dl);
2645 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2646 SmallVector<SDValue, 8> MemOpChains;
2649 // Walk the register/memloc assignments, inserting copies/loads. In the case
2650 // of tail call optimization arguments are handle later.
2651 const X86RegisterInfo *RegInfo =
2652 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2653 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2654 // Skip inalloca arguments, they have already been written.
2655 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2656 if (Flags.isInAlloca())
2659 CCValAssign &VA = ArgLocs[i];
2660 EVT RegVT = VA.getLocVT();
2661 SDValue Arg = OutVals[i];
2662 bool isByVal = Flags.isByVal();
2664 // Promote the value if needed.
2665 switch (VA.getLocInfo()) {
2666 default: llvm_unreachable("Unknown loc info!");
2667 case CCValAssign::Full: break;
2668 case CCValAssign::SExt:
2669 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2671 case CCValAssign::ZExt:
2672 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2674 case CCValAssign::AExt:
2675 if (RegVT.is128BitVector()) {
2676 // Special case: passing MMX values in XMM registers.
2677 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2678 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2679 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2681 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2683 case CCValAssign::BCvt:
2684 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2686 case CCValAssign::Indirect: {
2687 // Store the argument.
2688 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2689 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2690 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2691 MachinePointerInfo::getFixedStack(FI),
2698 if (VA.isRegLoc()) {
2699 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2700 if (isVarArg && IsWin64) {
2701 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2702 // shadow reg if callee is a varargs function.
2703 unsigned ShadowReg = 0;
2704 switch (VA.getLocReg()) {
2705 case X86::XMM0: ShadowReg = X86::RCX; break;
2706 case X86::XMM1: ShadowReg = X86::RDX; break;
2707 case X86::XMM2: ShadowReg = X86::R8; break;
2708 case X86::XMM3: ShadowReg = X86::R9; break;
2711 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2713 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2714 assert(VA.isMemLoc());
2715 if (!StackPtr.getNode())
2716 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2718 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2719 dl, DAG, VA, Flags));
2723 if (!MemOpChains.empty())
2724 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2726 if (Subtarget->isPICStyleGOT()) {
2727 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2730 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2731 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2733 // If we are tail calling and generating PIC/GOT style code load the
2734 // address of the callee into ECX. The value in ecx is used as target of
2735 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2736 // for tail calls on PIC/GOT architectures. Normally we would just put the
2737 // address of GOT into ebx and then call target@PLT. But for tail calls
2738 // ebx would be restored (since ebx is callee saved) before jumping to the
2741 // Note: The actual moving to ECX is done further down.
2742 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2743 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2744 !G->getGlobal()->hasProtectedVisibility())
2745 Callee = LowerGlobalAddress(Callee, DAG);
2746 else if (isa<ExternalSymbolSDNode>(Callee))
2747 Callee = LowerExternalSymbol(Callee, DAG);
2751 if (Is64Bit && isVarArg && !IsWin64) {
2752 // From AMD64 ABI document:
2753 // For calls that may call functions that use varargs or stdargs
2754 // (prototype-less calls or calls to functions containing ellipsis (...) in
2755 // the declaration) %al is used as hidden argument to specify the number
2756 // of SSE registers used. The contents of %al do not need to match exactly
2757 // the number of registers, but must be an ubound on the number of SSE
2758 // registers used and is in the range 0 - 8 inclusive.
2760 // Count the number of XMM registers allocated.
2761 static const MCPhysReg XMMArgRegs[] = {
2762 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2763 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2765 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2766 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2767 && "SSE registers cannot be used when SSE is disabled");
2769 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2770 DAG.getConstant(NumXMMRegs, MVT::i8)));
2773 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2774 // don't need this because the eligibility check rejects calls that require
2775 // shuffling arguments passed in memory.
2776 if (!IsSibcall && isTailCall) {
2777 // Force all the incoming stack arguments to be loaded from the stack
2778 // before any new outgoing arguments are stored to the stack, because the
2779 // outgoing stack slots may alias the incoming argument stack slots, and
2780 // the alias isn't otherwise explicit. This is slightly more conservative
2781 // than necessary, because it means that each store effectively depends
2782 // on every argument instead of just those arguments it would clobber.
2783 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2785 SmallVector<SDValue, 8> MemOpChains2;
2788 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2789 CCValAssign &VA = ArgLocs[i];
2792 assert(VA.isMemLoc());
2793 SDValue Arg = OutVals[i];
2794 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2795 // Skip inalloca arguments. They don't require any work.
2796 if (Flags.isInAlloca())
2798 // Create frame index.
2799 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2800 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2801 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2802 FIN = DAG.getFrameIndex(FI, getPointerTy());
2804 if (Flags.isByVal()) {
2805 // Copy relative to framepointer.
2806 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2807 if (!StackPtr.getNode())
2808 StackPtr = DAG.getCopyFromReg(Chain, dl,
2809 RegInfo->getStackRegister(),
2811 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2813 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2817 // Store relative to framepointer.
2818 MemOpChains2.push_back(
2819 DAG.getStore(ArgChain, dl, Arg, FIN,
2820 MachinePointerInfo::getFixedStack(FI),
2825 if (!MemOpChains2.empty())
2826 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2828 // Store the return address to the appropriate stack slot.
2829 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2830 getPointerTy(), RegInfo->getSlotSize(),
2834 // Build a sequence of copy-to-reg nodes chained together with token chain
2835 // and flag operands which copy the outgoing args into registers.
2837 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2838 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2839 RegsToPass[i].second, InFlag);
2840 InFlag = Chain.getValue(1);
2843 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2844 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2845 // In the 64-bit large code model, we have to make all calls
2846 // through a register, since the call instruction's 32-bit
2847 // pc-relative offset may not be large enough to hold the whole
2849 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2850 // If the callee is a GlobalAddress node (quite common, every direct call
2851 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2854 // We should use extra load for direct calls to dllimported functions in
2856 const GlobalValue *GV = G->getGlobal();
2857 if (!GV->hasDLLImportStorageClass()) {
2858 unsigned char OpFlags = 0;
2859 bool ExtraLoad = false;
2860 unsigned WrapperKind = ISD::DELETED_NODE;
2862 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2863 // external symbols most go through the PLT in PIC mode. If the symbol
2864 // has hidden or protected visibility, or if it is static or local, then
2865 // we don't need to use the PLT - we can directly call it.
2866 if (Subtarget->isTargetELF() &&
2867 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2868 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2869 OpFlags = X86II::MO_PLT;
2870 } else if (Subtarget->isPICStyleStubAny() &&
2871 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2872 (!Subtarget->getTargetTriple().isMacOSX() ||
2873 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2874 // PC-relative references to external symbols should go through $stub,
2875 // unless we're building with the leopard linker or later, which
2876 // automatically synthesizes these stubs.
2877 OpFlags = X86II::MO_DARWIN_STUB;
2878 } else if (Subtarget->isPICStyleRIPRel() &&
2879 isa<Function>(GV) &&
2880 cast<Function>(GV)->getAttributes().
2881 hasAttribute(AttributeSet::FunctionIndex,
2882 Attribute::NonLazyBind)) {
2883 // If the function is marked as non-lazy, generate an indirect call
2884 // which loads from the GOT directly. This avoids runtime overhead
2885 // at the cost of eager binding (and one extra byte of encoding).
2886 OpFlags = X86II::MO_GOTPCREL;
2887 WrapperKind = X86ISD::WrapperRIP;
2891 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2892 G->getOffset(), OpFlags);
2894 // Add a wrapper if needed.
2895 if (WrapperKind != ISD::DELETED_NODE)
2896 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2897 // Add extra indirection if needed.
2899 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2900 MachinePointerInfo::getGOT(),
2901 false, false, false, 0);
2903 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2904 unsigned char OpFlags = 0;
2906 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2907 // external symbols should go through the PLT.
2908 if (Subtarget->isTargetELF() &&
2909 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2910 OpFlags = X86II::MO_PLT;
2911 } else if (Subtarget->isPICStyleStubAny() &&
2912 (!Subtarget->getTargetTriple().isMacOSX() ||
2913 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2914 // PC-relative references to external symbols should go through $stub,
2915 // unless we're building with the leopard linker or later, which
2916 // automatically synthesizes these stubs.
2917 OpFlags = X86II::MO_DARWIN_STUB;
2920 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2924 // Returns a chain & a flag for retval copy to use.
2925 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2926 SmallVector<SDValue, 8> Ops;
2928 if (!IsSibcall && isTailCall) {
2929 Chain = DAG.getCALLSEQ_END(Chain,
2930 DAG.getIntPtrConstant(NumBytesToPop, true),
2931 DAG.getIntPtrConstant(0, true), InFlag, dl);
2932 InFlag = Chain.getValue(1);
2935 Ops.push_back(Chain);
2936 Ops.push_back(Callee);
2939 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2941 // Add argument registers to the end of the list so that they are known live
2943 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2944 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2945 RegsToPass[i].second.getValueType()));
2947 // Add a register mask operand representing the call-preserved registers.
2948 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2949 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2950 assert(Mask && "Missing call preserved mask for calling convention");
2951 Ops.push_back(DAG.getRegisterMask(Mask));
2953 if (InFlag.getNode())
2954 Ops.push_back(InFlag);
2958 //// If this is the first return lowered for this function, add the regs
2959 //// to the liveout set for the function.
2960 // This isn't right, although it's probably harmless on x86; liveouts
2961 // should be computed from returns not tail calls. Consider a void
2962 // function making a tail call to a function returning int.
2963 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2966 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2967 InFlag = Chain.getValue(1);
2969 // Create the CALLSEQ_END node.
2970 unsigned NumBytesForCalleeToPop;
2971 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2972 getTargetMachine().Options.GuaranteedTailCallOpt))
2973 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2974 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2975 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2976 SR == StackStructReturn)
2977 // If this is a call to a struct-return function, the callee
2978 // pops the hidden struct pointer, so we have to push it back.
2979 // This is common for Darwin/X86, Linux & Mingw32 targets.
2980 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2981 NumBytesForCalleeToPop = 4;
2983 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2985 // Returns a flag for retval copy to use.
2987 Chain = DAG.getCALLSEQ_END(Chain,
2988 DAG.getIntPtrConstant(NumBytesToPop, true),
2989 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2992 InFlag = Chain.getValue(1);
2995 // Handle result values, copying them out of physregs into vregs that we
2997 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2998 Ins, dl, DAG, InVals);
3001 //===----------------------------------------------------------------------===//
3002 // Fast Calling Convention (tail call) implementation
3003 //===----------------------------------------------------------------------===//
3005 // Like std call, callee cleans arguments, convention except that ECX is
3006 // reserved for storing the tail called function address. Only 2 registers are
3007 // free for argument passing (inreg). Tail call optimization is performed
3009 // * tailcallopt is enabled
3010 // * caller/callee are fastcc
3011 // On X86_64 architecture with GOT-style position independent code only local
3012 // (within module) calls are supported at the moment.
3013 // To keep the stack aligned according to platform abi the function
3014 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3015 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3016 // If a tail called function callee has more arguments than the caller the
3017 // caller needs to make sure that there is room to move the RETADDR to. This is
3018 // achieved by reserving an area the size of the argument delta right after the
3019 // original REtADDR, but before the saved framepointer or the spilled registers
3020 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3032 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3033 /// for a 16 byte align requirement.
3035 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3036 SelectionDAG& DAG) const {
3037 MachineFunction &MF = DAG.getMachineFunction();
3038 const TargetMachine &TM = MF.getTarget();
3039 const X86RegisterInfo *RegInfo =
3040 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3041 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3042 unsigned StackAlignment = TFI.getStackAlignment();
3043 uint64_t AlignMask = StackAlignment - 1;
3044 int64_t Offset = StackSize;
3045 unsigned SlotSize = RegInfo->getSlotSize();
3046 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3047 // Number smaller than 12 so just add the difference.
3048 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3050 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3051 Offset = ((~AlignMask) & Offset) + StackAlignment +
3052 (StackAlignment-SlotSize);
3057 /// MatchingStackOffset - Return true if the given stack call argument is
3058 /// already available in the same position (relatively) of the caller's
3059 /// incoming argument stack.
3061 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3062 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3063 const X86InstrInfo *TII) {
3064 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3066 if (Arg.getOpcode() == ISD::CopyFromReg) {
3067 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3068 if (!TargetRegisterInfo::isVirtualRegister(VR))
3070 MachineInstr *Def = MRI->getVRegDef(VR);
3073 if (!Flags.isByVal()) {
3074 if (!TII->isLoadFromStackSlot(Def, FI))
3077 unsigned Opcode = Def->getOpcode();
3078 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3079 Def->getOperand(1).isFI()) {
3080 FI = Def->getOperand(1).getIndex();
3081 Bytes = Flags.getByValSize();
3085 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3086 if (Flags.isByVal())
3087 // ByVal argument is passed in as a pointer but it's now being
3088 // dereferenced. e.g.
3089 // define @foo(%struct.X* %A) {
3090 // tail call @bar(%struct.X* byval %A)
3093 SDValue Ptr = Ld->getBasePtr();
3094 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3097 FI = FINode->getIndex();
3098 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3099 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3100 FI = FINode->getIndex();
3101 Bytes = Flags.getByValSize();
3105 assert(FI != INT_MAX);
3106 if (!MFI->isFixedObjectIndex(FI))
3108 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3111 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3112 /// for tail call optimization. Targets which want to do tail call
3113 /// optimization should implement this function.
3115 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3116 CallingConv::ID CalleeCC,
3118 bool isCalleeStructRet,
3119 bool isCallerStructRet,
3121 const SmallVectorImpl<ISD::OutputArg> &Outs,
3122 const SmallVectorImpl<SDValue> &OutVals,
3123 const SmallVectorImpl<ISD::InputArg> &Ins,
3124 SelectionDAG &DAG) const {
3125 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3128 // If -tailcallopt is specified, make fastcc functions tail-callable.
3129 const MachineFunction &MF = DAG.getMachineFunction();
3130 const Function *CallerF = MF.getFunction();
3132 // If the function return type is x86_fp80 and the callee return type is not,
3133 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3134 // perform a tailcall optimization here.
3135 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3138 CallingConv::ID CallerCC = CallerF->getCallingConv();
3139 bool CCMatch = CallerCC == CalleeCC;
3140 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3141 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3143 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3144 if (IsTailCallConvention(CalleeCC) && CCMatch)
3149 // Look for obvious safe cases to perform tail call optimization that do not
3150 // require ABI changes. This is what gcc calls sibcall.
3152 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3153 // emit a special epilogue.
3154 const X86RegisterInfo *RegInfo =
3155 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3156 if (RegInfo->needsStackRealignment(MF))
3159 // Also avoid sibcall optimization if either caller or callee uses struct
3160 // return semantics.
3161 if (isCalleeStructRet || isCallerStructRet)
3164 // An stdcall/thiscall caller is expected to clean up its arguments; the
3165 // callee isn't going to do that.
3166 // FIXME: this is more restrictive than needed. We could produce a tailcall
3167 // when the stack adjustment matches. For example, with a thiscall that takes
3168 // only one argument.
3169 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3170 CallerCC == CallingConv::X86_ThisCall))
3173 // Do not sibcall optimize vararg calls unless all arguments are passed via
3175 if (isVarArg && !Outs.empty()) {
3177 // Optimizing for varargs on Win64 is unlikely to be safe without
3178 // additional testing.
3179 if (IsCalleeWin64 || IsCallerWin64)
3182 SmallVector<CCValAssign, 16> ArgLocs;
3183 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3184 getTargetMachine(), ArgLocs, *DAG.getContext());
3186 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3187 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3188 if (!ArgLocs[i].isRegLoc())
3192 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3193 // stack. Therefore, if it's not used by the call it is not safe to optimize
3194 // this into a sibcall.
3195 bool Unused = false;
3196 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3203 SmallVector<CCValAssign, 16> RVLocs;
3204 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3205 getTargetMachine(), RVLocs, *DAG.getContext());
3206 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3207 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3208 CCValAssign &VA = RVLocs[i];
3209 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3214 // If the calling conventions do not match, then we'd better make sure the
3215 // results are returned in the same way as what the caller expects.
3217 SmallVector<CCValAssign, 16> RVLocs1;
3218 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3219 getTargetMachine(), RVLocs1, *DAG.getContext());
3220 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3222 SmallVector<CCValAssign, 16> RVLocs2;
3223 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3224 getTargetMachine(), RVLocs2, *DAG.getContext());
3225 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3227 if (RVLocs1.size() != RVLocs2.size())
3229 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3230 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3232 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3234 if (RVLocs1[i].isRegLoc()) {
3235 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3238 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3244 // If the callee takes no arguments then go on to check the results of the
3246 if (!Outs.empty()) {
3247 // Check if stack adjustment is needed. For now, do not do this if any
3248 // argument is passed on the stack.
3249 SmallVector<CCValAssign, 16> ArgLocs;
3250 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3251 getTargetMachine(), ArgLocs, *DAG.getContext());
3253 // Allocate shadow area for Win64
3255 CCInfo.AllocateStack(32, 8);
3257 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3258 if (CCInfo.getNextStackOffset()) {
3259 MachineFunction &MF = DAG.getMachineFunction();
3260 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3263 // Check if the arguments are already laid out in the right way as
3264 // the caller's fixed stack objects.
3265 MachineFrameInfo *MFI = MF.getFrameInfo();
3266 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3267 const X86InstrInfo *TII =
3268 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3269 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3270 CCValAssign &VA = ArgLocs[i];
3271 SDValue Arg = OutVals[i];
3272 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3273 if (VA.getLocInfo() == CCValAssign::Indirect)
3275 if (!VA.isRegLoc()) {
3276 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3283 // If the tailcall address may be in a register, then make sure it's
3284 // possible to register allocate for it. In 32-bit, the call address can
3285 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3286 // callee-saved registers are restored. These happen to be the same
3287 // registers used to pass 'inreg' arguments so watch out for those.
3288 if (!Subtarget->is64Bit() &&
3289 ((!isa<GlobalAddressSDNode>(Callee) &&
3290 !isa<ExternalSymbolSDNode>(Callee)) ||
3291 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3292 unsigned NumInRegs = 0;
3293 // In PIC we need an extra register to formulate the address computation
3295 unsigned MaxInRegs =
3296 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3298 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3299 CCValAssign &VA = ArgLocs[i];
3302 unsigned Reg = VA.getLocReg();
3305 case X86::EAX: case X86::EDX: case X86::ECX:
3306 if (++NumInRegs == MaxInRegs)
3318 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3319 const TargetLibraryInfo *libInfo) const {
3320 return X86::createFastISel(funcInfo, libInfo);
3323 //===----------------------------------------------------------------------===//
3324 // Other Lowering Hooks
3325 //===----------------------------------------------------------------------===//
3327 static bool MayFoldLoad(SDValue Op) {
3328 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3331 static bool MayFoldIntoStore(SDValue Op) {
3332 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3335 static bool isTargetShuffle(unsigned Opcode) {
3337 default: return false;
3338 case X86ISD::PSHUFD:
3339 case X86ISD::PSHUFHW:
3340 case X86ISD::PSHUFLW:
3342 case X86ISD::PALIGNR:
3343 case X86ISD::MOVLHPS:
3344 case X86ISD::MOVLHPD:
3345 case X86ISD::MOVHLPS:
3346 case X86ISD::MOVLPS:
3347 case X86ISD::MOVLPD:
3348 case X86ISD::MOVSHDUP:
3349 case X86ISD::MOVSLDUP:
3350 case X86ISD::MOVDDUP:
3353 case X86ISD::UNPCKL:
3354 case X86ISD::UNPCKH:
3355 case X86ISD::VPERMILP:
3356 case X86ISD::VPERM2X128:
3357 case X86ISD::VPERMI:
3362 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3363 SDValue V1, SelectionDAG &DAG) {
3365 default: llvm_unreachable("Unknown x86 shuffle node");
3366 case X86ISD::MOVSHDUP:
3367 case X86ISD::MOVSLDUP:
3368 case X86ISD::MOVDDUP:
3369 return DAG.getNode(Opc, dl, VT, V1);
3373 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3374 SDValue V1, unsigned TargetMask,
3375 SelectionDAG &DAG) {
3377 default: llvm_unreachable("Unknown x86 shuffle node");
3378 case X86ISD::PSHUFD:
3379 case X86ISD::PSHUFHW:
3380 case X86ISD::PSHUFLW:
3381 case X86ISD::VPERMILP:
3382 case X86ISD::VPERMI:
3383 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3387 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3388 SDValue V1, SDValue V2, unsigned TargetMask,
3389 SelectionDAG &DAG) {
3391 default: llvm_unreachable("Unknown x86 shuffle node");
3392 case X86ISD::PALIGNR:
3394 case X86ISD::VPERM2X128:
3395 return DAG.getNode(Opc, dl, VT, V1, V2,
3396 DAG.getConstant(TargetMask, MVT::i8));
3400 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3401 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3403 default: llvm_unreachable("Unknown x86 shuffle node");
3404 case X86ISD::MOVLHPS:
3405 case X86ISD::MOVLHPD:
3406 case X86ISD::MOVHLPS:
3407 case X86ISD::MOVLPS:
3408 case X86ISD::MOVLPD:
3411 case X86ISD::UNPCKL:
3412 case X86ISD::UNPCKH:
3413 return DAG.getNode(Opc, dl, VT, V1, V2);
3417 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3418 MachineFunction &MF = DAG.getMachineFunction();
3419 const X86RegisterInfo *RegInfo =
3420 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3421 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3422 int ReturnAddrIndex = FuncInfo->getRAIndex();
3424 if (ReturnAddrIndex == 0) {
3425 // Set up a frame object for the return address.
3426 unsigned SlotSize = RegInfo->getSlotSize();
3427 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3430 FuncInfo->setRAIndex(ReturnAddrIndex);
3433 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3436 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3437 bool hasSymbolicDisplacement) {
3438 // Offset should fit into 32 bit immediate field.
3439 if (!isInt<32>(Offset))
3442 // If we don't have a symbolic displacement - we don't have any extra
3444 if (!hasSymbolicDisplacement)
3447 // FIXME: Some tweaks might be needed for medium code model.
3448 if (M != CodeModel::Small && M != CodeModel::Kernel)
3451 // For small code model we assume that latest object is 16MB before end of 31
3452 // bits boundary. We may also accept pretty large negative constants knowing
3453 // that all objects are in the positive half of address space.
3454 if (M == CodeModel::Small && Offset < 16*1024*1024)
3457 // For kernel code model we know that all object resist in the negative half
3458 // of 32bits address space. We may not accept negative offsets, since they may
3459 // be just off and we may accept pretty large positive ones.
3460 if (M == CodeModel::Kernel && Offset > 0)
3466 /// isCalleePop - Determines whether the callee is required to pop its
3467 /// own arguments. Callee pop is necessary to support tail calls.
3468 bool X86::isCalleePop(CallingConv::ID CallingConv,
3469 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3473 switch (CallingConv) {
3476 case CallingConv::X86_StdCall:
3478 case CallingConv::X86_FastCall:
3480 case CallingConv::X86_ThisCall:
3482 case CallingConv::Fast:
3484 case CallingConv::GHC:
3486 case CallingConv::HiPE:
3491 /// \brief Return true if the condition is an unsigned comparison operation.
3492 static bool isX86CCUnsigned(unsigned X86CC) {
3494 default: llvm_unreachable("Invalid integer condition!");
3495 case X86::COND_E: return true;
3496 case X86::COND_G: return false;
3497 case X86::COND_GE: return false;
3498 case X86::COND_L: return false;
3499 case X86::COND_LE: return false;
3500 case X86::COND_NE: return true;
3501 case X86::COND_B: return true;
3502 case X86::COND_A: return true;
3503 case X86::COND_BE: return true;
3504 case X86::COND_AE: return true;
3506 llvm_unreachable("covered switch fell through?!");
3509 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3510 /// specific condition code, returning the condition code and the LHS/RHS of the
3511 /// comparison to make.
3512 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3513 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3515 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3516 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3517 // X > -1 -> X == 0, jump !sign.
3518 RHS = DAG.getConstant(0, RHS.getValueType());
3519 return X86::COND_NS;
3521 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3522 // X < 0 -> X == 0, jump on sign.
3525 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3527 RHS = DAG.getConstant(0, RHS.getValueType());
3528 return X86::COND_LE;
3532 switch (SetCCOpcode) {
3533 default: llvm_unreachable("Invalid integer condition!");
3534 case ISD::SETEQ: return X86::COND_E;
3535 case ISD::SETGT: return X86::COND_G;
3536 case ISD::SETGE: return X86::COND_GE;
3537 case ISD::SETLT: return X86::COND_L;
3538 case ISD::SETLE: return X86::COND_LE;
3539 case ISD::SETNE: return X86::COND_NE;
3540 case ISD::SETULT: return X86::COND_B;
3541 case ISD::SETUGT: return X86::COND_A;
3542 case ISD::SETULE: return X86::COND_BE;
3543 case ISD::SETUGE: return X86::COND_AE;
3547 // First determine if it is required or is profitable to flip the operands.
3549 // If LHS is a foldable load, but RHS is not, flip the condition.
3550 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3551 !ISD::isNON_EXTLoad(RHS.getNode())) {
3552 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3553 std::swap(LHS, RHS);
3556 switch (SetCCOpcode) {
3562 std::swap(LHS, RHS);
3566 // On a floating point condition, the flags are set as follows:
3568 // 0 | 0 | 0 | X > Y
3569 // 0 | 0 | 1 | X < Y
3570 // 1 | 0 | 0 | X == Y
3571 // 1 | 1 | 1 | unordered
3572 switch (SetCCOpcode) {
3573 default: llvm_unreachable("Condcode should be pre-legalized away");
3575 case ISD::SETEQ: return X86::COND_E;
3576 case ISD::SETOLT: // flipped
3578 case ISD::SETGT: return X86::COND_A;
3579 case ISD::SETOLE: // flipped
3581 case ISD::SETGE: return X86::COND_AE;
3582 case ISD::SETUGT: // flipped
3584 case ISD::SETLT: return X86::COND_B;
3585 case ISD::SETUGE: // flipped
3587 case ISD::SETLE: return X86::COND_BE;
3589 case ISD::SETNE: return X86::COND_NE;
3590 case ISD::SETUO: return X86::COND_P;
3591 case ISD::SETO: return X86::COND_NP;
3593 case ISD::SETUNE: return X86::COND_INVALID;
3597 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3598 /// code. Current x86 isa includes the following FP cmov instructions:
3599 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3600 static bool hasFPCMov(unsigned X86CC) {
3616 /// isFPImmLegal - Returns true if the target can instruction select the
3617 /// specified FP immediate natively. If false, the legalizer will
3618 /// materialize the FP immediate as a load from a constant pool.
3619 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3620 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3621 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3627 /// \brief Returns true if it is beneficial to convert a load of a constant
3628 /// to just the constant itself.
3629 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3631 assert(Ty->isIntegerTy());
3633 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3634 if (BitSize == 0 || BitSize > 64)
3639 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3640 /// the specified range (L, H].
3641 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3642 return (Val < 0) || (Val >= Low && Val < Hi);
3645 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3646 /// specified value.
3647 static bool isUndefOrEqual(int Val, int CmpVal) {
3648 return (Val < 0 || Val == CmpVal);
3651 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3652 /// from position Pos and ending in Pos+Size, falls within the specified
3653 /// sequential range (L, L+Pos]. or is undef.
3654 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3655 unsigned Pos, unsigned Size, int Low) {
3656 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3657 if (!isUndefOrEqual(Mask[i], Low))
3662 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3663 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3664 /// the second operand.
3665 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3666 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3667 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3668 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3669 return (Mask[0] < 2 && Mask[1] < 2);
3673 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3674 /// is suitable for input to PSHUFHW.
3675 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3676 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3679 // Lower quadword copied in order or undef.
3680 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3683 // Upper quadword shuffled.
3684 for (unsigned i = 4; i != 8; ++i)
3685 if (!isUndefOrInRange(Mask[i], 4, 8))
3688 if (VT == MVT::v16i16) {
3689 // Lower quadword copied in order or undef.
3690 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3693 // Upper quadword shuffled.
3694 for (unsigned i = 12; i != 16; ++i)
3695 if (!isUndefOrInRange(Mask[i], 12, 16))
3702 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3703 /// is suitable for input to PSHUFLW.
3704 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3705 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3708 // Upper quadword copied in order.
3709 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3712 // Lower quadword shuffled.
3713 for (unsigned i = 0; i != 4; ++i)
3714 if (!isUndefOrInRange(Mask[i], 0, 4))
3717 if (VT == MVT::v16i16) {
3718 // Upper quadword copied in order.
3719 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3722 // Lower quadword shuffled.
3723 for (unsigned i = 8; i != 12; ++i)
3724 if (!isUndefOrInRange(Mask[i], 8, 12))
3731 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3732 /// is suitable for input to PALIGNR.
3733 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3734 const X86Subtarget *Subtarget) {
3735 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3736 (VT.is256BitVector() && !Subtarget->hasInt256()))
3739 unsigned NumElts = VT.getVectorNumElements();
3740 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3741 unsigned NumLaneElts = NumElts/NumLanes;
3743 // Do not handle 64-bit element shuffles with palignr.
3744 if (NumLaneElts == 2)
3747 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3749 for (i = 0; i != NumLaneElts; ++i) {
3754 // Lane is all undef, go to next lane
3755 if (i == NumLaneElts)
3758 int Start = Mask[i+l];
3760 // Make sure its in this lane in one of the sources
3761 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3762 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3765 // If not lane 0, then we must match lane 0
3766 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3769 // Correct second source to be contiguous with first source
3770 if (Start >= (int)NumElts)
3771 Start -= NumElts - NumLaneElts;
3773 // Make sure we're shifting in the right direction.
3774 if (Start <= (int)(i+l))
3779 // Check the rest of the elements to see if they are consecutive.
3780 for (++i; i != NumLaneElts; ++i) {
3781 int Idx = Mask[i+l];
3783 // Make sure its in this lane
3784 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3785 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3788 // If not lane 0, then we must match lane 0
3789 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3792 if (Idx >= (int)NumElts)
3793 Idx -= NumElts - NumLaneElts;
3795 if (!isUndefOrEqual(Idx, Start+i))
3804 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3805 /// the two vector operands have swapped position.
3806 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3807 unsigned NumElems) {
3808 for (unsigned i = 0; i != NumElems; ++i) {
3812 else if (idx < (int)NumElems)
3813 Mask[i] = idx + NumElems;
3815 Mask[i] = idx - NumElems;
3819 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3820 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3821 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3822 /// reverse of what x86 shuffles want.
3823 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3825 unsigned NumElems = VT.getVectorNumElements();
3826 unsigned NumLanes = VT.getSizeInBits()/128;
3827 unsigned NumLaneElems = NumElems/NumLanes;
3829 if (NumLaneElems != 2 && NumLaneElems != 4)
3832 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3833 bool symetricMaskRequired =
3834 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3836 // VSHUFPSY divides the resulting vector into 4 chunks.
3837 // The sources are also splitted into 4 chunks, and each destination
3838 // chunk must come from a different source chunk.
3840 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3841 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3843 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3844 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3846 // VSHUFPDY divides the resulting vector into 4 chunks.
3847 // The sources are also splitted into 4 chunks, and each destination
3848 // chunk must come from a different source chunk.
3850 // SRC1 => X3 X2 X1 X0
3851 // SRC2 => Y3 Y2 Y1 Y0
3853 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3855 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3856 unsigned HalfLaneElems = NumLaneElems/2;
3857 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3858 for (unsigned i = 0; i != NumLaneElems; ++i) {
3859 int Idx = Mask[i+l];
3860 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3861 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3863 // For VSHUFPSY, the mask of the second half must be the same as the
3864 // first but with the appropriate offsets. This works in the same way as
3865 // VPERMILPS works with masks.
3866 if (!symetricMaskRequired || Idx < 0)
3868 if (MaskVal[i] < 0) {
3869 MaskVal[i] = Idx - l;
3872 if ((signed)(Idx - l) != MaskVal[i])
3880 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3881 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3882 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3883 if (!VT.is128BitVector())
3886 unsigned NumElems = VT.getVectorNumElements();
3891 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3892 return isUndefOrEqual(Mask[0], 6) &&
3893 isUndefOrEqual(Mask[1], 7) &&
3894 isUndefOrEqual(Mask[2], 2) &&
3895 isUndefOrEqual(Mask[3], 3);
3898 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3899 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3901 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3902 if (!VT.is128BitVector())
3905 unsigned NumElems = VT.getVectorNumElements();
3910 return isUndefOrEqual(Mask[0], 2) &&
3911 isUndefOrEqual(Mask[1], 3) &&
3912 isUndefOrEqual(Mask[2], 2) &&
3913 isUndefOrEqual(Mask[3], 3);
3916 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3917 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3918 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3919 if (!VT.is128BitVector())
3922 unsigned NumElems = VT.getVectorNumElements();
3924 if (NumElems != 2 && NumElems != 4)
3927 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3928 if (!isUndefOrEqual(Mask[i], i + NumElems))
3931 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3932 if (!isUndefOrEqual(Mask[i], i))
3938 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3939 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3940 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3941 if (!VT.is128BitVector())
3944 unsigned NumElems = VT.getVectorNumElements();
3946 if (NumElems != 2 && NumElems != 4)
3949 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3950 if (!isUndefOrEqual(Mask[i], i))
3953 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3954 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3960 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3961 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3962 /// i. e: If all but one element come from the same vector.
3963 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3964 // TODO: Deal with AVX's VINSERTPS
3965 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3968 unsigned CorrectPosV1 = 0;
3969 unsigned CorrectPosV2 = 0;
3970 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3973 else if (Mask[i] == i + 4)
3976 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3977 // We have 3 elements from one vector, and one from another.
3984 // Some special combinations that can be optimized.
3987 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3988 SelectionDAG &DAG) {
3989 MVT VT = SVOp->getSimpleValueType(0);
3992 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3995 ArrayRef<int> Mask = SVOp->getMask();
3997 // These are the special masks that may be optimized.
3998 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3999 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4000 bool MatchEvenMask = true;
4001 bool MatchOddMask = true;
4002 for (int i=0; i<8; ++i) {
4003 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4004 MatchEvenMask = false;
4005 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4006 MatchOddMask = false;
4009 if (!MatchEvenMask && !MatchOddMask)
4012 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4014 SDValue Op0 = SVOp->getOperand(0);
4015 SDValue Op1 = SVOp->getOperand(1);
4017 if (MatchEvenMask) {
4018 // Shift the second operand right to 32 bits.
4019 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4020 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4022 // Shift the first operand left to 32 bits.
4023 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4024 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4026 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4027 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4030 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4031 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4032 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4033 bool HasInt256, bool V2IsSplat = false) {
4035 assert(VT.getSizeInBits() >= 128 &&
4036 "Unsupported vector type for unpckl");
4038 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4040 unsigned NumOf256BitLanes;
4041 unsigned NumElts = VT.getVectorNumElements();
4042 if (VT.is256BitVector()) {
4043 if (NumElts != 4 && NumElts != 8 &&
4044 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4047 NumOf256BitLanes = 1;
4048 } else if (VT.is512BitVector()) {
4049 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4050 "Unsupported vector type for unpckh");
4052 NumOf256BitLanes = 2;
4055 NumOf256BitLanes = 1;
4058 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4059 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4061 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4062 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4063 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4064 int BitI = Mask[l256*NumEltsInStride+l+i];
4065 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4066 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4068 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4070 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4078 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4079 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4080 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4081 bool HasInt256, bool V2IsSplat = false) {
4082 assert(VT.getSizeInBits() >= 128 &&
4083 "Unsupported vector type for unpckh");
4085 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4087 unsigned NumOf256BitLanes;
4088 unsigned NumElts = VT.getVectorNumElements();
4089 if (VT.is256BitVector()) {
4090 if (NumElts != 4 && NumElts != 8 &&
4091 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4094 NumOf256BitLanes = 1;
4095 } else if (VT.is512BitVector()) {
4096 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4097 "Unsupported vector type for unpckh");
4099 NumOf256BitLanes = 2;
4102 NumOf256BitLanes = 1;
4105 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4106 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4108 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4109 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4110 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4111 int BitI = Mask[l256*NumEltsInStride+l+i];
4112 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4113 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4115 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4117 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4125 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4126 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4128 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4129 unsigned NumElts = VT.getVectorNumElements();
4130 bool Is256BitVec = VT.is256BitVector();
4132 if (VT.is512BitVector())
4134 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4135 "Unsupported vector type for unpckh");
4137 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4138 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4141 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4142 // FIXME: Need a better way to get rid of this, there's no latency difference
4143 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4144 // the former later. We should also remove the "_undef" special mask.
4145 if (NumElts == 4 && Is256BitVec)
4148 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4149 // independently on 128-bit lanes.
4150 unsigned NumLanes = VT.getSizeInBits()/128;
4151 unsigned NumLaneElts = NumElts/NumLanes;
4153 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4154 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4155 int BitI = Mask[l+i];
4156 int BitI1 = Mask[l+i+1];
4158 if (!isUndefOrEqual(BitI, j))
4160 if (!isUndefOrEqual(BitI1, j))
4168 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4169 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4171 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4172 unsigned NumElts = VT.getVectorNumElements();
4174 if (VT.is512BitVector())
4177 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4178 "Unsupported vector type for unpckh");
4180 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4181 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4184 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4185 // independently on 128-bit lanes.
4186 unsigned NumLanes = VT.getSizeInBits()/128;
4187 unsigned NumLaneElts = NumElts/NumLanes;
4189 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4190 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4191 int BitI = Mask[l+i];
4192 int BitI1 = Mask[l+i+1];
4193 if (!isUndefOrEqual(BitI, j))
4195 if (!isUndefOrEqual(BitI1, j))
4202 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4203 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4204 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4205 if (!VT.is512BitVector())
4208 unsigned NumElts = VT.getVectorNumElements();
4209 unsigned HalfSize = NumElts/2;
4210 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4211 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4216 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4217 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4225 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4226 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4227 /// MOVSD, and MOVD, i.e. setting the lowest element.
4228 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4229 if (VT.getVectorElementType().getSizeInBits() < 32)
4231 if (!VT.is128BitVector())
4234 unsigned NumElts = VT.getVectorNumElements();
4236 if (!isUndefOrEqual(Mask[0], NumElts))
4239 for (unsigned i = 1; i != NumElts; ++i)
4240 if (!isUndefOrEqual(Mask[i], i))
4246 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4247 /// as permutations between 128-bit chunks or halves. As an example: this
4249 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4250 /// The first half comes from the second half of V1 and the second half from the
4251 /// the second half of V2.
4252 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4253 if (!HasFp256 || !VT.is256BitVector())
4256 // The shuffle result is divided into half A and half B. In total the two
4257 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4258 // B must come from C, D, E or F.
4259 unsigned HalfSize = VT.getVectorNumElements()/2;
4260 bool MatchA = false, MatchB = false;
4262 // Check if A comes from one of C, D, E, F.
4263 for (unsigned Half = 0; Half != 4; ++Half) {
4264 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4270 // Check if B comes from one of C, D, E, F.
4271 for (unsigned Half = 0; Half != 4; ++Half) {
4272 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4278 return MatchA && MatchB;
4281 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4282 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4283 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4284 MVT VT = SVOp->getSimpleValueType(0);
4286 unsigned HalfSize = VT.getVectorNumElements()/2;
4288 unsigned FstHalf = 0, SndHalf = 0;
4289 for (unsigned i = 0; i < HalfSize; ++i) {
4290 if (SVOp->getMaskElt(i) > 0) {
4291 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4295 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4296 if (SVOp->getMaskElt(i) > 0) {
4297 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4302 return (FstHalf | (SndHalf << 4));
4305 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4306 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4307 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4311 unsigned NumElts = VT.getVectorNumElements();
4313 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4314 for (unsigned i = 0; i != NumElts; ++i) {
4317 Imm8 |= Mask[i] << (i*2);
4322 unsigned LaneSize = 4;
4323 SmallVector<int, 4> MaskVal(LaneSize, -1);
4325 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4326 for (unsigned i = 0; i != LaneSize; ++i) {
4327 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4331 if (MaskVal[i] < 0) {
4332 MaskVal[i] = Mask[i+l] - l;
4333 Imm8 |= MaskVal[i] << (i*2);
4336 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4343 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4344 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4345 /// Note that VPERMIL mask matching is different depending whether theunderlying
4346 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4347 /// to the same elements of the low, but to the higher half of the source.
4348 /// In VPERMILPD the two lanes could be shuffled independently of each other
4349 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4350 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4351 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4352 if (VT.getSizeInBits() < 256 || EltSize < 32)
4354 bool symetricMaskRequired = (EltSize == 32);
4355 unsigned NumElts = VT.getVectorNumElements();
4357 unsigned NumLanes = VT.getSizeInBits()/128;
4358 unsigned LaneSize = NumElts/NumLanes;
4359 // 2 or 4 elements in one lane
4361 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4362 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4363 for (unsigned i = 0; i != LaneSize; ++i) {
4364 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4366 if (symetricMaskRequired) {
4367 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4368 ExpectedMaskVal[i] = Mask[i+l] - l;
4371 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4379 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4380 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4381 /// element of vector 2 and the other elements to come from vector 1 in order.
4382 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4383 bool V2IsSplat = false, bool V2IsUndef = false) {
4384 if (!VT.is128BitVector())
4387 unsigned NumOps = VT.getVectorNumElements();
4388 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4391 if (!isUndefOrEqual(Mask[0], 0))
4394 for (unsigned i = 1; i != NumOps; ++i)
4395 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4396 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4397 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4403 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4404 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4405 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4406 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4407 const X86Subtarget *Subtarget) {
4408 if (!Subtarget->hasSSE3())
4411 unsigned NumElems = VT.getVectorNumElements();
4413 if ((VT.is128BitVector() && NumElems != 4) ||
4414 (VT.is256BitVector() && NumElems != 8) ||
4415 (VT.is512BitVector() && NumElems != 16))
4418 // "i+1" is the value the indexed mask element must have
4419 for (unsigned i = 0; i != NumElems; i += 2)
4420 if (!isUndefOrEqual(Mask[i], i+1) ||
4421 !isUndefOrEqual(Mask[i+1], i+1))
4427 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4428 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4429 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4430 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4431 const X86Subtarget *Subtarget) {
4432 if (!Subtarget->hasSSE3())
4435 unsigned NumElems = VT.getVectorNumElements();
4437 if ((VT.is128BitVector() && NumElems != 4) ||
4438 (VT.is256BitVector() && NumElems != 8) ||
4439 (VT.is512BitVector() && NumElems != 16))
4442 // "i" is the value the indexed mask element must have
4443 for (unsigned i = 0; i != NumElems; i += 2)
4444 if (!isUndefOrEqual(Mask[i], i) ||
4445 !isUndefOrEqual(Mask[i+1], i))
4451 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4452 /// specifies a shuffle of elements that is suitable for input to 256-bit
4453 /// version of MOVDDUP.
4454 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4455 if (!HasFp256 || !VT.is256BitVector())
4458 unsigned NumElts = VT.getVectorNumElements();
4462 for (unsigned i = 0; i != NumElts/2; ++i)
4463 if (!isUndefOrEqual(Mask[i], 0))
4465 for (unsigned i = NumElts/2; i != NumElts; ++i)
4466 if (!isUndefOrEqual(Mask[i], NumElts/2))
4471 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4472 /// specifies a shuffle of elements that is suitable for input to 128-bit
4473 /// version of MOVDDUP.
4474 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4475 if (!VT.is128BitVector())
4478 unsigned e = VT.getVectorNumElements() / 2;
4479 for (unsigned i = 0; i != e; ++i)
4480 if (!isUndefOrEqual(Mask[i], i))
4482 for (unsigned i = 0; i != e; ++i)
4483 if (!isUndefOrEqual(Mask[e+i], i))
4488 /// isVEXTRACTIndex - Return true if the specified
4489 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4490 /// suitable for instruction that extract 128 or 256 bit vectors
4491 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4492 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4493 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4496 // The index should be aligned on a vecWidth-bit boundary.
4498 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4500 MVT VT = N->getSimpleValueType(0);
4501 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4502 bool Result = (Index * ElSize) % vecWidth == 0;
4507 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4508 /// operand specifies a subvector insert that is suitable for input to
4509 /// insertion of 128 or 256-bit subvectors
4510 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4511 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4512 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4514 // The index should be aligned on a vecWidth-bit boundary.
4516 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4518 MVT VT = N->getSimpleValueType(0);
4519 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4520 bool Result = (Index * ElSize) % vecWidth == 0;
4525 bool X86::isVINSERT128Index(SDNode *N) {
4526 return isVINSERTIndex(N, 128);
4529 bool X86::isVINSERT256Index(SDNode *N) {
4530 return isVINSERTIndex(N, 256);
4533 bool X86::isVEXTRACT128Index(SDNode *N) {
4534 return isVEXTRACTIndex(N, 128);
4537 bool X86::isVEXTRACT256Index(SDNode *N) {
4538 return isVEXTRACTIndex(N, 256);
4541 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4542 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4543 /// Handles 128-bit and 256-bit.
4544 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4545 MVT VT = N->getSimpleValueType(0);
4547 assert((VT.getSizeInBits() >= 128) &&
4548 "Unsupported vector type for PSHUF/SHUFP");
4550 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4551 // independently on 128-bit lanes.
4552 unsigned NumElts = VT.getVectorNumElements();
4553 unsigned NumLanes = VT.getSizeInBits()/128;
4554 unsigned NumLaneElts = NumElts/NumLanes;
4556 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4557 "Only supports 2, 4 or 8 elements per lane");
4559 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4561 for (unsigned i = 0; i != NumElts; ++i) {
4562 int Elt = N->getMaskElt(i);
4563 if (Elt < 0) continue;
4564 Elt &= NumLaneElts - 1;
4565 unsigned ShAmt = (i << Shift) % 8;
4566 Mask |= Elt << ShAmt;
4572 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4573 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4574 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4575 MVT VT = N->getSimpleValueType(0);
4577 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4578 "Unsupported vector type for PSHUFHW");
4580 unsigned NumElts = VT.getVectorNumElements();
4583 for (unsigned l = 0; l != NumElts; l += 8) {
4584 // 8 nodes per lane, but we only care about the last 4.
4585 for (unsigned i = 0; i < 4; ++i) {
4586 int Elt = N->getMaskElt(l+i+4);
4587 if (Elt < 0) continue;
4588 Elt &= 0x3; // only 2-bits.
4589 Mask |= Elt << (i * 2);
4596 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4597 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4598 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4599 MVT VT = N->getSimpleValueType(0);
4601 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4602 "Unsupported vector type for PSHUFHW");
4604 unsigned NumElts = VT.getVectorNumElements();
4607 for (unsigned l = 0; l != NumElts; l += 8) {
4608 // 8 nodes per lane, but we only care about the first 4.
4609 for (unsigned i = 0; i < 4; ++i) {
4610 int Elt = N->getMaskElt(l+i);
4611 if (Elt < 0) continue;
4612 Elt &= 0x3; // only 2-bits
4613 Mask |= Elt << (i * 2);
4620 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4621 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4622 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4623 MVT VT = SVOp->getSimpleValueType(0);
4624 unsigned EltSize = VT.is512BitVector() ? 1 :
4625 VT.getVectorElementType().getSizeInBits() >> 3;
4627 unsigned NumElts = VT.getVectorNumElements();
4628 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4629 unsigned NumLaneElts = NumElts/NumLanes;
4633 for (i = 0; i != NumElts; ++i) {
4634 Val = SVOp->getMaskElt(i);
4638 if (Val >= (int)NumElts)
4639 Val -= NumElts - NumLaneElts;
4641 assert(Val - i > 0 && "PALIGNR imm should be positive");
4642 return (Val - i) * EltSize;
4645 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4646 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4647 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4648 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4651 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4653 MVT VecVT = N->getOperand(0).getSimpleValueType();
4654 MVT ElVT = VecVT.getVectorElementType();
4656 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4657 return Index / NumElemsPerChunk;
4660 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4661 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4662 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4663 llvm_unreachable("Illegal insert subvector for VINSERT");
4666 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4668 MVT VecVT = N->getSimpleValueType(0);
4669 MVT ElVT = VecVT.getVectorElementType();
4671 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4672 return Index / NumElemsPerChunk;
4675 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4676 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4677 /// and VINSERTI128 instructions.
4678 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4679 return getExtractVEXTRACTImmediate(N, 128);
4682 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4683 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4684 /// and VINSERTI64x4 instructions.
4685 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4686 return getExtractVEXTRACTImmediate(N, 256);
4689 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4690 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4691 /// and VINSERTI128 instructions.
4692 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4693 return getInsertVINSERTImmediate(N, 128);
4696 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4697 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4698 /// and VINSERTI64x4 instructions.
4699 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4700 return getInsertVINSERTImmediate(N, 256);
4703 /// isZero - Returns true if Elt is a constant integer zero
4704 static bool isZero(SDValue V) {
4705 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4706 return C && C->isNullValue();
4709 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4711 bool X86::isZeroNode(SDValue Elt) {
4714 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4715 return CFP->getValueAPF().isPosZero();
4719 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4720 /// their permute mask.
4721 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4722 SelectionDAG &DAG) {
4723 MVT VT = SVOp->getSimpleValueType(0);
4724 unsigned NumElems = VT.getVectorNumElements();
4725 SmallVector<int, 8> MaskVec;
4727 for (unsigned i = 0; i != NumElems; ++i) {
4728 int Idx = SVOp->getMaskElt(i);
4730 if (Idx < (int)NumElems)
4735 MaskVec.push_back(Idx);
4737 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4738 SVOp->getOperand(0), &MaskVec[0]);
4741 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4742 /// match movhlps. The lower half elements should come from upper half of
4743 /// V1 (and in order), and the upper half elements should come from the upper
4744 /// half of V2 (and in order).
4745 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4746 if (!VT.is128BitVector())
4748 if (VT.getVectorNumElements() != 4)
4750 for (unsigned i = 0, e = 2; i != e; ++i)
4751 if (!isUndefOrEqual(Mask[i], i+2))
4753 for (unsigned i = 2; i != 4; ++i)
4754 if (!isUndefOrEqual(Mask[i], i+4))
4759 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4760 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4762 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4763 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4765 N = N->getOperand(0).getNode();
4766 if (!ISD::isNON_EXTLoad(N))
4769 *LD = cast<LoadSDNode>(N);
4773 // Test whether the given value is a vector value which will be legalized
4775 static bool WillBeConstantPoolLoad(SDNode *N) {
4776 if (N->getOpcode() != ISD::BUILD_VECTOR)
4779 // Check for any non-constant elements.
4780 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4781 switch (N->getOperand(i).getNode()->getOpcode()) {
4783 case ISD::ConstantFP:
4790 // Vectors of all-zeros and all-ones are materialized with special
4791 // instructions rather than being loaded.
4792 return !ISD::isBuildVectorAllZeros(N) &&
4793 !ISD::isBuildVectorAllOnes(N);
4796 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4797 /// match movlp{s|d}. The lower half elements should come from lower half of
4798 /// V1 (and in order), and the upper half elements should come from the upper
4799 /// half of V2 (and in order). And since V1 will become the source of the
4800 /// MOVLP, it must be either a vector load or a scalar load to vector.
4801 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4802 ArrayRef<int> Mask, MVT VT) {
4803 if (!VT.is128BitVector())
4806 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4808 // Is V2 is a vector load, don't do this transformation. We will try to use
4809 // load folding shufps op.
4810 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4813 unsigned NumElems = VT.getVectorNumElements();
4815 if (NumElems != 2 && NumElems != 4)
4817 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4818 if (!isUndefOrEqual(Mask[i], i))
4820 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4821 if (!isUndefOrEqual(Mask[i], i+NumElems))
4826 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4828 static bool isSplatVector(SDNode *N) {
4829 if (N->getOpcode() != ISD::BUILD_VECTOR)
4832 SDValue SplatValue = N->getOperand(0);
4833 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4834 if (N->getOperand(i) != SplatValue)
4839 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4840 /// to an zero vector.
4841 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4842 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4843 SDValue V1 = N->getOperand(0);
4844 SDValue V2 = N->getOperand(1);
4845 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4846 for (unsigned i = 0; i != NumElems; ++i) {
4847 int Idx = N->getMaskElt(i);
4848 if (Idx >= (int)NumElems) {
4849 unsigned Opc = V2.getOpcode();
4850 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4852 if (Opc != ISD::BUILD_VECTOR ||
4853 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4855 } else if (Idx >= 0) {
4856 unsigned Opc = V1.getOpcode();
4857 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4859 if (Opc != ISD::BUILD_VECTOR ||
4860 !X86::isZeroNode(V1.getOperand(Idx)))
4867 /// getZeroVector - Returns a vector of specified type with all zero elements.
4869 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4870 SelectionDAG &DAG, SDLoc dl) {
4871 assert(VT.isVector() && "Expected a vector type");
4873 // Always build SSE zero vectors as <4 x i32> bitcasted
4874 // to their dest type. This ensures they get CSE'd.
4876 if (VT.is128BitVector()) { // SSE
4877 if (Subtarget->hasSSE2()) { // SSE2
4878 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4879 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4881 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4882 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4884 } else if (VT.is256BitVector()) { // AVX
4885 if (Subtarget->hasInt256()) { // AVX2
4886 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4887 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4888 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4890 // 256-bit logic and arithmetic instructions in AVX are all
4891 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4892 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4893 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4894 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4896 } else if (VT.is512BitVector()) { // AVX-512
4897 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4898 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4899 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4900 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4901 } else if (VT.getScalarType() == MVT::i1) {
4902 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4903 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4904 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4905 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4907 llvm_unreachable("Unexpected vector type");
4909 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4912 /// getOnesVector - Returns a vector of specified type with all bits set.
4913 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4914 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4915 /// Then bitcast to their original type, ensuring they get CSE'd.
4916 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4918 assert(VT.isVector() && "Expected a vector type");
4920 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4922 if (VT.is256BitVector()) {
4923 if (HasInt256) { // AVX2
4924 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4925 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4927 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4928 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4930 } else if (VT.is128BitVector()) {
4931 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4933 llvm_unreachable("Unexpected vector type");
4935 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4938 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4939 /// that point to V2 points to its first element.
4940 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4941 for (unsigned i = 0; i != NumElems; ++i) {
4942 if (Mask[i] > (int)NumElems) {
4948 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4949 /// operation of specified width.
4950 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4952 unsigned NumElems = VT.getVectorNumElements();
4953 SmallVector<int, 8> Mask;
4954 Mask.push_back(NumElems);
4955 for (unsigned i = 1; i != NumElems; ++i)
4957 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4960 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4961 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4963 unsigned NumElems = VT.getVectorNumElements();
4964 SmallVector<int, 8> Mask;
4965 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4967 Mask.push_back(i + NumElems);
4969 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4972 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4973 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4975 unsigned NumElems = VT.getVectorNumElements();
4976 SmallVector<int, 8> Mask;
4977 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4978 Mask.push_back(i + Half);
4979 Mask.push_back(i + NumElems + Half);
4981 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4984 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4985 // a generic shuffle instruction because the target has no such instructions.
4986 // Generate shuffles which repeat i16 and i8 several times until they can be
4987 // represented by v4f32 and then be manipulated by target suported shuffles.
4988 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4989 MVT VT = V.getSimpleValueType();
4990 int NumElems = VT.getVectorNumElements();
4993 while (NumElems > 4) {
4994 if (EltNo < NumElems/2) {
4995 V = getUnpackl(DAG, dl, VT, V, V);
4997 V = getUnpackh(DAG, dl, VT, V, V);
4998 EltNo -= NumElems/2;
5005 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5006 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5007 MVT VT = V.getSimpleValueType();
5010 if (VT.is128BitVector()) {
5011 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5012 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5013 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5015 } else if (VT.is256BitVector()) {
5016 // To use VPERMILPS to splat scalars, the second half of indicies must
5017 // refer to the higher part, which is a duplication of the lower one,
5018 // because VPERMILPS can only handle in-lane permutations.
5019 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5020 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5022 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5023 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5026 llvm_unreachable("Vector size not supported");
5028 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5031 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5032 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5033 MVT SrcVT = SV->getSimpleValueType(0);
5034 SDValue V1 = SV->getOperand(0);
5037 int EltNo = SV->getSplatIndex();
5038 int NumElems = SrcVT.getVectorNumElements();
5039 bool Is256BitVec = SrcVT.is256BitVector();
5041 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5042 "Unknown how to promote splat for type");
5044 // Extract the 128-bit part containing the splat element and update
5045 // the splat element index when it refers to the higher register.
5047 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5048 if (EltNo >= NumElems/2)
5049 EltNo -= NumElems/2;
5052 // All i16 and i8 vector types can't be used directly by a generic shuffle
5053 // instruction because the target has no such instruction. Generate shuffles
5054 // which repeat i16 and i8 several times until they fit in i32, and then can
5055 // be manipulated by target suported shuffles.
5056 MVT EltVT = SrcVT.getVectorElementType();
5057 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5058 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5060 // Recreate the 256-bit vector and place the same 128-bit vector
5061 // into the low and high part. This is necessary because we want
5062 // to use VPERM* to shuffle the vectors
5064 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5067 return getLegalSplat(DAG, V1, EltNo);
5070 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5071 /// vector of zero or undef vector. This produces a shuffle where the low
5072 /// element of V2 is swizzled into the zero/undef vector, landing at element
5073 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5074 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5076 const X86Subtarget *Subtarget,
5077 SelectionDAG &DAG) {
5078 MVT VT = V2.getSimpleValueType();
5080 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5081 unsigned NumElems = VT.getVectorNumElements();
5082 SmallVector<int, 16> MaskVec;
5083 for (unsigned i = 0; i != NumElems; ++i)
5084 // If this is the insertion idx, put the low elt of V2 here.
5085 MaskVec.push_back(i == Idx ? NumElems : i);
5086 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5089 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5090 /// target specific opcode. Returns true if the Mask could be calculated.
5091 /// Sets IsUnary to true if only uses one source.
5092 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5093 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5094 unsigned NumElems = VT.getVectorNumElements();
5098 switch(N->getOpcode()) {
5100 ImmN = N->getOperand(N->getNumOperands()-1);
5101 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5103 case X86ISD::UNPCKH:
5104 DecodeUNPCKHMask(VT, Mask);
5106 case X86ISD::UNPCKL:
5107 DecodeUNPCKLMask(VT, Mask);
5109 case X86ISD::MOVHLPS:
5110 DecodeMOVHLPSMask(NumElems, Mask);
5112 case X86ISD::MOVLHPS:
5113 DecodeMOVLHPSMask(NumElems, Mask);
5115 case X86ISD::PALIGNR:
5116 ImmN = N->getOperand(N->getNumOperands()-1);
5117 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5119 case X86ISD::PSHUFD:
5120 case X86ISD::VPERMILP:
5121 ImmN = N->getOperand(N->getNumOperands()-1);
5122 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5125 case X86ISD::PSHUFHW:
5126 ImmN = N->getOperand(N->getNumOperands()-1);
5127 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5130 case X86ISD::PSHUFLW:
5131 ImmN = N->getOperand(N->getNumOperands()-1);
5132 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5135 case X86ISD::VPERMI:
5136 ImmN = N->getOperand(N->getNumOperands()-1);
5137 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5141 case X86ISD::MOVSD: {
5142 // The index 0 always comes from the first element of the second source,
5143 // this is why MOVSS and MOVSD are used in the first place. The other
5144 // elements come from the other positions of the first source vector
5145 Mask.push_back(NumElems);
5146 for (unsigned i = 1; i != NumElems; ++i) {
5151 case X86ISD::VPERM2X128:
5152 ImmN = N->getOperand(N->getNumOperands()-1);
5153 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154 if (Mask.empty()) return false;
5156 case X86ISD::MOVDDUP:
5157 case X86ISD::MOVLHPD:
5158 case X86ISD::MOVLPD:
5159 case X86ISD::MOVLPS:
5160 case X86ISD::MOVSHDUP:
5161 case X86ISD::MOVSLDUP:
5162 // Not yet implemented
5164 default: llvm_unreachable("unknown target shuffle node");
5170 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5171 /// element of the result of the vector shuffle.
5172 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5175 return SDValue(); // Limit search depth.
5177 SDValue V = SDValue(N, 0);
5178 EVT VT = V.getValueType();
5179 unsigned Opcode = V.getOpcode();
5181 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5182 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5183 int Elt = SV->getMaskElt(Index);
5186 return DAG.getUNDEF(VT.getVectorElementType());
5188 unsigned NumElems = VT.getVectorNumElements();
5189 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5190 : SV->getOperand(1);
5191 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5194 // Recurse into target specific vector shuffles to find scalars.
5195 if (isTargetShuffle(Opcode)) {
5196 MVT ShufVT = V.getSimpleValueType();
5197 unsigned NumElems = ShufVT.getVectorNumElements();
5198 SmallVector<int, 16> ShuffleMask;
5201 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5204 int Elt = ShuffleMask[Index];
5206 return DAG.getUNDEF(ShufVT.getVectorElementType());
5208 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5210 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5214 // Actual nodes that may contain scalar elements
5215 if (Opcode == ISD::BITCAST) {
5216 V = V.getOperand(0);
5217 EVT SrcVT = V.getValueType();
5218 unsigned NumElems = VT.getVectorNumElements();
5220 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5224 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5225 return (Index == 0) ? V.getOperand(0)
5226 : DAG.getUNDEF(VT.getVectorElementType());
5228 if (V.getOpcode() == ISD::BUILD_VECTOR)
5229 return V.getOperand(Index);
5234 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5235 /// shuffle operation which come from a consecutively from a zero. The
5236 /// search can start in two different directions, from left or right.
5237 /// We count undefs as zeros until PreferredNum is reached.
5238 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5239 unsigned NumElems, bool ZerosFromLeft,
5241 unsigned PreferredNum = -1U) {
5242 unsigned NumZeros = 0;
5243 for (unsigned i = 0; i != NumElems; ++i) {
5244 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5245 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5249 if (X86::isZeroNode(Elt))
5251 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5252 NumZeros = std::min(NumZeros + 1, PreferredNum);
5260 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5261 /// correspond consecutively to elements from one of the vector operands,
5262 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5264 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5265 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5266 unsigned NumElems, unsigned &OpNum) {
5267 bool SeenV1 = false;
5268 bool SeenV2 = false;
5270 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5271 int Idx = SVOp->getMaskElt(i);
5272 // Ignore undef indicies
5276 if (Idx < (int)NumElems)
5281 // Only accept consecutive elements from the same vector
5282 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5286 OpNum = SeenV1 ? 0 : 1;
5290 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5291 /// logical left shift of a vector.
5292 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5293 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5295 SVOp->getSimpleValueType(0).getVectorNumElements();
5296 unsigned NumZeros = getNumOfConsecutiveZeros(
5297 SVOp, NumElems, false /* check zeros from right */, DAG,
5298 SVOp->getMaskElt(0));
5304 // Considering the elements in the mask that are not consecutive zeros,
5305 // check if they consecutively come from only one of the source vectors.
5307 // V1 = {X, A, B, C} 0
5309 // vector_shuffle V1, V2 <1, 2, 3, X>
5311 if (!isShuffleMaskConsecutive(SVOp,
5312 0, // Mask Start Index
5313 NumElems-NumZeros, // Mask End Index(exclusive)
5314 NumZeros, // Where to start looking in the src vector
5315 NumElems, // Number of elements in vector
5316 OpSrc)) // Which source operand ?
5321 ShVal = SVOp->getOperand(OpSrc);
5325 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5326 /// logical left shift of a vector.
5327 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5328 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5330 SVOp->getSimpleValueType(0).getVectorNumElements();
5331 unsigned NumZeros = getNumOfConsecutiveZeros(
5332 SVOp, NumElems, true /* check zeros from left */, DAG,
5333 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5339 // Considering the elements in the mask that are not consecutive zeros,
5340 // check if they consecutively come from only one of the source vectors.
5342 // 0 { A, B, X, X } = V2
5344 // vector_shuffle V1, V2 <X, X, 4, 5>
5346 if (!isShuffleMaskConsecutive(SVOp,
5347 NumZeros, // Mask Start Index
5348 NumElems, // Mask End Index(exclusive)
5349 0, // Where to start looking in the src vector
5350 NumElems, // Number of elements in vector
5351 OpSrc)) // Which source operand ?
5356 ShVal = SVOp->getOperand(OpSrc);
5360 /// isVectorShift - Returns true if the shuffle can be implemented as a
5361 /// logical left or right shift of a vector.
5362 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5363 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5364 // Although the logic below support any bitwidth size, there are no
5365 // shift instructions which handle more than 128-bit vectors.
5366 if (!SVOp->getSimpleValueType(0).is128BitVector())
5369 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5370 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5376 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5378 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5379 unsigned NumNonZero, unsigned NumZero,
5381 const X86Subtarget* Subtarget,
5382 const TargetLowering &TLI) {
5389 for (unsigned i = 0; i < 16; ++i) {
5390 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5391 if (ThisIsNonZero && First) {
5393 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5395 V = DAG.getUNDEF(MVT::v8i16);
5400 SDValue ThisElt, LastElt;
5401 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5402 if (LastIsNonZero) {
5403 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5404 MVT::i16, Op.getOperand(i-1));
5406 if (ThisIsNonZero) {
5407 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5408 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5409 ThisElt, DAG.getConstant(8, MVT::i8));
5411 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5415 if (ThisElt.getNode())
5416 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5417 DAG.getIntPtrConstant(i/2));
5421 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5424 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5426 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5427 unsigned NumNonZero, unsigned NumZero,
5429 const X86Subtarget* Subtarget,
5430 const TargetLowering &TLI) {
5437 for (unsigned i = 0; i < 8; ++i) {
5438 bool isNonZero = (NonZeros & (1 << i)) != 0;
5442 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5444 V = DAG.getUNDEF(MVT::v8i16);
5447 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5448 MVT::v8i16, V, Op.getOperand(i),
5449 DAG.getIntPtrConstant(i));
5456 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5457 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5458 unsigned NonZeros, unsigned NumNonZero,
5459 unsigned NumZero, SelectionDAG &DAG,
5460 const X86Subtarget *Subtarget,
5461 const TargetLowering &TLI) {
5462 // We know there's at least one non-zero element
5463 unsigned FirstNonZeroIdx = 0;
5464 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5465 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5466 X86::isZeroNode(FirstNonZero)) {
5468 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5471 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5472 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5475 SDValue V = FirstNonZero.getOperand(0);
5476 MVT VVT = V.getSimpleValueType();
5477 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5480 unsigned FirstNonZeroDst =
5481 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5482 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5483 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5484 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5486 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5487 SDValue Elem = Op.getOperand(Idx);
5488 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5491 // TODO: What else can be here? Deal with it.
5492 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5495 // TODO: Some optimizations are still possible here
5496 // ex: Getting one element from a vector, and the rest from another.
5497 if (Elem.getOperand(0) != V)
5500 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5503 else if (IncorrectIdx == -1U) {
5507 // There was already one element with an incorrect index.
5508 // We can't optimize this case to an insertps.
5512 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5514 EVT VT = Op.getSimpleValueType();
5515 unsigned ElementMoveMask = 0;
5516 if (IncorrectIdx == -1U)
5517 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5519 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5521 SDValue InsertpsMask =
5522 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5523 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5529 /// getVShift - Return a vector logical shift node.
5531 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5532 unsigned NumBits, SelectionDAG &DAG,
5533 const TargetLowering &TLI, SDLoc dl) {
5534 assert(VT.is128BitVector() && "Unknown type for VShift");
5535 EVT ShVT = MVT::v2i64;
5536 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5537 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5538 return DAG.getNode(ISD::BITCAST, dl, VT,
5539 DAG.getNode(Opc, dl, ShVT, SrcOp,
5540 DAG.getConstant(NumBits,
5541 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5545 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5547 // Check if the scalar load can be widened into a vector load. And if
5548 // the address is "base + cst" see if the cst can be "absorbed" into
5549 // the shuffle mask.
5550 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5551 SDValue Ptr = LD->getBasePtr();
5552 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5554 EVT PVT = LD->getValueType(0);
5555 if (PVT != MVT::i32 && PVT != MVT::f32)
5560 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5561 FI = FINode->getIndex();
5563 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5564 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5565 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5566 Offset = Ptr.getConstantOperandVal(1);
5567 Ptr = Ptr.getOperand(0);
5572 // FIXME: 256-bit vector instructions don't require a strict alignment,
5573 // improve this code to support it better.
5574 unsigned RequiredAlign = VT.getSizeInBits()/8;
5575 SDValue Chain = LD->getChain();
5576 // Make sure the stack object alignment is at least 16 or 32.
5577 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5578 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5579 if (MFI->isFixedObjectIndex(FI)) {
5580 // Can't change the alignment. FIXME: It's possible to compute
5581 // the exact stack offset and reference FI + adjust offset instead.
5582 // If someone *really* cares about this. That's the way to implement it.
5585 MFI->setObjectAlignment(FI, RequiredAlign);
5589 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5590 // Ptr + (Offset & ~15).
5593 if ((Offset % RequiredAlign) & 3)
5595 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5597 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5598 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5600 int EltNo = (Offset - StartOffset) >> 2;
5601 unsigned NumElems = VT.getVectorNumElements();
5603 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5604 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5605 LD->getPointerInfo().getWithOffset(StartOffset),
5606 false, false, false, 0);
5608 SmallVector<int, 8> Mask;
5609 for (unsigned i = 0; i != NumElems; ++i)
5610 Mask.push_back(EltNo);
5612 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5618 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5619 /// vector of type 'VT', see if the elements can be replaced by a single large
5620 /// load which has the same value as a build_vector whose operands are 'elts'.
5622 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5624 /// FIXME: we'd also like to handle the case where the last elements are zero
5625 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5626 /// There's even a handy isZeroNode for that purpose.
5627 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5628 SDLoc &DL, SelectionDAG &DAG,
5629 bool isAfterLegalize) {
5630 EVT EltVT = VT.getVectorElementType();
5631 unsigned NumElems = Elts.size();
5633 LoadSDNode *LDBase = nullptr;
5634 unsigned LastLoadedElt = -1U;
5636 // For each element in the initializer, see if we've found a load or an undef.
5637 // If we don't find an initial load element, or later load elements are
5638 // non-consecutive, bail out.
5639 for (unsigned i = 0; i < NumElems; ++i) {
5640 SDValue Elt = Elts[i];
5642 if (!Elt.getNode() ||
5643 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5646 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5648 LDBase = cast<LoadSDNode>(Elt.getNode());
5652 if (Elt.getOpcode() == ISD::UNDEF)
5655 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5656 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5661 // If we have found an entire vector of loads and undefs, then return a large
5662 // load of the entire vector width starting at the base pointer. If we found
5663 // consecutive loads for the low half, generate a vzext_load node.
5664 if (LastLoadedElt == NumElems - 1) {
5666 if (isAfterLegalize &&
5667 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5670 SDValue NewLd = SDValue();
5672 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5673 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5674 LDBase->getPointerInfo(),
5675 LDBase->isVolatile(), LDBase->isNonTemporal(),
5676 LDBase->isInvariant(), 0);
5677 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5678 LDBase->getPointerInfo(),
5679 LDBase->isVolatile(), LDBase->isNonTemporal(),
5680 LDBase->isInvariant(), LDBase->getAlignment());
5682 if (LDBase->hasAnyUseOfValue(1)) {
5683 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5685 SDValue(NewLd.getNode(), 1));
5686 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5687 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5688 SDValue(NewLd.getNode(), 1));
5693 if (NumElems == 4 && LastLoadedElt == 1 &&
5694 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5695 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5696 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5698 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5699 LDBase->getPointerInfo(),
5700 LDBase->getAlignment(),
5701 false/*isVolatile*/, true/*ReadMem*/,
5704 // Make sure the newly-created LOAD is in the same position as LDBase in
5705 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5706 // update uses of LDBase's output chain to use the TokenFactor.
5707 if (LDBase->hasAnyUseOfValue(1)) {
5708 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5709 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5710 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5711 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5712 SDValue(ResNode.getNode(), 1));
5715 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5720 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5721 /// to generate a splat value for the following cases:
5722 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5723 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5724 /// a scalar load, or a constant.
5725 /// The VBROADCAST node is returned when a pattern is found,
5726 /// or SDValue() otherwise.
5727 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5728 SelectionDAG &DAG) {
5729 if (!Subtarget->hasFp256())
5732 MVT VT = Op.getSimpleValueType();
5735 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5736 "Unsupported vector type for broadcast.");
5741 switch (Op.getOpcode()) {
5743 // Unknown pattern found.
5746 case ISD::BUILD_VECTOR: {
5747 // The BUILD_VECTOR node must be a splat.
5748 if (!isSplatVector(Op.getNode()))
5751 Ld = Op.getOperand(0);
5752 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5753 Ld.getOpcode() == ISD::ConstantFP);
5755 // The suspected load node has several users. Make sure that all
5756 // of its users are from the BUILD_VECTOR node.
5757 // Constants may have multiple users.
5758 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5763 case ISD::VECTOR_SHUFFLE: {
5764 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5766 // Shuffles must have a splat mask where the first element is
5768 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5771 SDValue Sc = Op.getOperand(0);
5772 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5773 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5775 if (!Subtarget->hasInt256())
5778 // Use the register form of the broadcast instruction available on AVX2.
5779 if (VT.getSizeInBits() >= 256)
5780 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5781 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5784 Ld = Sc.getOperand(0);
5785 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5786 Ld.getOpcode() == ISD::ConstantFP);
5788 // The scalar_to_vector node and the suspected
5789 // load node must have exactly one user.
5790 // Constants may have multiple users.
5792 // AVX-512 has register version of the broadcast
5793 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5794 Ld.getValueType().getSizeInBits() >= 32;
5795 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5802 bool IsGE256 = (VT.getSizeInBits() >= 256);
5804 // Handle the broadcasting a single constant scalar from the constant pool
5805 // into a vector. On Sandybridge it is still better to load a constant vector
5806 // from the constant pool and not to broadcast it from a scalar.
5807 if (ConstSplatVal && Subtarget->hasInt256()) {
5808 EVT CVT = Ld.getValueType();
5809 assert(!CVT.isVector() && "Must not broadcast a vector type");
5810 unsigned ScalarSize = CVT.getSizeInBits();
5812 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5813 const Constant *C = nullptr;
5814 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5815 C = CI->getConstantIntValue();
5816 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5817 C = CF->getConstantFPValue();
5819 assert(C && "Invalid constant type");
5821 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5822 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5823 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5824 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5825 MachinePointerInfo::getConstantPool(),
5826 false, false, false, Alignment);
5828 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5832 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5833 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5835 // Handle AVX2 in-register broadcasts.
5836 if (!IsLoad && Subtarget->hasInt256() &&
5837 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5838 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5840 // The scalar source must be a normal load.
5844 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5845 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5847 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5848 // double since there is no vbroadcastsd xmm
5849 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5850 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5851 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5854 // Unsupported broadcast.
5858 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5859 /// underlying vector and index.
5861 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5863 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5865 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5866 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5869 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5871 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5873 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5874 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5877 // In this case the vector is the extract_subvector expression and the index
5878 // is 2, as specified by the shuffle.
5879 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5880 SDValue ShuffleVec = SVOp->getOperand(0);
5881 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5882 assert(ShuffleVecVT.getVectorElementType() ==
5883 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5885 int ShuffleIdx = SVOp->getMaskElt(Idx);
5886 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5887 ExtractedFromVec = ShuffleVec;
5893 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5894 MVT VT = Op.getSimpleValueType();
5896 // Skip if insert_vec_elt is not supported.
5897 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5898 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5902 unsigned NumElems = Op.getNumOperands();
5906 SmallVector<unsigned, 4> InsertIndices;
5907 SmallVector<int, 8> Mask(NumElems, -1);
5909 for (unsigned i = 0; i != NumElems; ++i) {
5910 unsigned Opc = Op.getOperand(i).getOpcode();
5912 if (Opc == ISD::UNDEF)
5915 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5916 // Quit if more than 1 elements need inserting.
5917 if (InsertIndices.size() > 1)
5920 InsertIndices.push_back(i);
5924 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5925 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5926 // Quit if non-constant index.
5927 if (!isa<ConstantSDNode>(ExtIdx))
5929 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5931 // Quit if extracted from vector of different type.
5932 if (ExtractedFromVec.getValueType() != VT)
5935 if (!VecIn1.getNode())
5936 VecIn1 = ExtractedFromVec;
5937 else if (VecIn1 != ExtractedFromVec) {
5938 if (!VecIn2.getNode())
5939 VecIn2 = ExtractedFromVec;
5940 else if (VecIn2 != ExtractedFromVec)
5941 // Quit if more than 2 vectors to shuffle
5945 if (ExtractedFromVec == VecIn1)
5947 else if (ExtractedFromVec == VecIn2)
5948 Mask[i] = Idx + NumElems;
5951 if (!VecIn1.getNode())
5954 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5955 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5956 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5957 unsigned Idx = InsertIndices[i];
5958 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5959 DAG.getIntPtrConstant(Idx));
5965 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5967 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5969 MVT VT = Op.getSimpleValueType();
5970 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5971 "Unexpected type in LowerBUILD_VECTORvXi1!");
5974 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5975 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5976 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5977 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5980 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5981 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5982 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5983 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5986 bool AllContants = true;
5987 uint64_t Immediate = 0;
5988 int NonConstIdx = -1;
5989 bool IsSplat = true;
5990 unsigned NumNonConsts = 0;
5991 unsigned NumConsts = 0;
5992 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5993 SDValue In = Op.getOperand(idx);
5994 if (In.getOpcode() == ISD::UNDEF)
5996 if (!isa<ConstantSDNode>(In)) {
5997 AllContants = false;
6003 if (cast<ConstantSDNode>(In)->getZExtValue())
6004 Immediate |= (1ULL << idx);
6006 if (In != Op.getOperand(0))
6011 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6012 DAG.getConstant(Immediate, MVT::i16));
6013 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6014 DAG.getIntPtrConstant(0));
6017 if (NumNonConsts == 1 && NonConstIdx != 0) {
6020 SDValue VecAsImm = DAG.getConstant(Immediate,
6021 MVT::getIntegerVT(VT.getSizeInBits()));
6022 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6025 DstVec = DAG.getUNDEF(VT);
6026 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6027 Op.getOperand(NonConstIdx),
6028 DAG.getIntPtrConstant(NonConstIdx));
6030 if (!IsSplat && (NonConstIdx != 0))
6031 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6032 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6035 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6036 DAG.getConstant(-1, SelectVT),
6037 DAG.getConstant(0, SelectVT));
6039 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6040 DAG.getConstant((Immediate | 1), SelectVT),
6041 DAG.getConstant(Immediate, SelectVT));
6042 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6046 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6049 MVT VT = Op.getSimpleValueType();
6050 MVT ExtVT = VT.getVectorElementType();
6051 unsigned NumElems = Op.getNumOperands();
6053 // Generate vectors for predicate vectors.
6054 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6055 return LowerBUILD_VECTORvXi1(Op, DAG);
6057 // Vectors containing all zeros can be matched by pxor and xorps later
6058 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6059 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6060 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6061 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6064 return getZeroVector(VT, Subtarget, DAG, dl);
6067 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6068 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6069 // vpcmpeqd on 256-bit vectors.
6070 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6071 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6074 if (!VT.is512BitVector())
6075 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6078 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6079 if (Broadcast.getNode())
6082 unsigned EVTBits = ExtVT.getSizeInBits();
6084 unsigned NumZero = 0;
6085 unsigned NumNonZero = 0;
6086 unsigned NonZeros = 0;
6087 bool IsAllConstants = true;
6088 SmallSet<SDValue, 8> Values;
6089 for (unsigned i = 0; i < NumElems; ++i) {
6090 SDValue Elt = Op.getOperand(i);
6091 if (Elt.getOpcode() == ISD::UNDEF)
6094 if (Elt.getOpcode() != ISD::Constant &&
6095 Elt.getOpcode() != ISD::ConstantFP)
6096 IsAllConstants = false;
6097 if (X86::isZeroNode(Elt))
6100 NonZeros |= (1 << i);
6105 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6106 if (NumNonZero == 0)
6107 return DAG.getUNDEF(VT);
6109 // Special case for single non-zero, non-undef, element.
6110 if (NumNonZero == 1) {
6111 unsigned Idx = countTrailingZeros(NonZeros);
6112 SDValue Item = Op.getOperand(Idx);
6114 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6115 // the value are obviously zero, truncate the value to i32 and do the
6116 // insertion that way. Only do this if the value is non-constant or if the
6117 // value is a constant being inserted into element 0. It is cheaper to do
6118 // a constant pool load than it is to do a movd + shuffle.
6119 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6120 (!IsAllConstants || Idx == 0)) {
6121 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6123 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6124 EVT VecVT = MVT::v4i32;
6125 unsigned VecElts = 4;
6127 // Truncate the value (which may itself be a constant) to i32, and
6128 // convert it to a vector with movd (S2V+shuffle to zero extend).
6129 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6130 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6131 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6133 // Now we have our 32-bit value zero extended in the low element of
6134 // a vector. If Idx != 0, swizzle it into place.
6136 SmallVector<int, 4> Mask;
6137 Mask.push_back(Idx);
6138 for (unsigned i = 1; i != VecElts; ++i)
6140 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6143 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6147 // If we have a constant or non-constant insertion into the low element of
6148 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6149 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6150 // depending on what the source datatype is.
6153 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6155 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6156 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6157 if (VT.is256BitVector() || VT.is512BitVector()) {
6158 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6159 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6160 Item, DAG.getIntPtrConstant(0));
6162 assert(VT.is128BitVector() && "Expected an SSE value type!");
6163 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6164 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6165 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6168 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6169 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6170 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6171 if (VT.is256BitVector()) {
6172 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6173 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6175 assert(VT.is128BitVector() && "Expected an SSE value type!");
6176 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6178 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6182 // Is it a vector logical left shift?
6183 if (NumElems == 2 && Idx == 1 &&
6184 X86::isZeroNode(Op.getOperand(0)) &&
6185 !X86::isZeroNode(Op.getOperand(1))) {
6186 unsigned NumBits = VT.getSizeInBits();
6187 return getVShift(true, VT,
6188 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6189 VT, Op.getOperand(1)),
6190 NumBits/2, DAG, *this, dl);
6193 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6196 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6197 // is a non-constant being inserted into an element other than the low one,
6198 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6199 // movd/movss) to move this into the low element, then shuffle it into
6201 if (EVTBits == 32) {
6202 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6204 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6205 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6206 SmallVector<int, 8> MaskVec;
6207 for (unsigned i = 0; i != NumElems; ++i)
6208 MaskVec.push_back(i == Idx ? 0 : 1);
6209 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6213 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6214 if (Values.size() == 1) {
6215 if (EVTBits == 32) {
6216 // Instead of a shuffle like this:
6217 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6218 // Check if it's possible to issue this instead.
6219 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6220 unsigned Idx = countTrailingZeros(NonZeros);
6221 SDValue Item = Op.getOperand(Idx);
6222 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6223 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6228 // A vector full of immediates; various special cases are already
6229 // handled, so this is best done with a single constant-pool load.
6233 // For AVX-length vectors, build the individual 128-bit pieces and use
6234 // shuffles to put them in place.
6235 if (VT.is256BitVector() || VT.is512BitVector()) {
6236 SmallVector<SDValue, 64> V;
6237 for (unsigned i = 0; i != NumElems; ++i)
6238 V.push_back(Op.getOperand(i));
6240 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6242 // Build both the lower and upper subvector.
6243 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6244 makeArrayRef(&V[0], NumElems/2));
6245 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6246 makeArrayRef(&V[NumElems / 2], NumElems/2));
6248 // Recreate the wider vector with the lower and upper part.
6249 if (VT.is256BitVector())
6250 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6251 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6254 // Let legalizer expand 2-wide build_vectors.
6255 if (EVTBits == 64) {
6256 if (NumNonZero == 1) {
6257 // One half is zero or undef.
6258 unsigned Idx = countTrailingZeros(NonZeros);
6259 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6260 Op.getOperand(Idx));
6261 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6266 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6267 if (EVTBits == 8 && NumElems == 16) {
6268 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6270 if (V.getNode()) return V;
6273 if (EVTBits == 16 && NumElems == 8) {
6274 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6276 if (V.getNode()) return V;
6279 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6280 if (EVTBits == 32 && NumElems == 4) {
6281 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6282 NumZero, DAG, Subtarget, *this);
6287 // If element VT is == 32 bits, turn it into a number of shuffles.
6288 SmallVector<SDValue, 8> V(NumElems);
6289 if (NumElems == 4 && NumZero > 0) {
6290 for (unsigned i = 0; i < 4; ++i) {
6291 bool isZero = !(NonZeros & (1 << i));
6293 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6295 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6298 for (unsigned i = 0; i < 2; ++i) {
6299 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6302 V[i] = V[i*2]; // Must be a zero vector.
6305 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6308 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6311 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6316 bool Reverse1 = (NonZeros & 0x3) == 2;
6317 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6321 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6322 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6324 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6327 if (Values.size() > 1 && VT.is128BitVector()) {
6328 // Check for a build vector of consecutive loads.
6329 for (unsigned i = 0; i < NumElems; ++i)
6330 V[i] = Op.getOperand(i);
6332 // Check for elements which are consecutive loads.
6333 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6337 // Check for a build vector from mostly shuffle plus few inserting.
6338 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6342 // For SSE 4.1, use insertps to put the high elements into the low element.
6343 if (getSubtarget()->hasSSE41()) {
6345 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6346 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6348 Result = DAG.getUNDEF(VT);
6350 for (unsigned i = 1; i < NumElems; ++i) {
6351 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6352 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6353 Op.getOperand(i), DAG.getIntPtrConstant(i));
6358 // Otherwise, expand into a number of unpckl*, start by extending each of
6359 // our (non-undef) elements to the full vector width with the element in the
6360 // bottom slot of the vector (which generates no code for SSE).
6361 for (unsigned i = 0; i < NumElems; ++i) {
6362 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6363 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6365 V[i] = DAG.getUNDEF(VT);
6368 // Next, we iteratively mix elements, e.g. for v4f32:
6369 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6370 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6371 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6372 unsigned EltStride = NumElems >> 1;
6373 while (EltStride != 0) {
6374 for (unsigned i = 0; i < EltStride; ++i) {
6375 // If V[i+EltStride] is undef and this is the first round of mixing,
6376 // then it is safe to just drop this shuffle: V[i] is already in the
6377 // right place, the one element (since it's the first round) being
6378 // inserted as undef can be dropped. This isn't safe for successive
6379 // rounds because they will permute elements within both vectors.
6380 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6381 EltStride == NumElems/2)
6384 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6393 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6394 // to create 256-bit vectors from two other 128-bit ones.
6395 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6397 MVT ResVT = Op.getSimpleValueType();
6399 assert((ResVT.is256BitVector() ||
6400 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6402 SDValue V1 = Op.getOperand(0);
6403 SDValue V2 = Op.getOperand(1);
6404 unsigned NumElems = ResVT.getVectorNumElements();
6405 if(ResVT.is256BitVector())
6406 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6408 if (Op.getNumOperands() == 4) {
6409 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6410 ResVT.getVectorNumElements()/2);
6411 SDValue V3 = Op.getOperand(2);
6412 SDValue V4 = Op.getOperand(3);
6413 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6414 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6416 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6419 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6420 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6421 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6422 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6423 Op.getNumOperands() == 4)));
6425 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6426 // from two other 128-bit ones.
6428 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6429 return LowerAVXCONCAT_VECTORS(Op, DAG);
6432 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6433 bool hasInt256, unsigned *MaskOut = nullptr) {
6434 MVT EltVT = VT.getVectorElementType();
6436 // There is no blend with immediate in AVX-512.
6437 if (VT.is512BitVector())
6440 if (!hasSSE41 || EltVT == MVT::i8)
6442 if (!hasInt256 && VT == MVT::v16i16)
6445 unsigned MaskValue = 0;
6446 unsigned NumElems = VT.getVectorNumElements();
6447 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6448 unsigned NumLanes = (NumElems - 1) / 8 + 1;
6449 unsigned NumElemsInLane = NumElems / NumLanes;
6451 // Blend for v16i16 should be symetric for the both lanes.
6452 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6454 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6455 int EltIdx = MaskVals[i];
6457 if ((EltIdx < 0 || EltIdx == (int)i) &&
6458 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6461 if (((unsigned)EltIdx == (i + NumElems)) &&
6462 (SndLaneEltIdx < 0 ||
6463 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6464 MaskValue |= (1 << i);
6470 *MaskOut = MaskValue;
6474 // Try to lower a shuffle node into a simple blend instruction.
6475 // This function assumes isBlendMask returns true for this
6476 // SuffleVectorSDNode
6477 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6479 const X86Subtarget *Subtarget,
6480 SelectionDAG &DAG) {
6481 MVT VT = SVOp->getSimpleValueType(0);
6482 MVT EltVT = VT.getVectorElementType();
6483 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6484 Subtarget->hasInt256() && "Trying to lower a "
6485 "VECTOR_SHUFFLE to a Blend but "
6486 "with the wrong mask"));
6487 SDValue V1 = SVOp->getOperand(0);
6488 SDValue V2 = SVOp->getOperand(1);
6490 unsigned NumElems = VT.getVectorNumElements();
6492 // Convert i32 vectors to floating point if it is not AVX2.
6493 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6495 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6496 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6498 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6499 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6502 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6503 DAG.getConstant(MaskValue, MVT::i32));
6504 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6507 /// In vector type \p VT, return true if the element at index \p InputIdx
6508 /// falls on a different 128-bit lane than \p OutputIdx.
6509 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6510 unsigned OutputIdx) {
6511 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6512 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6515 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6516 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6517 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6518 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6520 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6521 SelectionDAG &DAG) {
6522 MVT VT = V1.getSimpleValueType();
6523 assert(VT.is128BitVector() || VT.is256BitVector());
6525 MVT EltVT = VT.getVectorElementType();
6526 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6527 unsigned NumElts = VT.getVectorNumElements();
6529 SmallVector<SDValue, 32> PshufbMask;
6530 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6531 int InputIdx = MaskVals[OutputIdx];
6532 unsigned InputByteIdx;
6534 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6535 InputByteIdx = 0x80;
6537 // Cross lane is not allowed.
6538 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6540 InputByteIdx = InputIdx * EltSizeInBytes;
6541 // Index is an byte offset within the 128-bit lane.
6542 InputByteIdx &= 0xf;
6545 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6546 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6547 if (InputByteIdx != 0x80)
6552 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6554 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6555 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6556 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6559 // v8i16 shuffles - Prefer shuffles in the following order:
6560 // 1. [all] pshuflw, pshufhw, optional move
6561 // 2. [ssse3] 1 x pshufb
6562 // 3. [ssse3] 2 x pshufb + 1 x por
6563 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6565 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6566 SelectionDAG &DAG) {
6567 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6568 SDValue V1 = SVOp->getOperand(0);
6569 SDValue V2 = SVOp->getOperand(1);
6571 SmallVector<int, 8> MaskVals;
6573 // Determine if more than 1 of the words in each of the low and high quadwords
6574 // of the result come from the same quadword of one of the two inputs. Undef
6575 // mask values count as coming from any quadword, for better codegen.
6577 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6578 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6579 unsigned LoQuad[] = { 0, 0, 0, 0 };
6580 unsigned HiQuad[] = { 0, 0, 0, 0 };
6581 // Indices of quads used.
6582 std::bitset<4> InputQuads;
6583 for (unsigned i = 0; i < 8; ++i) {
6584 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6585 int EltIdx = SVOp->getMaskElt(i);
6586 MaskVals.push_back(EltIdx);
6595 InputQuads.set(EltIdx / 4);
6598 int BestLoQuad = -1;
6599 unsigned MaxQuad = 1;
6600 for (unsigned i = 0; i < 4; ++i) {
6601 if (LoQuad[i] > MaxQuad) {
6603 MaxQuad = LoQuad[i];
6607 int BestHiQuad = -1;
6609 for (unsigned i = 0; i < 4; ++i) {
6610 if (HiQuad[i] > MaxQuad) {
6612 MaxQuad = HiQuad[i];
6616 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6617 // of the two input vectors, shuffle them into one input vector so only a
6618 // single pshufb instruction is necessary. If there are more than 2 input
6619 // quads, disable the next transformation since it does not help SSSE3.
6620 bool V1Used = InputQuads[0] || InputQuads[1];
6621 bool V2Used = InputQuads[2] || InputQuads[3];
6622 if (Subtarget->hasSSSE3()) {
6623 if (InputQuads.count() == 2 && V1Used && V2Used) {
6624 BestLoQuad = InputQuads[0] ? 0 : 1;
6625 BestHiQuad = InputQuads[2] ? 2 : 3;
6627 if (InputQuads.count() > 2) {
6633 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6634 // the shuffle mask. If a quad is scored as -1, that means that it contains
6635 // words from all 4 input quadwords.
6637 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6639 BestLoQuad < 0 ? 0 : BestLoQuad,
6640 BestHiQuad < 0 ? 1 : BestHiQuad
6642 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6643 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6644 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6645 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6647 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6648 // source words for the shuffle, to aid later transformations.
6649 bool AllWordsInNewV = true;
6650 bool InOrder[2] = { true, true };
6651 for (unsigned i = 0; i != 8; ++i) {
6652 int idx = MaskVals[i];
6654 InOrder[i/4] = false;
6655 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6657 AllWordsInNewV = false;
6661 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6662 if (AllWordsInNewV) {
6663 for (int i = 0; i != 8; ++i) {
6664 int idx = MaskVals[i];
6667 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6668 if ((idx != i) && idx < 4)
6670 if ((idx != i) && idx > 3)
6679 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6680 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6681 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6682 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6683 unsigned TargetMask = 0;
6684 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6685 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6686 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6687 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6688 getShufflePSHUFLWImmediate(SVOp);
6689 V1 = NewV.getOperand(0);
6690 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6694 // Promote splats to a larger type which usually leads to more efficient code.
6695 // FIXME: Is this true if pshufb is available?
6696 if (SVOp->isSplat())
6697 return PromoteSplat(SVOp, DAG);
6699 // If we have SSSE3, and all words of the result are from 1 input vector,
6700 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6701 // is present, fall back to case 4.
6702 if (Subtarget->hasSSSE3()) {
6703 SmallVector<SDValue,16> pshufbMask;
6705 // If we have elements from both input vectors, set the high bit of the
6706 // shuffle mask element to zero out elements that come from V2 in the V1
6707 // mask, and elements that come from V1 in the V2 mask, so that the two
6708 // results can be OR'd together.
6709 bool TwoInputs = V1Used && V2Used;
6710 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6712 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6714 // Calculate the shuffle mask for the second input, shuffle it, and
6715 // OR it with the first shuffled input.
6716 CommuteVectorShuffleMask(MaskVals, 8);
6717 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6718 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6719 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6722 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6723 // and update MaskVals with new element order.
6724 std::bitset<8> InOrder;
6725 if (BestLoQuad >= 0) {
6726 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6727 for (int i = 0; i != 4; ++i) {
6728 int idx = MaskVals[i];
6731 } else if ((idx / 4) == BestLoQuad) {
6736 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6739 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6740 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6741 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6743 getShufflePSHUFLWImmediate(SVOp), DAG);
6747 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6748 // and update MaskVals with the new element order.
6749 if (BestHiQuad >= 0) {
6750 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6751 for (unsigned i = 4; i != 8; ++i) {
6752 int idx = MaskVals[i];
6755 } else if ((idx / 4) == BestHiQuad) {
6756 MaskV[i] = (idx & 3) + 4;
6760 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6763 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6764 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6765 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6767 getShufflePSHUFHWImmediate(SVOp), DAG);
6771 // In case BestHi & BestLo were both -1, which means each quadword has a word
6772 // from each of the four input quadwords, calculate the InOrder bitvector now
6773 // before falling through to the insert/extract cleanup.
6774 if (BestLoQuad == -1 && BestHiQuad == -1) {
6776 for (int i = 0; i != 8; ++i)
6777 if (MaskVals[i] < 0 || MaskVals[i] == i)
6781 // The other elements are put in the right place using pextrw and pinsrw.
6782 for (unsigned i = 0; i != 8; ++i) {
6785 int EltIdx = MaskVals[i];
6788 SDValue ExtOp = (EltIdx < 8) ?
6789 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6790 DAG.getIntPtrConstant(EltIdx)) :
6791 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6792 DAG.getIntPtrConstant(EltIdx - 8));
6793 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6794 DAG.getIntPtrConstant(i));
6799 /// \brief v16i16 shuffles
6801 /// FIXME: We only support generation of a single pshufb currently. We can
6802 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6803 /// well (e.g 2 x pshufb + 1 x por).
6805 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6806 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6807 SDValue V1 = SVOp->getOperand(0);
6808 SDValue V2 = SVOp->getOperand(1);
6811 if (V2.getOpcode() != ISD::UNDEF)
6814 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6815 return getPSHUFB(MaskVals, V1, dl, DAG);
6818 // v16i8 shuffles - Prefer shuffles in the following order:
6819 // 1. [ssse3] 1 x pshufb
6820 // 2. [ssse3] 2 x pshufb + 1 x por
6821 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6822 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6823 const X86Subtarget* Subtarget,
6824 SelectionDAG &DAG) {
6825 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6826 SDValue V1 = SVOp->getOperand(0);
6827 SDValue V2 = SVOp->getOperand(1);
6829 ArrayRef<int> MaskVals = SVOp->getMask();
6831 // Promote splats to a larger type which usually leads to more efficient code.
6832 // FIXME: Is this true if pshufb is available?
6833 if (SVOp->isSplat())
6834 return PromoteSplat(SVOp, DAG);
6836 // If we have SSSE3, case 1 is generated when all result bytes come from
6837 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6838 // present, fall back to case 3.
6840 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6841 if (Subtarget->hasSSSE3()) {
6842 SmallVector<SDValue,16> pshufbMask;
6844 // If all result elements are from one input vector, then only translate
6845 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6847 // Otherwise, we have elements from both input vectors, and must zero out
6848 // elements that come from V2 in the first mask, and V1 in the second mask
6849 // so that we can OR them together.
6850 for (unsigned i = 0; i != 16; ++i) {
6851 int EltIdx = MaskVals[i];
6852 if (EltIdx < 0 || EltIdx >= 16)
6854 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6856 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6857 DAG.getNode(ISD::BUILD_VECTOR, dl,
6858 MVT::v16i8, pshufbMask));
6860 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6861 // the 2nd operand if it's undefined or zero.
6862 if (V2.getOpcode() == ISD::UNDEF ||
6863 ISD::isBuildVectorAllZeros(V2.getNode()))
6866 // Calculate the shuffle mask for the second input, shuffle it, and
6867 // OR it with the first shuffled input.
6869 for (unsigned i = 0; i != 16; ++i) {
6870 int EltIdx = MaskVals[i];
6871 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6872 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6874 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6875 DAG.getNode(ISD::BUILD_VECTOR, dl,
6876 MVT::v16i8, pshufbMask));
6877 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6880 // No SSSE3 - Calculate in place words and then fix all out of place words
6881 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6882 // the 16 different words that comprise the two doublequadword input vectors.
6883 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6884 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6886 for (int i = 0; i != 8; ++i) {
6887 int Elt0 = MaskVals[i*2];
6888 int Elt1 = MaskVals[i*2+1];
6890 // This word of the result is all undef, skip it.
6891 if (Elt0 < 0 && Elt1 < 0)
6894 // This word of the result is already in the correct place, skip it.
6895 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6898 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6899 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6902 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6903 // using a single extract together, load it and store it.
6904 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6905 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6906 DAG.getIntPtrConstant(Elt1 / 2));
6907 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6908 DAG.getIntPtrConstant(i));
6912 // If Elt1 is defined, extract it from the appropriate source. If the
6913 // source byte is not also odd, shift the extracted word left 8 bits
6914 // otherwise clear the bottom 8 bits if we need to do an or.
6916 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6917 DAG.getIntPtrConstant(Elt1 / 2));
6918 if ((Elt1 & 1) == 0)
6919 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6921 TLI.getShiftAmountTy(InsElt.getValueType())));
6923 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6924 DAG.getConstant(0xFF00, MVT::i16));
6926 // If Elt0 is defined, extract it from the appropriate source. If the
6927 // source byte is not also even, shift the extracted word right 8 bits. If
6928 // Elt1 was also defined, OR the extracted values together before
6929 // inserting them in the result.
6931 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6932 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6933 if ((Elt0 & 1) != 0)
6934 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6936 TLI.getShiftAmountTy(InsElt0.getValueType())));
6938 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6939 DAG.getConstant(0x00FF, MVT::i16));
6940 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6943 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6944 DAG.getIntPtrConstant(i));
6946 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6949 // v32i8 shuffles - Translate to VPSHUFB if possible.
6951 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6952 const X86Subtarget *Subtarget,
6953 SelectionDAG &DAG) {
6954 MVT VT = SVOp->getSimpleValueType(0);
6955 SDValue V1 = SVOp->getOperand(0);
6956 SDValue V2 = SVOp->getOperand(1);
6958 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6960 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6961 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6962 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6964 // VPSHUFB may be generated if
6965 // (1) one of input vector is undefined or zeroinitializer.
6966 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6967 // And (2) the mask indexes don't cross the 128-bit lane.
6968 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6969 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6972 if (V1IsAllZero && !V2IsAllZero) {
6973 CommuteVectorShuffleMask(MaskVals, 32);
6976 return getPSHUFB(MaskVals, V1, dl, DAG);
6979 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6980 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6981 /// done when every pair / quad of shuffle mask elements point to elements in
6982 /// the right sequence. e.g.
6983 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6985 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6986 SelectionDAG &DAG) {
6987 MVT VT = SVOp->getSimpleValueType(0);
6989 unsigned NumElems = VT.getVectorNumElements();
6992 switch (VT.SimpleTy) {
6993 default: llvm_unreachable("Unexpected!");
6996 return SDValue(SVOp, 0);
6997 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6998 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6999 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
7000 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
7001 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7002 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
7005 SmallVector<int, 8> MaskVec;
7006 for (unsigned i = 0; i != NumElems; i += Scale) {
7008 for (unsigned j = 0; j != Scale; ++j) {
7009 int EltIdx = SVOp->getMaskElt(i+j);
7013 StartIdx = (EltIdx / Scale);
7014 if (EltIdx != (int)(StartIdx*Scale + j))
7017 MaskVec.push_back(StartIdx);
7020 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7021 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7022 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7025 /// getVZextMovL - Return a zero-extending vector move low node.
7027 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7028 SDValue SrcOp, SelectionDAG &DAG,
7029 const X86Subtarget *Subtarget, SDLoc dl) {
7030 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7031 LoadSDNode *LD = nullptr;
7032 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7033 LD = dyn_cast<LoadSDNode>(SrcOp);
7035 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7037 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7038 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7039 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7040 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7041 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7043 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7044 return DAG.getNode(ISD::BITCAST, dl, VT,
7045 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7046 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7054 return DAG.getNode(ISD::BITCAST, dl, VT,
7055 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7056 DAG.getNode(ISD::BITCAST, dl,
7060 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7061 /// which could not be matched by any known target speficic shuffle
7063 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7065 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7066 if (NewOp.getNode())
7069 MVT VT = SVOp->getSimpleValueType(0);
7071 unsigned NumElems = VT.getVectorNumElements();
7072 unsigned NumLaneElems = NumElems / 2;
7075 MVT EltVT = VT.getVectorElementType();
7076 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7079 SmallVector<int, 16> Mask;
7080 for (unsigned l = 0; l < 2; ++l) {
7081 // Build a shuffle mask for the output, discovering on the fly which
7082 // input vectors to use as shuffle operands (recorded in InputUsed).
7083 // If building a suitable shuffle vector proves too hard, then bail
7084 // out with UseBuildVector set.
7085 bool UseBuildVector = false;
7086 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7087 unsigned LaneStart = l * NumLaneElems;
7088 for (unsigned i = 0; i != NumLaneElems; ++i) {
7089 // The mask element. This indexes into the input.
7090 int Idx = SVOp->getMaskElt(i+LaneStart);
7092 // the mask element does not index into any input vector.
7097 // The input vector this mask element indexes into.
7098 int Input = Idx / NumLaneElems;
7100 // Turn the index into an offset from the start of the input vector.
7101 Idx -= Input * NumLaneElems;
7103 // Find or create a shuffle vector operand to hold this input.
7105 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7106 if (InputUsed[OpNo] == Input)
7107 // This input vector is already an operand.
7109 if (InputUsed[OpNo] < 0) {
7110 // Create a new operand for this input vector.
7111 InputUsed[OpNo] = Input;
7116 if (OpNo >= array_lengthof(InputUsed)) {
7117 // More than two input vectors used! Give up on trying to create a
7118 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
7119 UseBuildVector = true;
7123 // Add the mask index for the new shuffle vector.
7124 Mask.push_back(Idx + OpNo * NumLaneElems);
7127 if (UseBuildVector) {
7128 SmallVector<SDValue, 16> SVOps;
7129 for (unsigned i = 0; i != NumLaneElems; ++i) {
7130 // The mask element. This indexes into the input.
7131 int Idx = SVOp->getMaskElt(i+LaneStart);
7133 SVOps.push_back(DAG.getUNDEF(EltVT));
7137 // The input vector this mask element indexes into.
7138 int Input = Idx / NumElems;
7140 // Turn the index into an offset from the start of the input vector.
7141 Idx -= Input * NumElems;
7143 // Extract the vector element by hand.
7144 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7145 SVOp->getOperand(Input),
7146 DAG.getIntPtrConstant(Idx)));
7149 // Construct the output using a BUILD_VECTOR.
7150 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7151 } else if (InputUsed[0] < 0) {
7152 // No input vectors were used! The result is undefined.
7153 Output[l] = DAG.getUNDEF(NVT);
7155 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7156 (InputUsed[0] % 2) * NumLaneElems,
7158 // If only one input was used, use an undefined vector for the other.
7159 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7160 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7161 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7162 // At least one input vector was used. Create a new shuffle vector.
7163 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7169 // Concatenate the result back
7170 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7173 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7174 /// 4 elements, and match them with several different shuffle types.
7176 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7177 SDValue V1 = SVOp->getOperand(0);
7178 SDValue V2 = SVOp->getOperand(1);
7180 MVT VT = SVOp->getSimpleValueType(0);
7182 assert(VT.is128BitVector() && "Unsupported vector size");
7184 std::pair<int, int> Locs[4];
7185 int Mask1[] = { -1, -1, -1, -1 };
7186 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7190 for (unsigned i = 0; i != 4; ++i) {
7191 int Idx = PermMask[i];
7193 Locs[i] = std::make_pair(-1, -1);
7195 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7197 Locs[i] = std::make_pair(0, NumLo);
7201 Locs[i] = std::make_pair(1, NumHi);
7203 Mask1[2+NumHi] = Idx;
7209 if (NumLo <= 2 && NumHi <= 2) {
7210 // If no more than two elements come from either vector. This can be
7211 // implemented with two shuffles. First shuffle gather the elements.
7212 // The second shuffle, which takes the first shuffle as both of its
7213 // vector operands, put the elements into the right order.
7214 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7216 int Mask2[] = { -1, -1, -1, -1 };
7218 for (unsigned i = 0; i != 4; ++i)
7219 if (Locs[i].first != -1) {
7220 unsigned Idx = (i < 2) ? 0 : 4;
7221 Idx += Locs[i].first * 2 + Locs[i].second;
7225 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7228 if (NumLo == 3 || NumHi == 3) {
7229 // Otherwise, we must have three elements from one vector, call it X, and
7230 // one element from the other, call it Y. First, use a shufps to build an
7231 // intermediate vector with the one element from Y and the element from X
7232 // that will be in the same half in the final destination (the indexes don't
7233 // matter). Then, use a shufps to build the final vector, taking the half
7234 // containing the element from Y from the intermediate, and the other half
7237 // Normalize it so the 3 elements come from V1.
7238 CommuteVectorShuffleMask(PermMask, 4);
7242 // Find the element from V2.
7244 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7245 int Val = PermMask[HiIndex];
7252 Mask1[0] = PermMask[HiIndex];
7254 Mask1[2] = PermMask[HiIndex^1];
7256 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7259 Mask1[0] = PermMask[0];
7260 Mask1[1] = PermMask[1];
7261 Mask1[2] = HiIndex & 1 ? 6 : 4;
7262 Mask1[3] = HiIndex & 1 ? 4 : 6;
7263 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7266 Mask1[0] = HiIndex & 1 ? 2 : 0;
7267 Mask1[1] = HiIndex & 1 ? 0 : 2;
7268 Mask1[2] = PermMask[2];
7269 Mask1[3] = PermMask[3];
7274 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7277 // Break it into (shuffle shuffle_hi, shuffle_lo).
7278 int LoMask[] = { -1, -1, -1, -1 };
7279 int HiMask[] = { -1, -1, -1, -1 };
7281 int *MaskPtr = LoMask;
7282 unsigned MaskIdx = 0;
7285 for (unsigned i = 0; i != 4; ++i) {
7292 int Idx = PermMask[i];
7294 Locs[i] = std::make_pair(-1, -1);
7295 } else if (Idx < 4) {
7296 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7297 MaskPtr[LoIdx] = Idx;
7300 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7301 MaskPtr[HiIdx] = Idx;
7306 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7307 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7308 int MaskOps[] = { -1, -1, -1, -1 };
7309 for (unsigned i = 0; i != 4; ++i)
7310 if (Locs[i].first != -1)
7311 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7312 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7315 static bool MayFoldVectorLoad(SDValue V) {
7316 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7317 V = V.getOperand(0);
7319 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7320 V = V.getOperand(0);
7321 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7322 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7323 // BUILD_VECTOR (load), undef
7324 V = V.getOperand(0);
7326 return MayFoldLoad(V);
7330 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7331 MVT VT = Op.getSimpleValueType();
7333 // Canonizalize to v2f64.
7334 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7335 return DAG.getNode(ISD::BITCAST, dl, VT,
7336 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7341 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7343 SDValue V1 = Op.getOperand(0);
7344 SDValue V2 = Op.getOperand(1);
7345 MVT VT = Op.getSimpleValueType();
7347 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7349 if (HasSSE2 && VT == MVT::v2f64)
7350 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7352 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7353 return DAG.getNode(ISD::BITCAST, dl, VT,
7354 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7355 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7356 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7360 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7361 SDValue V1 = Op.getOperand(0);
7362 SDValue V2 = Op.getOperand(1);
7363 MVT VT = Op.getSimpleValueType();
7365 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7366 "unsupported shuffle type");
7368 if (V2.getOpcode() == ISD::UNDEF)
7372 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7376 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7377 SDValue V1 = Op.getOperand(0);
7378 SDValue V2 = Op.getOperand(1);
7379 MVT VT = Op.getSimpleValueType();
7380 unsigned NumElems = VT.getVectorNumElements();
7382 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7383 // operand of these instructions is only memory, so check if there's a
7384 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7386 bool CanFoldLoad = false;
7388 // Trivial case, when V2 comes from a load.
7389 if (MayFoldVectorLoad(V2))
7392 // When V1 is a load, it can be folded later into a store in isel, example:
7393 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7395 // (MOVLPSmr addr:$src1, VR128:$src2)
7396 // So, recognize this potential and also use MOVLPS or MOVLPD
7397 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7400 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7402 if (HasSSE2 && NumElems == 2)
7403 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7406 // If we don't care about the second element, proceed to use movss.
7407 if (SVOp->getMaskElt(1) != -1)
7408 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7411 // movl and movlp will both match v2i64, but v2i64 is never matched by
7412 // movl earlier because we make it strict to avoid messing with the movlp load
7413 // folding logic (see the code above getMOVLP call). Match it here then,
7414 // this is horrible, but will stay like this until we move all shuffle
7415 // matching to x86 specific nodes. Note that for the 1st condition all
7416 // types are matched with movsd.
7418 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7419 // as to remove this logic from here, as much as possible
7420 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7421 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7422 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7425 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7427 // Invert the operand order and use SHUFPS to match it.
7428 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7429 getShuffleSHUFImmediate(SVOp), DAG);
7432 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7433 SelectionDAG &DAG) {
7435 MVT VT = Load->getSimpleValueType(0);
7436 MVT EVT = VT.getVectorElementType();
7437 SDValue Addr = Load->getOperand(1);
7438 SDValue NewAddr = DAG.getNode(
7439 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7440 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7443 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7444 DAG.getMachineFunction().getMachineMemOperand(
7445 Load->getMemOperand(), 0, EVT.getStoreSize()));
7449 // It is only safe to call this function if isINSERTPSMask is true for
7450 // this shufflevector mask.
7451 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7452 SelectionDAG &DAG) {
7453 // Generate an insertps instruction when inserting an f32 from memory onto a
7454 // v4f32 or when copying a member from one v4f32 to another.
7455 // We also use it for transferring i32 from one register to another,
7456 // since it simply copies the same bits.
7457 // If we're transferring an i32 from memory to a specific element in a
7458 // register, we output a generic DAG that will match the PINSRD
7460 MVT VT = SVOp->getSimpleValueType(0);
7461 MVT EVT = VT.getVectorElementType();
7462 SDValue V1 = SVOp->getOperand(0);
7463 SDValue V2 = SVOp->getOperand(1);
7464 auto Mask = SVOp->getMask();
7465 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7466 "unsupported vector type for insertps/pinsrd");
7468 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7469 [](const int &i) { return i < 4; });
7477 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7478 [](const int &i) { return i < 4; }) -
7483 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7484 [](const int &i) { return i >= 4; }) -
7488 if (MayFoldLoad(From)) {
7489 // Trivial case, when From comes from a load and is only used by the
7490 // shuffle. Make it use insertps from the vector that we need from that
7493 NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7494 if (!NewLoad.getNode())
7497 if (EVT == MVT::f32) {
7498 // Create this as a scalar to vector to match the instruction pattern.
7499 SDValue LoadScalarToVector =
7500 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7501 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7502 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7504 } else { // EVT == MVT::i32
7505 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7506 // instruction, to match the PINSRD instruction, which loads an i32 to a
7507 // certain vector element.
7508 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7509 DAG.getConstant(DestIndex, MVT::i32));
7513 // Vector-element-to-vector
7514 unsigned SrcIndex = Mask[DestIndex] % 4;
7515 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7516 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7519 // Reduce a vector shuffle to zext.
7520 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7521 SelectionDAG &DAG) {
7522 // PMOVZX is only available from SSE41.
7523 if (!Subtarget->hasSSE41())
7526 MVT VT = Op.getSimpleValueType();
7528 // Only AVX2 support 256-bit vector integer extending.
7529 if (!Subtarget->hasInt256() && VT.is256BitVector())
7532 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7534 SDValue V1 = Op.getOperand(0);
7535 SDValue V2 = Op.getOperand(1);
7536 unsigned NumElems = VT.getVectorNumElements();
7538 // Extending is an unary operation and the element type of the source vector
7539 // won't be equal to or larger than i64.
7540 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7541 VT.getVectorElementType() == MVT::i64)
7544 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7545 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7546 while ((1U << Shift) < NumElems) {
7547 if (SVOp->getMaskElt(1U << Shift) == 1)
7550 // The maximal ratio is 8, i.e. from i8 to i64.
7555 // Check the shuffle mask.
7556 unsigned Mask = (1U << Shift) - 1;
7557 for (unsigned i = 0; i != NumElems; ++i) {
7558 int EltIdx = SVOp->getMaskElt(i);
7559 if ((i & Mask) != 0 && EltIdx != -1)
7561 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7565 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7566 MVT NeVT = MVT::getIntegerVT(NBits);
7567 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7569 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7572 // Simplify the operand as it's prepared to be fed into shuffle.
7573 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7574 if (V1.getOpcode() == ISD::BITCAST &&
7575 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7576 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7577 V1.getOperand(0).getOperand(0)
7578 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7579 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7580 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7581 ConstantSDNode *CIdx =
7582 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7583 // If it's foldable, i.e. normal load with single use, we will let code
7584 // selection to fold it. Otherwise, we will short the conversion sequence.
7585 if (CIdx && CIdx->getZExtValue() == 0 &&
7586 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7587 MVT FullVT = V.getSimpleValueType();
7588 MVT V1VT = V1.getSimpleValueType();
7589 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7590 // The "ext_vec_elt" node is wider than the result node.
7591 // In this case we should extract subvector from V.
7592 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7593 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7594 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7595 FullVT.getVectorNumElements()/Ratio);
7596 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7597 DAG.getIntPtrConstant(0));
7599 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7603 return DAG.getNode(ISD::BITCAST, DL, VT,
7604 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7607 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7608 SelectionDAG &DAG) {
7609 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7610 MVT VT = Op.getSimpleValueType();
7612 SDValue V1 = Op.getOperand(0);
7613 SDValue V2 = Op.getOperand(1);
7615 if (isZeroShuffle(SVOp))
7616 return getZeroVector(VT, Subtarget, DAG, dl);
7618 // Handle splat operations
7619 if (SVOp->isSplat()) {
7620 // Use vbroadcast whenever the splat comes from a foldable load
7621 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7622 if (Broadcast.getNode())
7626 // Check integer expanding shuffles.
7627 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7628 if (NewOp.getNode())
7631 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7633 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7635 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7636 if (NewOp.getNode())
7637 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7638 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7639 // FIXME: Figure out a cleaner way to do this.
7640 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7641 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7642 if (NewOp.getNode()) {
7643 MVT NewVT = NewOp.getSimpleValueType();
7644 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7645 NewVT, true, false))
7646 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7649 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7650 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7651 if (NewOp.getNode()) {
7652 MVT NewVT = NewOp.getSimpleValueType();
7653 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7654 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7663 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7664 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7665 SDValue V1 = Op.getOperand(0);
7666 SDValue V2 = Op.getOperand(1);
7667 MVT VT = Op.getSimpleValueType();
7669 unsigned NumElems = VT.getVectorNumElements();
7670 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7671 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7672 bool V1IsSplat = false;
7673 bool V2IsSplat = false;
7674 bool HasSSE2 = Subtarget->hasSSE2();
7675 bool HasFp256 = Subtarget->hasFp256();
7676 bool HasInt256 = Subtarget->hasInt256();
7677 MachineFunction &MF = DAG.getMachineFunction();
7678 bool OptForSize = MF.getFunction()->getAttributes().
7679 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7681 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7683 if (V1IsUndef && V2IsUndef)
7684 return DAG.getUNDEF(VT);
7686 // When we create a shuffle node we put the UNDEF node to second operand,
7687 // but in some cases the first operand may be transformed to UNDEF.
7688 // In this case we should just commute the node.
7690 return CommuteVectorShuffle(SVOp, DAG);
7692 // Vector shuffle lowering takes 3 steps:
7694 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7695 // narrowing and commutation of operands should be handled.
7696 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7698 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7699 // so the shuffle can be broken into other shuffles and the legalizer can
7700 // try the lowering again.
7702 // The general idea is that no vector_shuffle operation should be left to
7703 // be matched during isel, all of them must be converted to a target specific
7706 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7707 // narrowing and commutation of operands should be handled. The actual code
7708 // doesn't include all of those, work in progress...
7709 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7710 if (NewOp.getNode())
7713 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7715 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7716 // unpckh_undef). Only use pshufd if speed is more important than size.
7717 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7718 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7719 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7720 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7722 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7723 V2IsUndef && MayFoldVectorLoad(V1))
7724 return getMOVDDup(Op, dl, V1, DAG);
7726 if (isMOVHLPS_v_undef_Mask(M, VT))
7727 return getMOVHighToLow(Op, dl, DAG);
7729 // Use to match splats
7730 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7731 (VT == MVT::v2f64 || VT == MVT::v2i64))
7732 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7734 if (isPSHUFDMask(M, VT)) {
7735 // The actual implementation will match the mask in the if above and then
7736 // during isel it can match several different instructions, not only pshufd
7737 // as its name says, sad but true, emulate the behavior for now...
7738 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7739 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7741 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7743 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7744 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7746 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7747 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7750 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7754 if (isPALIGNRMask(M, VT, Subtarget))
7755 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7756 getShufflePALIGNRImmediate(SVOp),
7759 // Check if this can be converted into a logical shift.
7760 bool isLeft = false;
7763 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7764 if (isShift && ShVal.hasOneUse()) {
7765 // If the shifted value has multiple uses, it may be cheaper to use
7766 // v_set0 + movlhps or movhlps, etc.
7767 MVT EltVT = VT.getVectorElementType();
7768 ShAmt *= EltVT.getSizeInBits();
7769 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7772 if (isMOVLMask(M, VT)) {
7773 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7774 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7775 if (!isMOVLPMask(M, VT)) {
7776 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7777 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7779 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7780 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7784 // FIXME: fold these into legal mask.
7785 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7786 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7788 if (isMOVHLPSMask(M, VT))
7789 return getMOVHighToLow(Op, dl, DAG);
7791 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7792 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7794 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7795 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7797 if (isMOVLPMask(M, VT))
7798 return getMOVLP(Op, dl, DAG, HasSSE2);
7800 if (ShouldXformToMOVHLPS(M, VT) ||
7801 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7802 return CommuteVectorShuffle(SVOp, DAG);
7805 // No better options. Use a vshldq / vsrldq.
7806 MVT EltVT = VT.getVectorElementType();
7807 ShAmt *= EltVT.getSizeInBits();
7808 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7811 bool Commuted = false;
7812 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7813 // 1,1,1,1 -> v8i16 though.
7814 V1IsSplat = isSplatVector(V1.getNode());
7815 V2IsSplat = isSplatVector(V2.getNode());
7817 // Canonicalize the splat or undef, if present, to be on the RHS.
7818 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7819 CommuteVectorShuffleMask(M, NumElems);
7821 std::swap(V1IsSplat, V2IsSplat);
7825 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7826 // Shuffling low element of v1 into undef, just return v1.
7829 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7830 // the instruction selector will not match, so get a canonical MOVL with
7831 // swapped operands to undo the commute.
7832 return getMOVL(DAG, dl, VT, V2, V1);
7835 if (isUNPCKLMask(M, VT, HasInt256))
7836 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7838 if (isUNPCKHMask(M, VT, HasInt256))
7839 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7842 // Normalize mask so all entries that point to V2 points to its first
7843 // element then try to match unpck{h|l} again. If match, return a
7844 // new vector_shuffle with the corrected mask.p
7845 SmallVector<int, 8> NewMask(M.begin(), M.end());
7846 NormalizeMask(NewMask, NumElems);
7847 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7848 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7849 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7850 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7854 // Commute is back and try unpck* again.
7855 // FIXME: this seems wrong.
7856 CommuteVectorShuffleMask(M, NumElems);
7858 std::swap(V1IsSplat, V2IsSplat);
7860 if (isUNPCKLMask(M, VT, HasInt256))
7861 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7863 if (isUNPCKHMask(M, VT, HasInt256))
7864 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7867 // Normalize the node to match x86 shuffle ops if needed
7868 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7869 return CommuteVectorShuffle(SVOp, DAG);
7871 // The checks below are all present in isShuffleMaskLegal, but they are
7872 // inlined here right now to enable us to directly emit target specific
7873 // nodes, and remove one by one until they don't return Op anymore.
7875 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7876 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7877 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7878 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7881 if (isPSHUFHWMask(M, VT, HasInt256))
7882 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7883 getShufflePSHUFHWImmediate(SVOp),
7886 if (isPSHUFLWMask(M, VT, HasInt256))
7887 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7888 getShufflePSHUFLWImmediate(SVOp),
7891 if (isSHUFPMask(M, VT))
7892 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7893 getShuffleSHUFImmediate(SVOp), DAG);
7895 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7896 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7897 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7898 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7900 //===--------------------------------------------------------------------===//
7901 // Generate target specific nodes for 128 or 256-bit shuffles only
7902 // supported in the AVX instruction set.
7905 // Handle VMOVDDUPY permutations
7906 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7907 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7909 // Handle VPERMILPS/D* permutations
7910 if (isVPERMILPMask(M, VT)) {
7911 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7912 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7913 getShuffleSHUFImmediate(SVOp), DAG);
7914 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7915 getShuffleSHUFImmediate(SVOp), DAG);
7919 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7920 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7921 Idx*(NumElems/2), DAG, dl);
7923 // Handle VPERM2F128/VPERM2I128 permutations
7924 if (isVPERM2X128Mask(M, VT, HasFp256))
7925 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7926 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7929 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
7931 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
7933 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7934 return getINSERTPS(SVOp, dl, DAG);
7937 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7938 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7940 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7941 VT.is512BitVector()) {
7942 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7943 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7944 SmallVector<SDValue, 16> permclMask;
7945 for (unsigned i = 0; i != NumElems; ++i) {
7946 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7949 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7951 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7952 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7953 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7954 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7955 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7958 //===--------------------------------------------------------------------===//
7959 // Since no target specific shuffle was selected for this generic one,
7960 // lower it into other known shuffles. FIXME: this isn't true yet, but
7961 // this is the plan.
7964 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7965 if (VT == MVT::v8i16) {
7966 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7967 if (NewOp.getNode())
7971 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7972 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7973 if (NewOp.getNode())
7977 if (VT == MVT::v16i8) {
7978 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7979 if (NewOp.getNode())
7983 if (VT == MVT::v32i8) {
7984 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7985 if (NewOp.getNode())
7989 // Handle all 128-bit wide vectors with 4 elements, and match them with
7990 // several different shuffle types.
7991 if (NumElems == 4 && VT.is128BitVector())
7992 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7994 // Handle general 256-bit shuffles
7995 if (VT.is256BitVector())
7996 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8001 // This function assumes its argument is a BUILD_VECTOR of constants or
8002 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8004 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8005 unsigned &MaskValue) {
8007 unsigned NumElems = BuildVector->getNumOperands();
8008 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8009 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8010 unsigned NumElemsInLane = NumElems / NumLanes;
8012 // Blend for v16i16 should be symetric for the both lanes.
8013 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8014 SDValue EltCond = BuildVector->getOperand(i);
8015 SDValue SndLaneEltCond =
8016 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8018 int Lane1Cond = -1, Lane2Cond = -1;
8019 if (isa<ConstantSDNode>(EltCond))
8020 Lane1Cond = !isZero(EltCond);
8021 if (isa<ConstantSDNode>(SndLaneEltCond))
8022 Lane2Cond = !isZero(SndLaneEltCond);
8024 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8025 // Lane1Cond != 0, means we want the first argument.
8026 // Lane1Cond == 0, means we want the second argument.
8027 // The encoding of this argument is 0 for the first argument, 1
8028 // for the second. Therefore, invert the condition.
8029 MaskValue |= !Lane1Cond << i;
8030 else if (Lane1Cond < 0)
8031 MaskValue |= !Lane2Cond << i;
8038 // Try to lower a vselect node into a simple blend instruction.
8039 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8040 SelectionDAG &DAG) {
8041 SDValue Cond = Op.getOperand(0);
8042 SDValue LHS = Op.getOperand(1);
8043 SDValue RHS = Op.getOperand(2);
8045 MVT VT = Op.getSimpleValueType();
8046 MVT EltVT = VT.getVectorElementType();
8047 unsigned NumElems = VT.getVectorNumElements();
8049 // There is no blend with immediate in AVX-512.
8050 if (VT.is512BitVector())
8053 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8055 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8058 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8061 // Check the mask for BLEND and build the value.
8062 unsigned MaskValue = 0;
8063 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8066 // Convert i32 vectors to floating point if it is not AVX2.
8067 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8069 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8070 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8072 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8073 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8076 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8077 DAG.getConstant(MaskValue, MVT::i32));
8078 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8081 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8082 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8083 if (BlendOp.getNode())
8086 // Some types for vselect were previously set to Expand, not Legal or
8087 // Custom. Return an empty SDValue so we fall-through to Expand, after
8088 // the Custom lowering phase.
8089 MVT VT = Op.getSimpleValueType();
8090 switch (VT.SimpleTy) {
8098 // We couldn't create a "Blend with immediate" node.
8099 // This node should still be legal, but we'll have to emit a blendv*
8104 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8105 MVT VT = Op.getSimpleValueType();
8108 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8111 if (VT.getSizeInBits() == 8) {
8112 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8113 Op.getOperand(0), Op.getOperand(1));
8114 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8115 DAG.getValueType(VT));
8116 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8119 if (VT.getSizeInBits() == 16) {
8120 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8121 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8123 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8124 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8125 DAG.getNode(ISD::BITCAST, dl,
8129 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8130 Op.getOperand(0), Op.getOperand(1));
8131 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8132 DAG.getValueType(VT));
8133 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8136 if (VT == MVT::f32) {
8137 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8138 // the result back to FR32 register. It's only worth matching if the
8139 // result has a single use which is a store or a bitcast to i32. And in
8140 // the case of a store, it's not worth it if the index is a constant 0,
8141 // because a MOVSSmr can be used instead, which is smaller and faster.
8142 if (!Op.hasOneUse())
8144 SDNode *User = *Op.getNode()->use_begin();
8145 if ((User->getOpcode() != ISD::STORE ||
8146 (isa<ConstantSDNode>(Op.getOperand(1)) &&
8147 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8148 (User->getOpcode() != ISD::BITCAST ||
8149 User->getValueType(0) != MVT::i32))
8151 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8152 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8155 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8158 if (VT == MVT::i32 || VT == MVT::i64) {
8159 // ExtractPS/pextrq works with constant index.
8160 if (isa<ConstantSDNode>(Op.getOperand(1)))
8166 /// Extract one bit from mask vector, like v16i1 or v8i1.
8167 /// AVX-512 feature.
8169 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8170 SDValue Vec = Op.getOperand(0);
8172 MVT VecVT = Vec.getSimpleValueType();
8173 SDValue Idx = Op.getOperand(1);
8174 MVT EltVT = Op.getSimpleValueType();
8176 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8178 // variable index can't be handled in mask registers,
8179 // extend vector to VR512
8180 if (!isa<ConstantSDNode>(Idx)) {
8181 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8182 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8183 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8184 ExtVT.getVectorElementType(), Ext, Idx);
8185 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8188 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8189 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8190 unsigned MaxSift = rc->getSize()*8 - 1;
8191 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8192 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8193 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8194 DAG.getConstant(MaxSift, MVT::i8));
8195 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8196 DAG.getIntPtrConstant(0));
8200 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8201 SelectionDAG &DAG) const {
8203 SDValue Vec = Op.getOperand(0);
8204 MVT VecVT = Vec.getSimpleValueType();
8205 SDValue Idx = Op.getOperand(1);
8207 if (Op.getSimpleValueType() == MVT::i1)
8208 return ExtractBitFromMaskVector(Op, DAG);
8210 if (!isa<ConstantSDNode>(Idx)) {
8211 if (VecVT.is512BitVector() ||
8212 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8213 VecVT.getVectorElementType().getSizeInBits() == 32)) {
8216 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8217 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8218 MaskEltVT.getSizeInBits());
8220 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8221 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8222 getZeroVector(MaskVT, Subtarget, DAG, dl),
8223 Idx, DAG.getConstant(0, getPointerTy()));
8224 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8225 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8226 Perm, DAG.getConstant(0, getPointerTy()));
8231 // If this is a 256-bit vector result, first extract the 128-bit vector and
8232 // then extract the element from the 128-bit vector.
8233 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8235 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8236 // Get the 128-bit vector.
8237 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8238 MVT EltVT = VecVT.getVectorElementType();
8240 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8242 //if (IdxVal >= NumElems/2)
8243 // IdxVal -= NumElems/2;
8244 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8245 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8246 DAG.getConstant(IdxVal, MVT::i32));
8249 assert(VecVT.is128BitVector() && "Unexpected vector length");
8251 if (Subtarget->hasSSE41()) {
8252 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8257 MVT VT = Op.getSimpleValueType();
8258 // TODO: handle v16i8.
8259 if (VT.getSizeInBits() == 16) {
8260 SDValue Vec = Op.getOperand(0);
8261 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8263 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8264 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8265 DAG.getNode(ISD::BITCAST, dl,
8268 // Transform it so it match pextrw which produces a 32-bit result.
8269 MVT EltVT = MVT::i32;
8270 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8271 Op.getOperand(0), Op.getOperand(1));
8272 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8273 DAG.getValueType(VT));
8274 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8277 if (VT.getSizeInBits() == 32) {
8278 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8282 // SHUFPS the element to the lowest double word, then movss.
8283 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8284 MVT VVT = Op.getOperand(0).getSimpleValueType();
8285 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8286 DAG.getUNDEF(VVT), Mask);
8287 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8288 DAG.getIntPtrConstant(0));
8291 if (VT.getSizeInBits() == 64) {
8292 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8293 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8294 // to match extract_elt for f64.
8295 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8299 // UNPCKHPD the element to the lowest double word, then movsd.
8300 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8301 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8302 int Mask[2] = { 1, -1 };
8303 MVT VVT = Op.getOperand(0).getSimpleValueType();
8304 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8305 DAG.getUNDEF(VVT), Mask);
8306 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8307 DAG.getIntPtrConstant(0));
8313 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8314 MVT VT = Op.getSimpleValueType();
8315 MVT EltVT = VT.getVectorElementType();
8318 SDValue N0 = Op.getOperand(0);
8319 SDValue N1 = Op.getOperand(1);
8320 SDValue N2 = Op.getOperand(2);
8322 if (!VT.is128BitVector())
8325 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8326 isa<ConstantSDNode>(N2)) {
8328 if (VT == MVT::v8i16)
8329 Opc = X86ISD::PINSRW;
8330 else if (VT == MVT::v16i8)
8331 Opc = X86ISD::PINSRB;
8333 Opc = X86ISD::PINSRB;
8335 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8337 if (N1.getValueType() != MVT::i32)
8338 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8339 if (N2.getValueType() != MVT::i32)
8340 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8341 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8344 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8345 // Bits [7:6] of the constant are the source select. This will always be
8346 // zero here. The DAG Combiner may combine an extract_elt index into these
8347 // bits. For example (insert (extract, 3), 2) could be matched by putting
8348 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8349 // Bits [5:4] of the constant are the destination select. This is the
8350 // value of the incoming immediate.
8351 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8352 // combine either bitwise AND or insert of float 0.0 to set these bits.
8353 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8354 // Create this as a scalar to vector..
8355 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8356 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8359 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8360 // PINSR* works with constant index.
8366 /// Insert one bit to mask vector, like v16i1 or v8i1.
8367 /// AVX-512 feature.
8369 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8371 SDValue Vec = Op.getOperand(0);
8372 SDValue Elt = Op.getOperand(1);
8373 SDValue Idx = Op.getOperand(2);
8374 MVT VecVT = Vec.getSimpleValueType();
8376 if (!isa<ConstantSDNode>(Idx)) {
8377 // Non constant index. Extend source and destination,
8378 // insert element and then truncate the result.
8379 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8380 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8381 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8382 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8383 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8384 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8387 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8388 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8389 if (Vec.getOpcode() == ISD::UNDEF)
8390 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8391 DAG.getConstant(IdxVal, MVT::i8));
8392 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8393 unsigned MaxSift = rc->getSize()*8 - 1;
8394 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8395 DAG.getConstant(MaxSift, MVT::i8));
8396 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8397 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8398 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8401 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8402 MVT VT = Op.getSimpleValueType();
8403 MVT EltVT = VT.getVectorElementType();
8405 if (EltVT == MVT::i1)
8406 return InsertBitToMaskVector(Op, DAG);
8409 SDValue N0 = Op.getOperand(0);
8410 SDValue N1 = Op.getOperand(1);
8411 SDValue N2 = Op.getOperand(2);
8413 // If this is a 256-bit vector result, first extract the 128-bit vector,
8414 // insert the element into the extracted half and then place it back.
8415 if (VT.is256BitVector() || VT.is512BitVector()) {
8416 if (!isa<ConstantSDNode>(N2))
8419 // Get the desired 128-bit vector half.
8420 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8421 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8423 // Insert the element into the desired half.
8424 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8425 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8427 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8428 DAG.getConstant(IdxIn128, MVT::i32));
8430 // Insert the changed part back to the 256-bit vector
8431 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8434 if (Subtarget->hasSSE41())
8435 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8437 if (EltVT == MVT::i8)
8440 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8441 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8442 // as its second argument.
8443 if (N1.getValueType() != MVT::i32)
8444 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8445 if (N2.getValueType() != MVT::i32)
8446 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8447 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8452 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8454 MVT OpVT = Op.getSimpleValueType();
8456 // If this is a 256-bit vector result, first insert into a 128-bit
8457 // vector and then insert into the 256-bit vector.
8458 if (!OpVT.is128BitVector()) {
8459 // Insert into a 128-bit vector.
8460 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8461 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8462 OpVT.getVectorNumElements() / SizeFactor);
8464 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8466 // Insert the 128-bit vector.
8467 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8470 if (OpVT == MVT::v1i64 &&
8471 Op.getOperand(0).getValueType() == MVT::i64)
8472 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8474 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8475 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8476 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8477 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8480 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8481 // a simple subregister reference or explicit instructions to grab
8482 // upper bits of a vector.
8483 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8484 SelectionDAG &DAG) {
8486 SDValue In = Op.getOperand(0);
8487 SDValue Idx = Op.getOperand(1);
8488 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8489 MVT ResVT = Op.getSimpleValueType();
8490 MVT InVT = In.getSimpleValueType();
8492 if (Subtarget->hasFp256()) {
8493 if (ResVT.is128BitVector() &&
8494 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8495 isa<ConstantSDNode>(Idx)) {
8496 return Extract128BitVector(In, IdxVal, DAG, dl);
8498 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8499 isa<ConstantSDNode>(Idx)) {
8500 return Extract256BitVector(In, IdxVal, DAG, dl);
8506 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8507 // simple superregister reference or explicit instructions to insert
8508 // the upper bits of a vector.
8509 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8510 SelectionDAG &DAG) {
8511 if (Subtarget->hasFp256()) {
8512 SDLoc dl(Op.getNode());
8513 SDValue Vec = Op.getNode()->getOperand(0);
8514 SDValue SubVec = Op.getNode()->getOperand(1);
8515 SDValue Idx = Op.getNode()->getOperand(2);
8517 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8518 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8519 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8520 isa<ConstantSDNode>(Idx)) {
8521 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8522 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8525 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8526 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8527 isa<ConstantSDNode>(Idx)) {
8528 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8529 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8535 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8536 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8537 // one of the above mentioned nodes. It has to be wrapped because otherwise
8538 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8539 // be used to form addressing mode. These wrapped nodes will be selected
8542 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8543 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8545 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8547 unsigned char OpFlag = 0;
8548 unsigned WrapperKind = X86ISD::Wrapper;
8549 CodeModel::Model M = getTargetMachine().getCodeModel();
8551 if (Subtarget->isPICStyleRIPRel() &&
8552 (M == CodeModel::Small || M == CodeModel::Kernel))
8553 WrapperKind = X86ISD::WrapperRIP;
8554 else if (Subtarget->isPICStyleGOT())
8555 OpFlag = X86II::MO_GOTOFF;
8556 else if (Subtarget->isPICStyleStubPIC())
8557 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8559 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8561 CP->getOffset(), OpFlag);
8563 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8564 // With PIC, the address is actually $g + Offset.
8566 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8567 DAG.getNode(X86ISD::GlobalBaseReg,
8568 SDLoc(), getPointerTy()),
8575 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8576 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8578 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8580 unsigned char OpFlag = 0;
8581 unsigned WrapperKind = X86ISD::Wrapper;
8582 CodeModel::Model M = getTargetMachine().getCodeModel();
8584 if (Subtarget->isPICStyleRIPRel() &&
8585 (M == CodeModel::Small || M == CodeModel::Kernel))
8586 WrapperKind = X86ISD::WrapperRIP;
8587 else if (Subtarget->isPICStyleGOT())
8588 OpFlag = X86II::MO_GOTOFF;
8589 else if (Subtarget->isPICStyleStubPIC())
8590 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8592 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8595 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8597 // With PIC, the address is actually $g + Offset.
8599 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8600 DAG.getNode(X86ISD::GlobalBaseReg,
8601 SDLoc(), getPointerTy()),
8608 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8609 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8611 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8613 unsigned char OpFlag = 0;
8614 unsigned WrapperKind = X86ISD::Wrapper;
8615 CodeModel::Model M = getTargetMachine().getCodeModel();
8617 if (Subtarget->isPICStyleRIPRel() &&
8618 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8619 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8620 OpFlag = X86II::MO_GOTPCREL;
8621 WrapperKind = X86ISD::WrapperRIP;
8622 } else if (Subtarget->isPICStyleGOT()) {
8623 OpFlag = X86II::MO_GOT;
8624 } else if (Subtarget->isPICStyleStubPIC()) {
8625 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8626 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8627 OpFlag = X86II::MO_DARWIN_NONLAZY;
8630 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8633 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8635 // With PIC, the address is actually $g + Offset.
8636 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8637 !Subtarget->is64Bit()) {
8638 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8639 DAG.getNode(X86ISD::GlobalBaseReg,
8640 SDLoc(), getPointerTy()),
8644 // For symbols that require a load from a stub to get the address, emit the
8646 if (isGlobalStubReference(OpFlag))
8647 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8648 MachinePointerInfo::getGOT(), false, false, false, 0);
8654 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8655 // Create the TargetBlockAddressAddress node.
8656 unsigned char OpFlags =
8657 Subtarget->ClassifyBlockAddressReference();
8658 CodeModel::Model M = getTargetMachine().getCodeModel();
8659 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8660 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8662 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8665 if (Subtarget->isPICStyleRIPRel() &&
8666 (M == CodeModel::Small || M == CodeModel::Kernel))
8667 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8669 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8671 // With PIC, the address is actually $g + Offset.
8672 if (isGlobalRelativeToPICBase(OpFlags)) {
8673 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8674 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8682 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8683 int64_t Offset, SelectionDAG &DAG) const {
8684 // Create the TargetGlobalAddress node, folding in the constant
8685 // offset if it is legal.
8686 unsigned char OpFlags =
8687 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8688 CodeModel::Model M = getTargetMachine().getCodeModel();
8690 if (OpFlags == X86II::MO_NO_FLAG &&
8691 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8692 // A direct static reference to a global.
8693 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8696 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8699 if (Subtarget->isPICStyleRIPRel() &&
8700 (M == CodeModel::Small || M == CodeModel::Kernel))
8701 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8703 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8705 // With PIC, the address is actually $g + Offset.
8706 if (isGlobalRelativeToPICBase(OpFlags)) {
8707 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8708 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8712 // For globals that require a load from a stub to get the address, emit the
8714 if (isGlobalStubReference(OpFlags))
8715 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8716 MachinePointerInfo::getGOT(), false, false, false, 0);
8718 // If there was a non-zero offset that we didn't fold, create an explicit
8721 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8722 DAG.getConstant(Offset, getPointerTy()));
8728 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8729 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8730 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8731 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8735 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8736 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8737 unsigned char OperandFlags, bool LocalDynamic = false) {
8738 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8739 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8741 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8742 GA->getValueType(0),
8746 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8750 SDValue Ops[] = { Chain, TGA, *InFlag };
8751 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8753 SDValue Ops[] = { Chain, TGA };
8754 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8757 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8758 MFI->setAdjustsStack(true);
8760 SDValue Flag = Chain.getValue(1);
8761 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8764 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8766 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8769 SDLoc dl(GA); // ? function entry point might be better
8770 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8771 DAG.getNode(X86ISD::GlobalBaseReg,
8772 SDLoc(), PtrVT), InFlag);
8773 InFlag = Chain.getValue(1);
8775 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8778 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8780 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8782 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8783 X86::RAX, X86II::MO_TLSGD);
8786 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8792 // Get the start address of the TLS block for this module.
8793 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8794 .getInfo<X86MachineFunctionInfo>();
8795 MFI->incNumLocalDynamicTLSAccesses();
8799 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8800 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8803 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8804 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8805 InFlag = Chain.getValue(1);
8806 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8807 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8810 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8814 unsigned char OperandFlags = X86II::MO_DTPOFF;
8815 unsigned WrapperKind = X86ISD::Wrapper;
8816 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8817 GA->getValueType(0),
8818 GA->getOffset(), OperandFlags);
8819 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8821 // Add x@dtpoff with the base.
8822 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8825 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8826 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8827 const EVT PtrVT, TLSModel::Model model,
8828 bool is64Bit, bool isPIC) {
8831 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8832 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8833 is64Bit ? 257 : 256));
8835 SDValue ThreadPointer =
8836 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8837 MachinePointerInfo(Ptr), false, false, false, 0);
8839 unsigned char OperandFlags = 0;
8840 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8842 unsigned WrapperKind = X86ISD::Wrapper;
8843 if (model == TLSModel::LocalExec) {
8844 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8845 } else if (model == TLSModel::InitialExec) {
8847 OperandFlags = X86II::MO_GOTTPOFF;
8848 WrapperKind = X86ISD::WrapperRIP;
8850 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8853 llvm_unreachable("Unexpected model");
8856 // emit "addl x@ntpoff,%eax" (local exec)
8857 // or "addl x@indntpoff,%eax" (initial exec)
8858 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8860 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8861 GA->getOffset(), OperandFlags);
8862 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8864 if (model == TLSModel::InitialExec) {
8865 if (isPIC && !is64Bit) {
8866 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8867 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8871 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8872 MachinePointerInfo::getGOT(), false, false, false, 0);
8875 // The address of the thread local variable is the add of the thread
8876 // pointer with the offset of the variable.
8877 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8881 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8883 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8884 const GlobalValue *GV = GA->getGlobal();
8886 if (Subtarget->isTargetELF()) {
8887 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8890 case TLSModel::GeneralDynamic:
8891 if (Subtarget->is64Bit())
8892 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8893 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8894 case TLSModel::LocalDynamic:
8895 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8896 Subtarget->is64Bit());
8897 case TLSModel::InitialExec:
8898 case TLSModel::LocalExec:
8899 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8900 Subtarget->is64Bit(),
8901 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8903 llvm_unreachable("Unknown TLS model.");
8906 if (Subtarget->isTargetDarwin()) {
8907 // Darwin only has one model of TLS. Lower to that.
8908 unsigned char OpFlag = 0;
8909 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8910 X86ISD::WrapperRIP : X86ISD::Wrapper;
8912 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8914 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8915 !Subtarget->is64Bit();
8917 OpFlag = X86II::MO_TLVP_PIC_BASE;
8919 OpFlag = X86II::MO_TLVP;
8921 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8922 GA->getValueType(0),
8923 GA->getOffset(), OpFlag);
8924 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8926 // With PIC32, the address is actually $g + Offset.
8928 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8929 DAG.getNode(X86ISD::GlobalBaseReg,
8930 SDLoc(), getPointerTy()),
8933 // Lowering the machine isd will make sure everything is in the right
8935 SDValue Chain = DAG.getEntryNode();
8936 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8937 SDValue Args[] = { Chain, Offset };
8938 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8940 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8941 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8942 MFI->setAdjustsStack(true);
8944 // And our return value (tls address) is in the standard call return value
8946 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8947 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8951 if (Subtarget->isTargetKnownWindowsMSVC() ||
8952 Subtarget->isTargetWindowsGNU()) {
8953 // Just use the implicit TLS architecture
8954 // Need to generate someting similar to:
8955 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8957 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8958 // mov rcx, qword [rdx+rcx*8]
8959 // mov eax, .tls$:tlsvar
8960 // [rax+rcx] contains the address
8961 // Windows 64bit: gs:0x58
8962 // Windows 32bit: fs:__tls_array
8965 SDValue Chain = DAG.getEntryNode();
8967 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8968 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8969 // use its literal value of 0x2C.
8970 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8971 ? Type::getInt8PtrTy(*DAG.getContext(),
8973 : Type::getInt32PtrTy(*DAG.getContext(),
8977 Subtarget->is64Bit()
8978 ? DAG.getIntPtrConstant(0x58)
8979 : (Subtarget->isTargetWindowsGNU()
8980 ? DAG.getIntPtrConstant(0x2C)
8981 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8983 SDValue ThreadPointer =
8984 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8985 MachinePointerInfo(Ptr), false, false, false, 0);
8987 // Load the _tls_index variable
8988 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8989 if (Subtarget->is64Bit())
8990 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8991 IDX, MachinePointerInfo(), MVT::i32,
8994 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8995 false, false, false, 0);
8997 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8999 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9001 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9002 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9003 false, false, false, 0);
9005 // Get the offset of start of .tls section
9006 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9007 GA->getValueType(0),
9008 GA->getOffset(), X86II::MO_SECREL);
9009 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9011 // The address of the thread local variable is the add of the thread
9012 // pointer with the offset of the variable.
9013 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9016 llvm_unreachable("TLS not implemented for this target.");
9019 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9020 /// and take a 2 x i32 value to shift plus a shift amount.
9021 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9022 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9023 MVT VT = Op.getSimpleValueType();
9024 unsigned VTBits = VT.getSizeInBits();
9026 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9027 SDValue ShOpLo = Op.getOperand(0);
9028 SDValue ShOpHi = Op.getOperand(1);
9029 SDValue ShAmt = Op.getOperand(2);
9030 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9031 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9033 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9034 DAG.getConstant(VTBits - 1, MVT::i8));
9035 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9036 DAG.getConstant(VTBits - 1, MVT::i8))
9037 : DAG.getConstant(0, VT);
9040 if (Op.getOpcode() == ISD::SHL_PARTS) {
9041 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9042 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9044 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9045 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9048 // If the shift amount is larger or equal than the width of a part we can't
9049 // rely on the results of shld/shrd. Insert a test and select the appropriate
9050 // values for large shift amounts.
9051 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9052 DAG.getConstant(VTBits, MVT::i8));
9053 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9054 AndNode, DAG.getConstant(0, MVT::i8));
9057 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9058 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9059 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9061 if (Op.getOpcode() == ISD::SHL_PARTS) {
9062 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9063 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9065 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9066 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9069 SDValue Ops[2] = { Lo, Hi };
9070 return DAG.getMergeValues(Ops, dl);
9073 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9074 SelectionDAG &DAG) const {
9075 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9077 if (SrcVT.isVector())
9080 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9081 "Unknown SINT_TO_FP to lower!");
9083 // These are really Legal; return the operand so the caller accepts it as
9085 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9087 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9088 Subtarget->is64Bit()) {
9093 unsigned Size = SrcVT.getSizeInBits()/8;
9094 MachineFunction &MF = DAG.getMachineFunction();
9095 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9096 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9097 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9099 MachinePointerInfo::getFixedStack(SSFI),
9101 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9104 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9106 SelectionDAG &DAG) const {
9110 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9112 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9114 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9116 unsigned ByteSize = SrcVT.getSizeInBits()/8;
9118 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9119 MachineMemOperand *MMO;
9121 int SSFI = FI->getIndex();
9123 DAG.getMachineFunction()
9124 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9125 MachineMemOperand::MOLoad, ByteSize, ByteSize);
9127 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9128 StackSlot = StackSlot.getOperand(1);
9130 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9131 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9133 Tys, Ops, SrcVT, MMO);
9136 Chain = Result.getValue(1);
9137 SDValue InFlag = Result.getValue(2);
9139 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9140 // shouldn't be necessary except that RFP cannot be live across
9141 // multiple blocks. When stackifier is fixed, they can be uncoupled.
9142 MachineFunction &MF = DAG.getMachineFunction();
9143 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9144 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9145 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9146 Tys = DAG.getVTList(MVT::Other);
9148 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9150 MachineMemOperand *MMO =
9151 DAG.getMachineFunction()
9152 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9153 MachineMemOperand::MOStore, SSFISize, SSFISize);
9155 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9156 Ops, Op.getValueType(), MMO);
9157 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9158 MachinePointerInfo::getFixedStack(SSFI),
9159 false, false, false, 0);
9165 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9166 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9167 SelectionDAG &DAG) const {
9168 // This algorithm is not obvious. Here it is what we're trying to output:
9171 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9172 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9176 pshufd $0x4e, %xmm0, %xmm1
9182 LLVMContext *Context = DAG.getContext();
9184 // Build some magic constants.
9185 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9186 Constant *C0 = ConstantDataVector::get(*Context, CV0);
9187 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9189 SmallVector<Constant*,2> CV1;
9191 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9192 APInt(64, 0x4330000000000000ULL))));
9194 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9195 APInt(64, 0x4530000000000000ULL))));
9196 Constant *C1 = ConstantVector::get(CV1);
9197 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9199 // Load the 64-bit value into an XMM register.
9200 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9202 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9203 MachinePointerInfo::getConstantPool(),
9204 false, false, false, 16);
9205 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9206 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9209 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9210 MachinePointerInfo::getConstantPool(),
9211 false, false, false, 16);
9212 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9213 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9216 if (Subtarget->hasSSE3()) {
9217 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9218 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9220 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9221 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9223 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9224 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9228 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9229 DAG.getIntPtrConstant(0));
9232 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9233 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9234 SelectionDAG &DAG) const {
9236 // FP constant to bias correct the final result.
9237 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9240 // Load the 32-bit value into an XMM register.
9241 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9244 // Zero out the upper parts of the register.
9245 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9247 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9248 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9249 DAG.getIntPtrConstant(0));
9251 // Or the load with the bias.
9252 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9253 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9254 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9256 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9257 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9258 MVT::v2f64, Bias)));
9259 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9260 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9261 DAG.getIntPtrConstant(0));
9263 // Subtract the bias.
9264 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9266 // Handle final rounding.
9267 EVT DestVT = Op.getValueType();
9269 if (DestVT.bitsLT(MVT::f64))
9270 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9271 DAG.getIntPtrConstant(0));
9272 if (DestVT.bitsGT(MVT::f64))
9273 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9275 // Handle final rounding.
9279 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9280 SelectionDAG &DAG) const {
9281 SDValue N0 = Op.getOperand(0);
9282 MVT SVT = N0.getSimpleValueType();
9285 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9286 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9287 "Custom UINT_TO_FP is not supported!");
9289 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9290 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9291 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9294 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9295 SelectionDAG &DAG) const {
9296 SDValue N0 = Op.getOperand(0);
9299 if (Op.getValueType().isVector())
9300 return lowerUINT_TO_FP_vec(Op, DAG);
9302 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9303 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9304 // the optimization here.
9305 if (DAG.SignBitIsZero(N0))
9306 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9308 MVT SrcVT = N0.getSimpleValueType();
9309 MVT DstVT = Op.getSimpleValueType();
9310 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9311 return LowerUINT_TO_FP_i64(Op, DAG);
9312 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9313 return LowerUINT_TO_FP_i32(Op, DAG);
9314 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9317 // Make a 64-bit buffer, and use it to build an FILD.
9318 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9319 if (SrcVT == MVT::i32) {
9320 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9321 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9322 getPointerTy(), StackSlot, WordOff);
9323 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9324 StackSlot, MachinePointerInfo(),
9326 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9327 OffsetSlot, MachinePointerInfo(),
9329 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9333 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9334 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9335 StackSlot, MachinePointerInfo(),
9337 // For i64 source, we need to add the appropriate power of 2 if the input
9338 // was negative. This is the same as the optimization in
9339 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9340 // we must be careful to do the computation in x87 extended precision, not
9341 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9342 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9343 MachineMemOperand *MMO =
9344 DAG.getMachineFunction()
9345 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9346 MachineMemOperand::MOLoad, 8, 8);
9348 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9349 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9350 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9353 APInt FF(32, 0x5F800000ULL);
9355 // Check whether the sign bit is set.
9356 SDValue SignSet = DAG.getSetCC(dl,
9357 getSetCCResultType(*DAG.getContext(), MVT::i64),
9358 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9361 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9362 SDValue FudgePtr = DAG.getConstantPool(
9363 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9366 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9367 SDValue Zero = DAG.getIntPtrConstant(0);
9368 SDValue Four = DAG.getIntPtrConstant(4);
9369 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9371 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9373 // Load the value out, extending it from f32 to f80.
9374 // FIXME: Avoid the extend by constructing the right constant pool?
9375 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9376 FudgePtr, MachinePointerInfo::getConstantPool(),
9377 MVT::f32, false, false, 4);
9378 // Extend everything to 80 bits to force it to be done on x87.
9379 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9380 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9383 std::pair<SDValue,SDValue>
9384 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9385 bool IsSigned, bool IsReplace) const {
9388 EVT DstTy = Op.getValueType();
9390 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9391 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9395 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9396 DstTy.getSimpleVT() >= MVT::i16 &&
9397 "Unknown FP_TO_INT to lower!");
9399 // These are really Legal.
9400 if (DstTy == MVT::i32 &&
9401 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9402 return std::make_pair(SDValue(), SDValue());
9403 if (Subtarget->is64Bit() &&
9404 DstTy == MVT::i64 &&
9405 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9406 return std::make_pair(SDValue(), SDValue());
9408 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9409 // stack slot, or into the FTOL runtime function.
9410 MachineFunction &MF = DAG.getMachineFunction();
9411 unsigned MemSize = DstTy.getSizeInBits()/8;
9412 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9413 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9416 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9417 Opc = X86ISD::WIN_FTOL;
9419 switch (DstTy.getSimpleVT().SimpleTy) {
9420 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9421 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9422 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9423 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9426 SDValue Chain = DAG.getEntryNode();
9427 SDValue Value = Op.getOperand(0);
9428 EVT TheVT = Op.getOperand(0).getValueType();
9429 // FIXME This causes a redundant load/store if the SSE-class value is already
9430 // in memory, such as if it is on the callstack.
9431 if (isScalarFPTypeInSSEReg(TheVT)) {
9432 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9433 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9434 MachinePointerInfo::getFixedStack(SSFI),
9436 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9438 Chain, StackSlot, DAG.getValueType(TheVT)
9441 MachineMemOperand *MMO =
9442 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9443 MachineMemOperand::MOLoad, MemSize, MemSize);
9444 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9445 Chain = Value.getValue(1);
9446 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9447 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9450 MachineMemOperand *MMO =
9451 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9452 MachineMemOperand::MOStore, MemSize, MemSize);
9454 if (Opc != X86ISD::WIN_FTOL) {
9455 // Build the FP_TO_INT*_IN_MEM
9456 SDValue Ops[] = { Chain, Value, StackSlot };
9457 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9459 return std::make_pair(FIST, StackSlot);
9461 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9462 DAG.getVTList(MVT::Other, MVT::Glue),
9464 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9465 MVT::i32, ftol.getValue(1));
9466 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9467 MVT::i32, eax.getValue(2));
9468 SDValue Ops[] = { eax, edx };
9469 SDValue pair = IsReplace
9470 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9471 : DAG.getMergeValues(Ops, DL);
9472 return std::make_pair(pair, SDValue());
9476 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9477 const X86Subtarget *Subtarget) {
9478 MVT VT = Op->getSimpleValueType(0);
9479 SDValue In = Op->getOperand(0);
9480 MVT InVT = In.getSimpleValueType();
9483 // Optimize vectors in AVX mode:
9486 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9487 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9488 // Concat upper and lower parts.
9491 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9492 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9493 // Concat upper and lower parts.
9496 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9497 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9498 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9501 if (Subtarget->hasInt256())
9502 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9504 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9505 SDValue Undef = DAG.getUNDEF(InVT);
9506 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9507 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9508 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9510 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9511 VT.getVectorNumElements()/2);
9513 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9514 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9516 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9519 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9520 SelectionDAG &DAG) {
9521 MVT VT = Op->getSimpleValueType(0);
9522 SDValue In = Op->getOperand(0);
9523 MVT InVT = In.getSimpleValueType();
9525 unsigned int NumElts = VT.getVectorNumElements();
9526 if (NumElts != 8 && NumElts != 16)
9529 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9530 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9532 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9534 // Now we have only mask extension
9535 assert(InVT.getVectorElementType() == MVT::i1);
9536 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9537 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9538 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9539 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9540 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9541 MachinePointerInfo::getConstantPool(),
9542 false, false, false, Alignment);
9544 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9545 if (VT.is512BitVector())
9547 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9550 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9551 SelectionDAG &DAG) {
9552 if (Subtarget->hasFp256()) {
9553 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9561 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9562 SelectionDAG &DAG) {
9564 MVT VT = Op.getSimpleValueType();
9565 SDValue In = Op.getOperand(0);
9566 MVT SVT = In.getSimpleValueType();
9568 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9569 return LowerZERO_EXTEND_AVX512(Op, DAG);
9571 if (Subtarget->hasFp256()) {
9572 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9577 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9578 VT.getVectorNumElements() != SVT.getVectorNumElements());
9582 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9584 MVT VT = Op.getSimpleValueType();
9585 SDValue In = Op.getOperand(0);
9586 MVT InVT = In.getSimpleValueType();
9588 if (VT == MVT::i1) {
9589 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9590 "Invalid scalar TRUNCATE operation");
9591 if (InVT == MVT::i32)
9593 if (InVT.getSizeInBits() == 64)
9594 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9595 else if (InVT.getSizeInBits() < 32)
9596 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9597 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9599 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9600 "Invalid TRUNCATE operation");
9602 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9603 if (VT.getVectorElementType().getSizeInBits() >=8)
9604 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9606 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9607 unsigned NumElts = InVT.getVectorNumElements();
9608 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9609 if (InVT.getSizeInBits() < 512) {
9610 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9611 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9615 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9616 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9617 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9618 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9619 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9620 MachinePointerInfo::getConstantPool(),
9621 false, false, false, Alignment);
9622 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9623 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9624 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9627 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9628 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9629 if (Subtarget->hasInt256()) {
9630 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9631 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9632 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9634 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9635 DAG.getIntPtrConstant(0));
9638 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9639 DAG.getIntPtrConstant(0));
9640 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9641 DAG.getIntPtrConstant(2));
9642 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9643 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9644 static const int ShufMask[] = {0, 2, 4, 6};
9645 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9648 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9649 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9650 if (Subtarget->hasInt256()) {
9651 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9653 SmallVector<SDValue,32> pshufbMask;
9654 for (unsigned i = 0; i < 2; ++i) {
9655 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9656 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9657 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9658 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9659 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9660 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9661 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9662 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9663 for (unsigned j = 0; j < 8; ++j)
9664 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9666 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9667 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9668 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9670 static const int ShufMask[] = {0, 2, -1, -1};
9671 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9673 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9674 DAG.getIntPtrConstant(0));
9675 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9678 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9679 DAG.getIntPtrConstant(0));
9681 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9682 DAG.getIntPtrConstant(4));
9684 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9685 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9688 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9689 -1, -1, -1, -1, -1, -1, -1, -1};
9691 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9692 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9693 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9695 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9696 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9698 // The MOVLHPS Mask:
9699 static const int ShufMask2[] = {0, 1, 4, 5};
9700 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9701 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9704 // Handle truncation of V256 to V128 using shuffles.
9705 if (!VT.is128BitVector() || !InVT.is256BitVector())
9708 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9710 unsigned NumElems = VT.getVectorNumElements();
9711 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9713 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9714 // Prepare truncation shuffle mask
9715 for (unsigned i = 0; i != NumElems; ++i)
9717 SDValue V = DAG.getVectorShuffle(NVT, DL,
9718 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9719 DAG.getUNDEF(NVT), &MaskVec[0]);
9720 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9721 DAG.getIntPtrConstant(0));
9724 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9725 SelectionDAG &DAG) const {
9726 assert(!Op.getSimpleValueType().isVector());
9728 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9729 /*IsSigned=*/ true, /*IsReplace=*/ false);
9730 SDValue FIST = Vals.first, StackSlot = Vals.second;
9731 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9732 if (!FIST.getNode()) return Op;
9734 if (StackSlot.getNode())
9736 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9737 FIST, StackSlot, MachinePointerInfo(),
9738 false, false, false, 0);
9740 // The node is the result.
9744 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9745 SelectionDAG &DAG) const {
9746 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9747 /*IsSigned=*/ false, /*IsReplace=*/ false);
9748 SDValue FIST = Vals.first, StackSlot = Vals.second;
9749 assert(FIST.getNode() && "Unexpected failure");
9751 if (StackSlot.getNode())
9753 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9754 FIST, StackSlot, MachinePointerInfo(),
9755 false, false, false, 0);
9757 // The node is the result.
9761 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9763 MVT VT = Op.getSimpleValueType();
9764 SDValue In = Op.getOperand(0);
9765 MVT SVT = In.getSimpleValueType();
9767 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9769 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9770 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9771 In, DAG.getUNDEF(SVT)));
9774 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9775 LLVMContext *Context = DAG.getContext();
9777 MVT VT = Op.getSimpleValueType();
9779 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9780 if (VT.isVector()) {
9781 EltVT = VT.getVectorElementType();
9782 NumElts = VT.getVectorNumElements();
9785 if (EltVT == MVT::f64)
9786 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9787 APInt(64, ~(1ULL << 63))));
9789 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9790 APInt(32, ~(1U << 31))));
9791 C = ConstantVector::getSplat(NumElts, C);
9792 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9793 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9794 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9795 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9796 MachinePointerInfo::getConstantPool(),
9797 false, false, false, Alignment);
9798 if (VT.isVector()) {
9799 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9800 return DAG.getNode(ISD::BITCAST, dl, VT,
9801 DAG.getNode(ISD::AND, dl, ANDVT,
9802 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9804 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9806 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9809 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9810 LLVMContext *Context = DAG.getContext();
9812 MVT VT = Op.getSimpleValueType();
9814 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9815 if (VT.isVector()) {
9816 EltVT = VT.getVectorElementType();
9817 NumElts = VT.getVectorNumElements();
9820 if (EltVT == MVT::f64)
9821 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9822 APInt(64, 1ULL << 63)));
9824 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9825 APInt(32, 1U << 31)));
9826 C = ConstantVector::getSplat(NumElts, C);
9827 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9828 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9829 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9830 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9831 MachinePointerInfo::getConstantPool(),
9832 false, false, false, Alignment);
9833 if (VT.isVector()) {
9834 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9835 return DAG.getNode(ISD::BITCAST, dl, VT,
9836 DAG.getNode(ISD::XOR, dl, XORVT,
9837 DAG.getNode(ISD::BITCAST, dl, XORVT,
9839 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9842 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9845 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9846 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9847 LLVMContext *Context = DAG.getContext();
9848 SDValue Op0 = Op.getOperand(0);
9849 SDValue Op1 = Op.getOperand(1);
9851 MVT VT = Op.getSimpleValueType();
9852 MVT SrcVT = Op1.getSimpleValueType();
9854 // If second operand is smaller, extend it first.
9855 if (SrcVT.bitsLT(VT)) {
9856 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9859 // And if it is bigger, shrink it first.
9860 if (SrcVT.bitsGT(VT)) {
9861 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9865 // At this point the operands and the result should have the same
9866 // type, and that won't be f80 since that is not custom lowered.
9868 // First get the sign bit of second operand.
9869 SmallVector<Constant*,4> CV;
9870 if (SrcVT == MVT::f64) {
9871 const fltSemantics &Sem = APFloat::IEEEdouble;
9872 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9873 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9875 const fltSemantics &Sem = APFloat::IEEEsingle;
9876 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9877 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9878 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9879 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9881 Constant *C = ConstantVector::get(CV);
9882 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9883 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9884 MachinePointerInfo::getConstantPool(),
9885 false, false, false, 16);
9886 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9888 // Shift sign bit right or left if the two operands have different types.
9889 if (SrcVT.bitsGT(VT)) {
9890 // Op0 is MVT::f32, Op1 is MVT::f64.
9891 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9892 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9893 DAG.getConstant(32, MVT::i32));
9894 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9895 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9896 DAG.getIntPtrConstant(0));
9899 // Clear first operand sign bit.
9901 if (VT == MVT::f64) {
9902 const fltSemantics &Sem = APFloat::IEEEdouble;
9903 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9904 APInt(64, ~(1ULL << 63)))));
9905 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9907 const fltSemantics &Sem = APFloat::IEEEsingle;
9908 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9909 APInt(32, ~(1U << 31)))));
9910 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9911 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9912 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9914 C = ConstantVector::get(CV);
9915 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9916 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9917 MachinePointerInfo::getConstantPool(),
9918 false, false, false, 16);
9919 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9921 // Or the value with the sign bit.
9922 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9925 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9926 SDValue N0 = Op.getOperand(0);
9928 MVT VT = Op.getSimpleValueType();
9930 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9931 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9932 DAG.getConstant(1, VT));
9933 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9936 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9938 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9939 SelectionDAG &DAG) {
9940 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9942 if (!Subtarget->hasSSE41())
9945 if (!Op->hasOneUse())
9948 SDNode *N = Op.getNode();
9951 SmallVector<SDValue, 8> Opnds;
9952 DenseMap<SDValue, unsigned> VecInMap;
9953 SmallVector<SDValue, 8> VecIns;
9954 EVT VT = MVT::Other;
9956 // Recognize a special case where a vector is casted into wide integer to
9958 Opnds.push_back(N->getOperand(0));
9959 Opnds.push_back(N->getOperand(1));
9961 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9962 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9963 // BFS traverse all OR'd operands.
9964 if (I->getOpcode() == ISD::OR) {
9965 Opnds.push_back(I->getOperand(0));
9966 Opnds.push_back(I->getOperand(1));
9967 // Re-evaluate the number of nodes to be traversed.
9968 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9972 // Quit if a non-EXTRACT_VECTOR_ELT
9973 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9976 // Quit if without a constant index.
9977 SDValue Idx = I->getOperand(1);
9978 if (!isa<ConstantSDNode>(Idx))
9981 SDValue ExtractedFromVec = I->getOperand(0);
9982 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9983 if (M == VecInMap.end()) {
9984 VT = ExtractedFromVec.getValueType();
9985 // Quit if not 128/256-bit vector.
9986 if (!VT.is128BitVector() && !VT.is256BitVector())
9988 // Quit if not the same type.
9989 if (VecInMap.begin() != VecInMap.end() &&
9990 VT != VecInMap.begin()->first.getValueType())
9992 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9993 VecIns.push_back(ExtractedFromVec);
9995 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9998 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9999 "Not extracted from 128-/256-bit vector.");
10001 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10003 for (DenseMap<SDValue, unsigned>::const_iterator
10004 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10005 // Quit if not all elements are used.
10006 if (I->second != FullMask)
10010 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10012 // Cast all vectors into TestVT for PTEST.
10013 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10014 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10016 // If more than one full vectors are evaluated, OR them first before PTEST.
10017 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10018 // Each iteration will OR 2 nodes and append the result until there is only
10019 // 1 node left, i.e. the final OR'd value of all vectors.
10020 SDValue LHS = VecIns[Slot];
10021 SDValue RHS = VecIns[Slot + 1];
10022 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10025 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10026 VecIns.back(), VecIns.back());
10029 /// \brief return true if \c Op has a use that doesn't just read flags.
10030 static bool hasNonFlagsUse(SDValue Op) {
10031 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10033 SDNode *User = *UI;
10034 unsigned UOpNo = UI.getOperandNo();
10035 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10036 // Look pass truncate.
10037 UOpNo = User->use_begin().getOperandNo();
10038 User = *User->use_begin();
10041 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10042 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10048 /// Emit nodes that will be selected as "test Op0,Op0", or something
10050 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10051 SelectionDAG &DAG) const {
10052 if (Op.getValueType() == MVT::i1)
10053 // KORTEST instruction should be selected
10054 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10055 DAG.getConstant(0, Op.getValueType()));
10057 // CF and OF aren't always set the way we want. Determine which
10058 // of these we need.
10059 bool NeedCF = false;
10060 bool NeedOF = false;
10063 case X86::COND_A: case X86::COND_AE:
10064 case X86::COND_B: case X86::COND_BE:
10067 case X86::COND_G: case X86::COND_GE:
10068 case X86::COND_L: case X86::COND_LE:
10069 case X86::COND_O: case X86::COND_NO:
10073 // See if we can use the EFLAGS value from the operand instead of
10074 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10075 // we prove that the arithmetic won't overflow, we can't use OF or CF.
10076 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10077 // Emit a CMP with 0, which is the TEST pattern.
10078 //if (Op.getValueType() == MVT::i1)
10079 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10080 // DAG.getConstant(0, MVT::i1));
10081 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10082 DAG.getConstant(0, Op.getValueType()));
10084 unsigned Opcode = 0;
10085 unsigned NumOperands = 0;
10087 // Truncate operations may prevent the merge of the SETCC instruction
10088 // and the arithmetic instruction before it. Attempt to truncate the operands
10089 // of the arithmetic instruction and use a reduced bit-width instruction.
10090 bool NeedTruncation = false;
10091 SDValue ArithOp = Op;
10092 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10093 SDValue Arith = Op->getOperand(0);
10094 // Both the trunc and the arithmetic op need to have one user each.
10095 if (Arith->hasOneUse())
10096 switch (Arith.getOpcode()) {
10103 NeedTruncation = true;
10109 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10110 // which may be the result of a CAST. We use the variable 'Op', which is the
10111 // non-casted variable when we check for possible users.
10112 switch (ArithOp.getOpcode()) {
10114 // Due to an isel shortcoming, be conservative if this add is likely to be
10115 // selected as part of a load-modify-store instruction. When the root node
10116 // in a match is a store, isel doesn't know how to remap non-chain non-flag
10117 // uses of other nodes in the match, such as the ADD in this case. This
10118 // leads to the ADD being left around and reselected, with the result being
10119 // two adds in the output. Alas, even if none our users are stores, that
10120 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
10121 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
10122 // climbing the DAG back to the root, and it doesn't seem to be worth the
10124 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10125 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10126 if (UI->getOpcode() != ISD::CopyToReg &&
10127 UI->getOpcode() != ISD::SETCC &&
10128 UI->getOpcode() != ISD::STORE)
10131 if (ConstantSDNode *C =
10132 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10133 // An add of one will be selected as an INC.
10134 if (C->getAPIntValue() == 1) {
10135 Opcode = X86ISD::INC;
10140 // An add of negative one (subtract of one) will be selected as a DEC.
10141 if (C->getAPIntValue().isAllOnesValue()) {
10142 Opcode = X86ISD::DEC;
10148 // Otherwise use a regular EFLAGS-setting add.
10149 Opcode = X86ISD::ADD;
10154 // If we have a constant logical shift that's only used in a comparison
10155 // against zero turn it into an equivalent AND. This allows turning it into
10156 // a TEST instruction later.
10157 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
10158 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10159 EVT VT = Op.getValueType();
10160 unsigned BitWidth = VT.getSizeInBits();
10161 unsigned ShAmt = Op->getConstantOperandVal(1);
10162 if (ShAmt >= BitWidth) // Avoid undefined shifts.
10164 APInt Mask = ArithOp.getOpcode() == ISD::SRL
10165 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10166 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10167 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10169 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10170 DAG.getConstant(Mask, VT));
10171 DAG.ReplaceAllUsesWith(Op, New);
10177 // If the primary and result isn't used, don't bother using X86ISD::AND,
10178 // because a TEST instruction will be better.
10179 if (!hasNonFlagsUse(Op))
10185 // Due to the ISEL shortcoming noted above, be conservative if this op is
10186 // likely to be selected as part of a load-modify-store instruction.
10187 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10188 UE = Op.getNode()->use_end(); UI != UE; ++UI)
10189 if (UI->getOpcode() == ISD::STORE)
10192 // Otherwise use a regular EFLAGS-setting instruction.
10193 switch (ArithOp.getOpcode()) {
10194 default: llvm_unreachable("unexpected operator!");
10195 case ISD::SUB: Opcode = X86ISD::SUB; break;
10196 case ISD::XOR: Opcode = X86ISD::XOR; break;
10197 case ISD::AND: Opcode = X86ISD::AND; break;
10199 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10200 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10201 if (EFLAGS.getNode())
10204 Opcode = X86ISD::OR;
10218 return SDValue(Op.getNode(), 1);
10224 // If we found that truncation is beneficial, perform the truncation and
10226 if (NeedTruncation) {
10227 EVT VT = Op.getValueType();
10228 SDValue WideVal = Op->getOperand(0);
10229 EVT WideVT = WideVal.getValueType();
10230 unsigned ConvertedOp = 0;
10231 // Use a target machine opcode to prevent further DAGCombine
10232 // optimizations that may separate the arithmetic operations
10233 // from the setcc node.
10234 switch (WideVal.getOpcode()) {
10236 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10237 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10238 case ISD::AND: ConvertedOp = X86ISD::AND; break;
10239 case ISD::OR: ConvertedOp = X86ISD::OR; break;
10240 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10244 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10245 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10246 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10247 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10248 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10254 // Emit a CMP with 0, which is the TEST pattern.
10255 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10256 DAG.getConstant(0, Op.getValueType()));
10258 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10259 SmallVector<SDValue, 4> Ops;
10260 for (unsigned i = 0; i != NumOperands; ++i)
10261 Ops.push_back(Op.getOperand(i));
10263 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10264 DAG.ReplaceAllUsesWith(Op, New);
10265 return SDValue(New.getNode(), 1);
10268 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10270 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10271 SDLoc dl, SelectionDAG &DAG) const {
10272 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10273 if (C->getAPIntValue() == 0)
10274 return EmitTest(Op0, X86CC, dl, DAG);
10276 if (Op0.getValueType() == MVT::i1)
10277 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10280 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10281 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10282 // Do the comparison at i32 if it's smaller, besides the Atom case.
10283 // This avoids subregister aliasing issues. Keep the smaller reference
10284 // if we're optimizing for size, however, as that'll allow better folding
10285 // of memory operations.
10286 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10287 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10288 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10289 !Subtarget->isAtom()) {
10290 unsigned ExtendOp =
10291 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10292 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10293 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10295 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10296 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10297 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10299 return SDValue(Sub.getNode(), 1);
10301 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10304 /// Convert a comparison if required by the subtarget.
10305 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10306 SelectionDAG &DAG) const {
10307 // If the subtarget does not support the FUCOMI instruction, floating-point
10308 // comparisons have to be converted.
10309 if (Subtarget->hasCMov() ||
10310 Cmp.getOpcode() != X86ISD::CMP ||
10311 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10312 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10315 // The instruction selector will select an FUCOM instruction instead of
10316 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10317 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10318 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10320 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10321 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10322 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10323 DAG.getConstant(8, MVT::i8));
10324 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10325 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10328 static bool isAllOnes(SDValue V) {
10329 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10330 return C && C->isAllOnesValue();
10333 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10334 /// if it's possible.
10335 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10336 SDLoc dl, SelectionDAG &DAG) const {
10337 SDValue Op0 = And.getOperand(0);
10338 SDValue Op1 = And.getOperand(1);
10339 if (Op0.getOpcode() == ISD::TRUNCATE)
10340 Op0 = Op0.getOperand(0);
10341 if (Op1.getOpcode() == ISD::TRUNCATE)
10342 Op1 = Op1.getOperand(0);
10345 if (Op1.getOpcode() == ISD::SHL)
10346 std::swap(Op0, Op1);
10347 if (Op0.getOpcode() == ISD::SHL) {
10348 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10349 if (And00C->getZExtValue() == 1) {
10350 // If we looked past a truncate, check that it's only truncating away
10352 unsigned BitWidth = Op0.getValueSizeInBits();
10353 unsigned AndBitWidth = And.getValueSizeInBits();
10354 if (BitWidth > AndBitWidth) {
10356 DAG.computeKnownBits(Op0, Zeros, Ones);
10357 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10361 RHS = Op0.getOperand(1);
10363 } else if (Op1.getOpcode() == ISD::Constant) {
10364 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10365 uint64_t AndRHSVal = AndRHS->getZExtValue();
10366 SDValue AndLHS = Op0;
10368 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10369 LHS = AndLHS.getOperand(0);
10370 RHS = AndLHS.getOperand(1);
10373 // Use BT if the immediate can't be encoded in a TEST instruction.
10374 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10376 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10380 if (LHS.getNode()) {
10381 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10382 // instruction. Since the shift amount is in-range-or-undefined, we know
10383 // that doing a bittest on the i32 value is ok. We extend to i32 because
10384 // the encoding for the i16 version is larger than the i32 version.
10385 // Also promote i16 to i32 for performance / code size reason.
10386 if (LHS.getValueType() == MVT::i8 ||
10387 LHS.getValueType() == MVT::i16)
10388 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10390 // If the operand types disagree, extend the shift amount to match. Since
10391 // BT ignores high bits (like shifts) we can use anyextend.
10392 if (LHS.getValueType() != RHS.getValueType())
10393 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10395 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10396 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10397 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10398 DAG.getConstant(Cond, MVT::i8), BT);
10404 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10406 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10411 // SSE Condition code mapping:
10420 switch (SetCCOpcode) {
10421 default: llvm_unreachable("Unexpected SETCC condition");
10423 case ISD::SETEQ: SSECC = 0; break;
10425 case ISD::SETGT: Swap = true; // Fallthrough
10427 case ISD::SETOLT: SSECC = 1; break;
10429 case ISD::SETGE: Swap = true; // Fallthrough
10431 case ISD::SETOLE: SSECC = 2; break;
10432 case ISD::SETUO: SSECC = 3; break;
10434 case ISD::SETNE: SSECC = 4; break;
10435 case ISD::SETULE: Swap = true; // Fallthrough
10436 case ISD::SETUGE: SSECC = 5; break;
10437 case ISD::SETULT: Swap = true; // Fallthrough
10438 case ISD::SETUGT: SSECC = 6; break;
10439 case ISD::SETO: SSECC = 7; break;
10441 case ISD::SETONE: SSECC = 8; break;
10444 std::swap(Op0, Op1);
10449 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10450 // ones, and then concatenate the result back.
10451 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10452 MVT VT = Op.getSimpleValueType();
10454 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10455 "Unsupported value type for operation");
10457 unsigned NumElems = VT.getVectorNumElements();
10459 SDValue CC = Op.getOperand(2);
10461 // Extract the LHS vectors
10462 SDValue LHS = Op.getOperand(0);
10463 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10464 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10466 // Extract the RHS vectors
10467 SDValue RHS = Op.getOperand(1);
10468 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10469 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10471 // Issue the operation on the smaller types and concatenate the result back
10472 MVT EltVT = VT.getVectorElementType();
10473 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10474 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10475 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10476 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10479 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10480 const X86Subtarget *Subtarget) {
10481 SDValue Op0 = Op.getOperand(0);
10482 SDValue Op1 = Op.getOperand(1);
10483 SDValue CC = Op.getOperand(2);
10484 MVT VT = Op.getSimpleValueType();
10487 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10488 Op.getValueType().getScalarType() == MVT::i1 &&
10489 "Cannot set masked compare for this operation");
10491 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10493 bool Unsigned = false;
10496 switch (SetCCOpcode) {
10497 default: llvm_unreachable("Unexpected SETCC condition");
10498 case ISD::SETNE: SSECC = 4; break;
10499 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10500 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10501 case ISD::SETLT: Swap = true; //fall-through
10502 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10503 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10504 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10505 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10506 case ISD::SETULE: Unsigned = true; //fall-through
10507 case ISD::SETLE: SSECC = 2; break;
10511 std::swap(Op0, Op1);
10513 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10514 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10515 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10516 DAG.getConstant(SSECC, MVT::i8));
10519 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10520 /// operand \p Op1. If non-trivial (for example because it's not constant)
10521 /// return an empty value.
10522 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10524 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10528 MVT VT = Op1.getSimpleValueType();
10529 MVT EVT = VT.getVectorElementType();
10530 unsigned n = VT.getVectorNumElements();
10531 SmallVector<SDValue, 8> ULTOp1;
10533 for (unsigned i = 0; i < n; ++i) {
10534 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10535 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10538 // Avoid underflow.
10539 APInt Val = Elt->getAPIntValue();
10543 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10546 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10549 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10550 SelectionDAG &DAG) {
10551 SDValue Op0 = Op.getOperand(0);
10552 SDValue Op1 = Op.getOperand(1);
10553 SDValue CC = Op.getOperand(2);
10554 MVT VT = Op.getSimpleValueType();
10555 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10556 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10561 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10562 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10565 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10566 unsigned Opc = X86ISD::CMPP;
10567 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10568 assert(VT.getVectorNumElements() <= 16);
10569 Opc = X86ISD::CMPM;
10571 // In the two special cases we can't handle, emit two comparisons.
10574 unsigned CombineOpc;
10575 if (SetCCOpcode == ISD::SETUEQ) {
10576 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10578 assert(SetCCOpcode == ISD::SETONE);
10579 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10582 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10583 DAG.getConstant(CC0, MVT::i8));
10584 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10585 DAG.getConstant(CC1, MVT::i8));
10586 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10588 // Handle all other FP comparisons here.
10589 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10590 DAG.getConstant(SSECC, MVT::i8));
10593 // Break 256-bit integer vector compare into smaller ones.
10594 if (VT.is256BitVector() && !Subtarget->hasInt256())
10595 return Lower256IntVSETCC(Op, DAG);
10597 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10598 EVT OpVT = Op1.getValueType();
10599 if (Subtarget->hasAVX512()) {
10600 if (Op1.getValueType().is512BitVector() ||
10601 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10602 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10604 // In AVX-512 architecture setcc returns mask with i1 elements,
10605 // But there is no compare instruction for i8 and i16 elements.
10606 // We are not talking about 512-bit operands in this case, these
10607 // types are illegal.
10609 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10610 OpVT.getVectorElementType().getSizeInBits() >= 8))
10611 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10612 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10615 // We are handling one of the integer comparisons here. Since SSE only has
10616 // GT and EQ comparisons for integer, swapping operands and multiple
10617 // operations may be required for some comparisons.
10619 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10620 bool Subus = false;
10622 switch (SetCCOpcode) {
10623 default: llvm_unreachable("Unexpected SETCC condition");
10624 case ISD::SETNE: Invert = true;
10625 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10626 case ISD::SETLT: Swap = true;
10627 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10628 case ISD::SETGE: Swap = true;
10629 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10630 Invert = true; break;
10631 case ISD::SETULT: Swap = true;
10632 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10633 FlipSigns = true; break;
10634 case ISD::SETUGE: Swap = true;
10635 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10636 FlipSigns = true; Invert = true; break;
10639 // Special case: Use min/max operations for SETULE/SETUGE
10640 MVT VET = VT.getVectorElementType();
10642 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10643 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10646 switch (SetCCOpcode) {
10648 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10649 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10652 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10655 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10656 if (!MinMax && hasSubus) {
10657 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10659 // t = psubus Op0, Op1
10660 // pcmpeq t, <0..0>
10661 switch (SetCCOpcode) {
10663 case ISD::SETULT: {
10664 // If the comparison is against a constant we can turn this into a
10665 // setule. With psubus, setule does not require a swap. This is
10666 // beneficial because the constant in the register is no longer
10667 // destructed as the destination so it can be hoisted out of a loop.
10668 // Only do this pre-AVX since vpcmp* is no longer destructive.
10669 if (Subtarget->hasAVX())
10671 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10672 if (ULEOp1.getNode()) {
10674 Subus = true; Invert = false; Swap = false;
10678 // Psubus is better than flip-sign because it requires no inversion.
10679 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10680 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10684 Opc = X86ISD::SUBUS;
10690 std::swap(Op0, Op1);
10692 // Check that the operation in question is available (most are plain SSE2,
10693 // but PCMPGTQ and PCMPEQQ have different requirements).
10694 if (VT == MVT::v2i64) {
10695 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10696 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10698 // First cast everything to the right type.
10699 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10700 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10702 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10703 // bits of the inputs before performing those operations. The lower
10704 // compare is always unsigned.
10707 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10709 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10710 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10711 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10712 Sign, Zero, Sign, Zero);
10714 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10715 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10717 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10718 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10719 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10721 // Create masks for only the low parts/high parts of the 64 bit integers.
10722 static const int MaskHi[] = { 1, 1, 3, 3 };
10723 static const int MaskLo[] = { 0, 0, 2, 2 };
10724 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10725 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10726 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10728 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10729 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10732 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10734 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10737 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10738 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10739 // pcmpeqd + pshufd + pand.
10740 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10742 // First cast everything to the right type.
10743 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10744 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10747 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10749 // Make sure the lower and upper halves are both all-ones.
10750 static const int Mask[] = { 1, 0, 3, 2 };
10751 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10752 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10755 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10757 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10761 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10762 // bits of the inputs before performing those operations.
10764 EVT EltVT = VT.getVectorElementType();
10765 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10766 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10767 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10770 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10772 // If the logical-not of the result is required, perform that now.
10774 Result = DAG.getNOT(dl, Result, VT);
10777 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10780 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10781 getZeroVector(VT, Subtarget, DAG, dl));
10786 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10788 MVT VT = Op.getSimpleValueType();
10790 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10792 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10793 && "SetCC type must be 8-bit or 1-bit integer");
10794 SDValue Op0 = Op.getOperand(0);
10795 SDValue Op1 = Op.getOperand(1);
10797 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10799 // Optimize to BT if possible.
10800 // Lower (X & (1 << N)) == 0 to BT(X, N).
10801 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10802 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10803 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10804 Op1.getOpcode() == ISD::Constant &&
10805 cast<ConstantSDNode>(Op1)->isNullValue() &&
10806 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10807 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10808 if (NewSetCC.getNode())
10812 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10814 if (Op1.getOpcode() == ISD::Constant &&
10815 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10816 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10817 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10819 // If the input is a setcc, then reuse the input setcc or use a new one with
10820 // the inverted condition.
10821 if (Op0.getOpcode() == X86ISD::SETCC) {
10822 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10823 bool Invert = (CC == ISD::SETNE) ^
10824 cast<ConstantSDNode>(Op1)->isNullValue();
10828 CCode = X86::GetOppositeBranchCondition(CCode);
10829 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10830 DAG.getConstant(CCode, MVT::i8),
10831 Op0.getOperand(1));
10833 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10837 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10838 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10839 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10841 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10842 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10845 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10846 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10847 if (X86CC == X86::COND_INVALID)
10850 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10851 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10852 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10853 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10855 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10859 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10860 static bool isX86LogicalCmp(SDValue Op) {
10861 unsigned Opc = Op.getNode()->getOpcode();
10862 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10863 Opc == X86ISD::SAHF)
10865 if (Op.getResNo() == 1 &&
10866 (Opc == X86ISD::ADD ||
10867 Opc == X86ISD::SUB ||
10868 Opc == X86ISD::ADC ||
10869 Opc == X86ISD::SBB ||
10870 Opc == X86ISD::SMUL ||
10871 Opc == X86ISD::UMUL ||
10872 Opc == X86ISD::INC ||
10873 Opc == X86ISD::DEC ||
10874 Opc == X86ISD::OR ||
10875 Opc == X86ISD::XOR ||
10876 Opc == X86ISD::AND))
10879 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10885 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10886 if (V.getOpcode() != ISD::TRUNCATE)
10889 SDValue VOp0 = V.getOperand(0);
10890 unsigned InBits = VOp0.getValueSizeInBits();
10891 unsigned Bits = V.getValueSizeInBits();
10892 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10895 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10896 bool addTest = true;
10897 SDValue Cond = Op.getOperand(0);
10898 SDValue Op1 = Op.getOperand(1);
10899 SDValue Op2 = Op.getOperand(2);
10901 EVT VT = Op1.getValueType();
10904 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10905 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10906 // sequence later on.
10907 if (Cond.getOpcode() == ISD::SETCC &&
10908 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10909 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10910 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10911 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10912 int SSECC = translateX86FSETCC(
10913 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10916 if (Subtarget->hasAVX512()) {
10917 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10918 DAG.getConstant(SSECC, MVT::i8));
10919 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10921 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10922 DAG.getConstant(SSECC, MVT::i8));
10923 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10924 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10925 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10929 if (Cond.getOpcode() == ISD::SETCC) {
10930 SDValue NewCond = LowerSETCC(Cond, DAG);
10931 if (NewCond.getNode())
10935 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10936 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10937 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10938 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10939 if (Cond.getOpcode() == X86ISD::SETCC &&
10940 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10941 isZero(Cond.getOperand(1).getOperand(1))) {
10942 SDValue Cmp = Cond.getOperand(1);
10944 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10946 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10947 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10948 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10950 SDValue CmpOp0 = Cmp.getOperand(0);
10951 // Apply further optimizations for special cases
10952 // (select (x != 0), -1, 0) -> neg & sbb
10953 // (select (x == 0), 0, -1) -> neg & sbb
10954 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10955 if (YC->isNullValue() &&
10956 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10957 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10958 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10959 DAG.getConstant(0, CmpOp0.getValueType()),
10961 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10962 DAG.getConstant(X86::COND_B, MVT::i8),
10963 SDValue(Neg.getNode(), 1));
10967 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10968 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10969 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10971 SDValue Res = // Res = 0 or -1.
10972 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10973 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10975 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10976 Res = DAG.getNOT(DL, Res, Res.getValueType());
10978 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10979 if (!N2C || !N2C->isNullValue())
10980 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10985 // Look past (and (setcc_carry (cmp ...)), 1).
10986 if (Cond.getOpcode() == ISD::AND &&
10987 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10988 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10989 if (C && C->getAPIntValue() == 1)
10990 Cond = Cond.getOperand(0);
10993 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10994 // setting operand in place of the X86ISD::SETCC.
10995 unsigned CondOpcode = Cond.getOpcode();
10996 if (CondOpcode == X86ISD::SETCC ||
10997 CondOpcode == X86ISD::SETCC_CARRY) {
10998 CC = Cond.getOperand(0);
11000 SDValue Cmp = Cond.getOperand(1);
11001 unsigned Opc = Cmp.getOpcode();
11002 MVT VT = Op.getSimpleValueType();
11004 bool IllegalFPCMov = false;
11005 if (VT.isFloatingPoint() && !VT.isVector() &&
11006 !isScalarFPTypeInSSEReg(VT)) // FPStack?
11007 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11009 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11010 Opc == X86ISD::BT) { // FIXME
11014 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11015 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11016 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11017 Cond.getOperand(0).getValueType() != MVT::i8)) {
11018 SDValue LHS = Cond.getOperand(0);
11019 SDValue RHS = Cond.getOperand(1);
11020 unsigned X86Opcode;
11023 switch (CondOpcode) {
11024 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11025 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11026 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11027 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11028 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11029 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11030 default: llvm_unreachable("unexpected overflowing operator");
11032 if (CondOpcode == ISD::UMULO)
11033 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11036 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11038 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11040 if (CondOpcode == ISD::UMULO)
11041 Cond = X86Op.getValue(2);
11043 Cond = X86Op.getValue(1);
11045 CC = DAG.getConstant(X86Cond, MVT::i8);
11050 // Look pass the truncate if the high bits are known zero.
11051 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11052 Cond = Cond.getOperand(0);
11054 // We know the result of AND is compared against zero. Try to match
11056 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11057 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11058 if (NewSetCC.getNode()) {
11059 CC = NewSetCC.getOperand(0);
11060 Cond = NewSetCC.getOperand(1);
11067 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11068 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11071 // a < b ? -1 : 0 -> RES = ~setcc_carry
11072 // a < b ? 0 : -1 -> RES = setcc_carry
11073 // a >= b ? -1 : 0 -> RES = setcc_carry
11074 // a >= b ? 0 : -1 -> RES = ~setcc_carry
11075 if (Cond.getOpcode() == X86ISD::SUB) {
11076 Cond = ConvertCmpIfNecessary(Cond, DAG);
11077 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11079 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11080 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11081 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11082 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11083 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11084 return DAG.getNOT(DL, Res, Res.getValueType());
11089 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11090 // widen the cmov and push the truncate through. This avoids introducing a new
11091 // branch during isel and doesn't add any extensions.
11092 if (Op.getValueType() == MVT::i8 &&
11093 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11094 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11095 if (T1.getValueType() == T2.getValueType() &&
11096 // Blacklist CopyFromReg to avoid partial register stalls.
11097 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11098 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11099 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11100 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11104 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11105 // condition is true.
11106 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11107 SDValue Ops[] = { Op2, Op1, CC, Cond };
11108 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11111 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11112 MVT VT = Op->getSimpleValueType(0);
11113 SDValue In = Op->getOperand(0);
11114 MVT InVT = In.getSimpleValueType();
11117 unsigned int NumElts = VT.getVectorNumElements();
11118 if (NumElts != 8 && NumElts != 16)
11121 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11122 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11124 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11125 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11127 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11128 Constant *C = ConstantInt::get(*DAG.getContext(),
11129 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11131 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11132 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11133 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11134 MachinePointerInfo::getConstantPool(),
11135 false, false, false, Alignment);
11136 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11137 if (VT.is512BitVector())
11139 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11142 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11143 SelectionDAG &DAG) {
11144 MVT VT = Op->getSimpleValueType(0);
11145 SDValue In = Op->getOperand(0);
11146 MVT InVT = In.getSimpleValueType();
11149 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11150 return LowerSIGN_EXTEND_AVX512(Op, DAG);
11152 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11153 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11154 (VT != MVT::v16i16 || InVT != MVT::v16i8))
11157 if (Subtarget->hasInt256())
11158 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11160 // Optimize vectors in AVX mode
11161 // Sign extend v8i16 to v8i32 and
11164 // Divide input vector into two parts
11165 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11166 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11167 // concat the vectors to original VT
11169 unsigned NumElems = InVT.getVectorNumElements();
11170 SDValue Undef = DAG.getUNDEF(InVT);
11172 SmallVector<int,8> ShufMask1(NumElems, -1);
11173 for (unsigned i = 0; i != NumElems/2; ++i)
11176 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11178 SmallVector<int,8> ShufMask2(NumElems, -1);
11179 for (unsigned i = 0; i != NumElems/2; ++i)
11180 ShufMask2[i] = i + NumElems/2;
11182 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11184 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11185 VT.getVectorNumElements()/2);
11187 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11188 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11190 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11193 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11194 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11195 // from the AND / OR.
11196 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11197 Opc = Op.getOpcode();
11198 if (Opc != ISD::OR && Opc != ISD::AND)
11200 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11201 Op.getOperand(0).hasOneUse() &&
11202 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11203 Op.getOperand(1).hasOneUse());
11206 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11207 // 1 and that the SETCC node has a single use.
11208 static bool isXor1OfSetCC(SDValue Op) {
11209 if (Op.getOpcode() != ISD::XOR)
11211 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11212 if (N1C && N1C->getAPIntValue() == 1) {
11213 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11214 Op.getOperand(0).hasOneUse();
11219 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11220 bool addTest = true;
11221 SDValue Chain = Op.getOperand(0);
11222 SDValue Cond = Op.getOperand(1);
11223 SDValue Dest = Op.getOperand(2);
11226 bool Inverted = false;
11228 if (Cond.getOpcode() == ISD::SETCC) {
11229 // Check for setcc([su]{add,sub,mul}o == 0).
11230 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11231 isa<ConstantSDNode>(Cond.getOperand(1)) &&
11232 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11233 Cond.getOperand(0).getResNo() == 1 &&
11234 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11235 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11236 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11237 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11238 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11239 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11241 Cond = Cond.getOperand(0);
11243 SDValue NewCond = LowerSETCC(Cond, DAG);
11244 if (NewCond.getNode())
11249 // FIXME: LowerXALUO doesn't handle these!!
11250 else if (Cond.getOpcode() == X86ISD::ADD ||
11251 Cond.getOpcode() == X86ISD::SUB ||
11252 Cond.getOpcode() == X86ISD::SMUL ||
11253 Cond.getOpcode() == X86ISD::UMUL)
11254 Cond = LowerXALUO(Cond, DAG);
11257 // Look pass (and (setcc_carry (cmp ...)), 1).
11258 if (Cond.getOpcode() == ISD::AND &&
11259 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11260 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11261 if (C && C->getAPIntValue() == 1)
11262 Cond = Cond.getOperand(0);
11265 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11266 // setting operand in place of the X86ISD::SETCC.
11267 unsigned CondOpcode = Cond.getOpcode();
11268 if (CondOpcode == X86ISD::SETCC ||
11269 CondOpcode == X86ISD::SETCC_CARRY) {
11270 CC = Cond.getOperand(0);
11272 SDValue Cmp = Cond.getOperand(1);
11273 unsigned Opc = Cmp.getOpcode();
11274 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11275 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11279 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11283 // These can only come from an arithmetic instruction with overflow,
11284 // e.g. SADDO, UADDO.
11285 Cond = Cond.getNode()->getOperand(1);
11291 CondOpcode = Cond.getOpcode();
11292 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11293 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11294 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11295 Cond.getOperand(0).getValueType() != MVT::i8)) {
11296 SDValue LHS = Cond.getOperand(0);
11297 SDValue RHS = Cond.getOperand(1);
11298 unsigned X86Opcode;
11301 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11302 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11304 switch (CondOpcode) {
11305 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11307 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11309 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11312 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11313 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11315 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11317 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11320 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11321 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11322 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11323 default: llvm_unreachable("unexpected overflowing operator");
11326 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11327 if (CondOpcode == ISD::UMULO)
11328 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11331 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11333 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11335 if (CondOpcode == ISD::UMULO)
11336 Cond = X86Op.getValue(2);
11338 Cond = X86Op.getValue(1);
11340 CC = DAG.getConstant(X86Cond, MVT::i8);
11344 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11345 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11346 if (CondOpc == ISD::OR) {
11347 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11348 // two branches instead of an explicit OR instruction with a
11350 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11351 isX86LogicalCmp(Cmp)) {
11352 CC = Cond.getOperand(0).getOperand(0);
11353 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11354 Chain, Dest, CC, Cmp);
11355 CC = Cond.getOperand(1).getOperand(0);
11359 } else { // ISD::AND
11360 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11361 // two branches instead of an explicit AND instruction with a
11362 // separate test. However, we only do this if this block doesn't
11363 // have a fall-through edge, because this requires an explicit
11364 // jmp when the condition is false.
11365 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11366 isX86LogicalCmp(Cmp) &&
11367 Op.getNode()->hasOneUse()) {
11368 X86::CondCode CCode =
11369 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11370 CCode = X86::GetOppositeBranchCondition(CCode);
11371 CC = DAG.getConstant(CCode, MVT::i8);
11372 SDNode *User = *Op.getNode()->use_begin();
11373 // Look for an unconditional branch following this conditional branch.
11374 // We need this because we need to reverse the successors in order
11375 // to implement FCMP_OEQ.
11376 if (User->getOpcode() == ISD::BR) {
11377 SDValue FalseBB = User->getOperand(1);
11379 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11380 assert(NewBR == User);
11384 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11385 Chain, Dest, CC, Cmp);
11386 X86::CondCode CCode =
11387 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11388 CCode = X86::GetOppositeBranchCondition(CCode);
11389 CC = DAG.getConstant(CCode, MVT::i8);
11395 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11396 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11397 // It should be transformed during dag combiner except when the condition
11398 // is set by a arithmetics with overflow node.
11399 X86::CondCode CCode =
11400 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11401 CCode = X86::GetOppositeBranchCondition(CCode);
11402 CC = DAG.getConstant(CCode, MVT::i8);
11403 Cond = Cond.getOperand(0).getOperand(1);
11405 } else if (Cond.getOpcode() == ISD::SETCC &&
11406 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11407 // For FCMP_OEQ, we can emit
11408 // two branches instead of an explicit AND instruction with a
11409 // separate test. However, we only do this if this block doesn't
11410 // have a fall-through edge, because this requires an explicit
11411 // jmp when the condition is false.
11412 if (Op.getNode()->hasOneUse()) {
11413 SDNode *User = *Op.getNode()->use_begin();
11414 // Look for an unconditional branch following this conditional branch.
11415 // We need this because we need to reverse the successors in order
11416 // to implement FCMP_OEQ.
11417 if (User->getOpcode() == ISD::BR) {
11418 SDValue FalseBB = User->getOperand(1);
11420 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11421 assert(NewBR == User);
11425 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11426 Cond.getOperand(0), Cond.getOperand(1));
11427 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11428 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11429 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11430 Chain, Dest, CC, Cmp);
11431 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11436 } else if (Cond.getOpcode() == ISD::SETCC &&
11437 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11438 // For FCMP_UNE, we can emit
11439 // two branches instead of an explicit AND instruction with a
11440 // separate test. However, we only do this if this block doesn't
11441 // have a fall-through edge, because this requires an explicit
11442 // jmp when the condition is false.
11443 if (Op.getNode()->hasOneUse()) {
11444 SDNode *User = *Op.getNode()->use_begin();
11445 // Look for an unconditional branch following this conditional branch.
11446 // We need this because we need to reverse the successors in order
11447 // to implement FCMP_UNE.
11448 if (User->getOpcode() == ISD::BR) {
11449 SDValue FalseBB = User->getOperand(1);
11451 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11452 assert(NewBR == User);
11455 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11456 Cond.getOperand(0), Cond.getOperand(1));
11457 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11458 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11459 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11460 Chain, Dest, CC, Cmp);
11461 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11471 // Look pass the truncate if the high bits are known zero.
11472 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11473 Cond = Cond.getOperand(0);
11475 // We know the result of AND is compared against zero. Try to match
11477 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11478 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11479 if (NewSetCC.getNode()) {
11480 CC = NewSetCC.getOperand(0);
11481 Cond = NewSetCC.getOperand(1);
11488 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11489 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11491 Cond = ConvertCmpIfNecessary(Cond, DAG);
11492 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11493 Chain, Dest, CC, Cond);
11496 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11497 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11498 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11499 // that the guard pages used by the OS virtual memory manager are allocated in
11500 // correct sequence.
11502 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11503 SelectionDAG &DAG) const {
11504 MachineFunction &MF = DAG.getMachineFunction();
11505 bool SplitStack = MF.shouldSplitStack();
11506 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11511 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11512 SDNode* Node = Op.getNode();
11514 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11515 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11516 " not tell us which reg is the stack pointer!");
11517 EVT VT = Node->getValueType(0);
11518 SDValue Tmp1 = SDValue(Node, 0);
11519 SDValue Tmp2 = SDValue(Node, 1);
11520 SDValue Tmp3 = Node->getOperand(2);
11521 SDValue Chain = Tmp1.getOperand(0);
11523 // Chain the dynamic stack allocation so that it doesn't modify the stack
11524 // pointer when other instructions are using the stack.
11525 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11528 SDValue Size = Tmp2.getOperand(1);
11529 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11530 Chain = SP.getValue(1);
11531 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11532 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11533 unsigned StackAlign = TFI.getStackAlignment();
11534 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11535 if (Align > StackAlign)
11536 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11537 DAG.getConstant(-(uint64_t)Align, VT));
11538 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11540 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11541 DAG.getIntPtrConstant(0, true), SDValue(),
11544 SDValue Ops[2] = { Tmp1, Tmp2 };
11545 return DAG.getMergeValues(Ops, dl);
11549 SDValue Chain = Op.getOperand(0);
11550 SDValue Size = Op.getOperand(1);
11551 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11552 EVT VT = Op.getNode()->getValueType(0);
11554 bool Is64Bit = Subtarget->is64Bit();
11555 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11558 MachineRegisterInfo &MRI = MF.getRegInfo();
11561 // The 64 bit implementation of segmented stacks needs to clobber both r10
11562 // r11. This makes it impossible to use it along with nested parameters.
11563 const Function *F = MF.getFunction();
11565 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11567 if (I->hasNestAttr())
11568 report_fatal_error("Cannot use segmented stacks with functions that "
11569 "have nested arguments.");
11572 const TargetRegisterClass *AddrRegClass =
11573 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11574 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11575 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11576 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11577 DAG.getRegister(Vreg, SPTy));
11578 SDValue Ops1[2] = { Value, Chain };
11579 return DAG.getMergeValues(Ops1, dl);
11582 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11584 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11585 Flag = Chain.getValue(1);
11586 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11588 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11590 const X86RegisterInfo *RegInfo =
11591 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11592 unsigned SPReg = RegInfo->getStackRegister();
11593 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11594 Chain = SP.getValue(1);
11597 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11598 DAG.getConstant(-(uint64_t)Align, VT));
11599 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11602 SDValue Ops1[2] = { SP, Chain };
11603 return DAG.getMergeValues(Ops1, dl);
11607 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11608 MachineFunction &MF = DAG.getMachineFunction();
11609 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11611 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11614 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11615 // vastart just stores the address of the VarArgsFrameIndex slot into the
11616 // memory location argument.
11617 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11619 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11620 MachinePointerInfo(SV), false, false, 0);
11624 // gp_offset (0 - 6 * 8)
11625 // fp_offset (48 - 48 + 8 * 16)
11626 // overflow_arg_area (point to parameters coming in memory).
11628 SmallVector<SDValue, 8> MemOps;
11629 SDValue FIN = Op.getOperand(1);
11631 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11632 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11634 FIN, MachinePointerInfo(SV), false, false, 0);
11635 MemOps.push_back(Store);
11638 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11639 FIN, DAG.getIntPtrConstant(4));
11640 Store = DAG.getStore(Op.getOperand(0), DL,
11641 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11643 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11644 MemOps.push_back(Store);
11646 // Store ptr to overflow_arg_area
11647 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11648 FIN, DAG.getIntPtrConstant(4));
11649 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11651 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11652 MachinePointerInfo(SV, 8),
11654 MemOps.push_back(Store);
11656 // Store ptr to reg_save_area.
11657 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11658 FIN, DAG.getIntPtrConstant(8));
11659 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11661 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11662 MachinePointerInfo(SV, 16), false, false, 0);
11663 MemOps.push_back(Store);
11664 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11667 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11668 assert(Subtarget->is64Bit() &&
11669 "LowerVAARG only handles 64-bit va_arg!");
11670 assert((Subtarget->isTargetLinux() ||
11671 Subtarget->isTargetDarwin()) &&
11672 "Unhandled target in LowerVAARG");
11673 assert(Op.getNode()->getNumOperands() == 4);
11674 SDValue Chain = Op.getOperand(0);
11675 SDValue SrcPtr = Op.getOperand(1);
11676 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11677 unsigned Align = Op.getConstantOperandVal(3);
11680 EVT ArgVT = Op.getNode()->getValueType(0);
11681 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11682 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11685 // Decide which area this value should be read from.
11686 // TODO: Implement the AMD64 ABI in its entirety. This simple
11687 // selection mechanism works only for the basic types.
11688 if (ArgVT == MVT::f80) {
11689 llvm_unreachable("va_arg for f80 not yet implemented");
11690 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11691 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11692 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11693 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11695 llvm_unreachable("Unhandled argument type in LowerVAARG");
11698 if (ArgMode == 2) {
11699 // Sanity Check: Make sure using fp_offset makes sense.
11700 assert(!getTargetMachine().Options.UseSoftFloat &&
11701 !(DAG.getMachineFunction()
11702 .getFunction()->getAttributes()
11703 .hasAttribute(AttributeSet::FunctionIndex,
11704 Attribute::NoImplicitFloat)) &&
11705 Subtarget->hasSSE1());
11708 // Insert VAARG_64 node into the DAG
11709 // VAARG_64 returns two values: Variable Argument Address, Chain
11710 SmallVector<SDValue, 11> InstOps;
11711 InstOps.push_back(Chain);
11712 InstOps.push_back(SrcPtr);
11713 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11714 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11715 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11716 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11717 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11718 VTs, InstOps, MVT::i64,
11719 MachinePointerInfo(SV),
11721 /*Volatile=*/false,
11723 /*WriteMem=*/true);
11724 Chain = VAARG.getValue(1);
11726 // Load the next argument and return it
11727 return DAG.getLoad(ArgVT, dl,
11730 MachinePointerInfo(),
11731 false, false, false, 0);
11734 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11735 SelectionDAG &DAG) {
11736 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11737 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11738 SDValue Chain = Op.getOperand(0);
11739 SDValue DstPtr = Op.getOperand(1);
11740 SDValue SrcPtr = Op.getOperand(2);
11741 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11742 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11745 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11746 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11748 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11751 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11752 // amount is a constant. Takes immediate version of shift as input.
11753 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11754 SDValue SrcOp, uint64_t ShiftAmt,
11755 SelectionDAG &DAG) {
11756 MVT ElementType = VT.getVectorElementType();
11758 // Fold this packed shift into its first operand if ShiftAmt is 0.
11762 // Check for ShiftAmt >= element width
11763 if (ShiftAmt >= ElementType.getSizeInBits()) {
11764 if (Opc == X86ISD::VSRAI)
11765 ShiftAmt = ElementType.getSizeInBits() - 1;
11767 return DAG.getConstant(0, VT);
11770 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11771 && "Unknown target vector shift-by-constant node");
11773 // Fold this packed vector shift into a build vector if SrcOp is a
11774 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11775 if (VT == SrcOp.getSimpleValueType() &&
11776 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11777 SmallVector<SDValue, 8> Elts;
11778 unsigned NumElts = SrcOp->getNumOperands();
11779 ConstantSDNode *ND;
11782 default: llvm_unreachable(nullptr);
11783 case X86ISD::VSHLI:
11784 for (unsigned i=0; i!=NumElts; ++i) {
11785 SDValue CurrentOp = SrcOp->getOperand(i);
11786 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11787 Elts.push_back(CurrentOp);
11790 ND = cast<ConstantSDNode>(CurrentOp);
11791 const APInt &C = ND->getAPIntValue();
11792 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11795 case X86ISD::VSRLI:
11796 for (unsigned i=0; i!=NumElts; ++i) {
11797 SDValue CurrentOp = SrcOp->getOperand(i);
11798 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11799 Elts.push_back(CurrentOp);
11802 ND = cast<ConstantSDNode>(CurrentOp);
11803 const APInt &C = ND->getAPIntValue();
11804 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11807 case X86ISD::VSRAI:
11808 for (unsigned i=0; i!=NumElts; ++i) {
11809 SDValue CurrentOp = SrcOp->getOperand(i);
11810 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11811 Elts.push_back(CurrentOp);
11814 ND = cast<ConstantSDNode>(CurrentOp);
11815 const APInt &C = ND->getAPIntValue();
11816 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11821 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11824 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11827 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11828 // may or may not be a constant. Takes immediate version of shift as input.
11829 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11830 SDValue SrcOp, SDValue ShAmt,
11831 SelectionDAG &DAG) {
11832 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11834 // Catch shift-by-constant.
11835 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11836 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11837 CShAmt->getZExtValue(), DAG);
11839 // Change opcode to non-immediate version
11841 default: llvm_unreachable("Unknown target vector shift node");
11842 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11843 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11844 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11847 // Need to build a vector containing shift amount
11848 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11851 ShOps[1] = DAG.getConstant(0, MVT::i32);
11852 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11853 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11855 // The return type has to be a 128-bit type with the same element
11856 // type as the input type.
11857 MVT EltVT = VT.getVectorElementType();
11858 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11860 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11861 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11864 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11866 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11868 default: return SDValue(); // Don't custom lower most intrinsics.
11869 // Comparison intrinsics.
11870 case Intrinsic::x86_sse_comieq_ss:
11871 case Intrinsic::x86_sse_comilt_ss:
11872 case Intrinsic::x86_sse_comile_ss:
11873 case Intrinsic::x86_sse_comigt_ss:
11874 case Intrinsic::x86_sse_comige_ss:
11875 case Intrinsic::x86_sse_comineq_ss:
11876 case Intrinsic::x86_sse_ucomieq_ss:
11877 case Intrinsic::x86_sse_ucomilt_ss:
11878 case Intrinsic::x86_sse_ucomile_ss:
11879 case Intrinsic::x86_sse_ucomigt_ss:
11880 case Intrinsic::x86_sse_ucomige_ss:
11881 case Intrinsic::x86_sse_ucomineq_ss:
11882 case Intrinsic::x86_sse2_comieq_sd:
11883 case Intrinsic::x86_sse2_comilt_sd:
11884 case Intrinsic::x86_sse2_comile_sd:
11885 case Intrinsic::x86_sse2_comigt_sd:
11886 case Intrinsic::x86_sse2_comige_sd:
11887 case Intrinsic::x86_sse2_comineq_sd:
11888 case Intrinsic::x86_sse2_ucomieq_sd:
11889 case Intrinsic::x86_sse2_ucomilt_sd:
11890 case Intrinsic::x86_sse2_ucomile_sd:
11891 case Intrinsic::x86_sse2_ucomigt_sd:
11892 case Intrinsic::x86_sse2_ucomige_sd:
11893 case Intrinsic::x86_sse2_ucomineq_sd: {
11897 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11898 case Intrinsic::x86_sse_comieq_ss:
11899 case Intrinsic::x86_sse2_comieq_sd:
11900 Opc = X86ISD::COMI;
11903 case Intrinsic::x86_sse_comilt_ss:
11904 case Intrinsic::x86_sse2_comilt_sd:
11905 Opc = X86ISD::COMI;
11908 case Intrinsic::x86_sse_comile_ss:
11909 case Intrinsic::x86_sse2_comile_sd:
11910 Opc = X86ISD::COMI;
11913 case Intrinsic::x86_sse_comigt_ss:
11914 case Intrinsic::x86_sse2_comigt_sd:
11915 Opc = X86ISD::COMI;
11918 case Intrinsic::x86_sse_comige_ss:
11919 case Intrinsic::x86_sse2_comige_sd:
11920 Opc = X86ISD::COMI;
11923 case Intrinsic::x86_sse_comineq_ss:
11924 case Intrinsic::x86_sse2_comineq_sd:
11925 Opc = X86ISD::COMI;
11928 case Intrinsic::x86_sse_ucomieq_ss:
11929 case Intrinsic::x86_sse2_ucomieq_sd:
11930 Opc = X86ISD::UCOMI;
11933 case Intrinsic::x86_sse_ucomilt_ss:
11934 case Intrinsic::x86_sse2_ucomilt_sd:
11935 Opc = X86ISD::UCOMI;
11938 case Intrinsic::x86_sse_ucomile_ss:
11939 case Intrinsic::x86_sse2_ucomile_sd:
11940 Opc = X86ISD::UCOMI;
11943 case Intrinsic::x86_sse_ucomigt_ss:
11944 case Intrinsic::x86_sse2_ucomigt_sd:
11945 Opc = X86ISD::UCOMI;
11948 case Intrinsic::x86_sse_ucomige_ss:
11949 case Intrinsic::x86_sse2_ucomige_sd:
11950 Opc = X86ISD::UCOMI;
11953 case Intrinsic::x86_sse_ucomineq_ss:
11954 case Intrinsic::x86_sse2_ucomineq_sd:
11955 Opc = X86ISD::UCOMI;
11960 SDValue LHS = Op.getOperand(1);
11961 SDValue RHS = Op.getOperand(2);
11962 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11963 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11964 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11965 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11966 DAG.getConstant(X86CC, MVT::i8), Cond);
11967 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11970 // Arithmetic intrinsics.
11971 case Intrinsic::x86_sse2_pmulu_dq:
11972 case Intrinsic::x86_avx2_pmulu_dq:
11973 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11974 Op.getOperand(1), Op.getOperand(2));
11976 case Intrinsic::x86_sse41_pmuldq:
11977 case Intrinsic::x86_avx2_pmul_dq:
11978 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11979 Op.getOperand(1), Op.getOperand(2));
11981 case Intrinsic::x86_sse2_pmulhu_w:
11982 case Intrinsic::x86_avx2_pmulhu_w:
11983 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11984 Op.getOperand(1), Op.getOperand(2));
11986 case Intrinsic::x86_sse2_pmulh_w:
11987 case Intrinsic::x86_avx2_pmulh_w:
11988 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11989 Op.getOperand(1), Op.getOperand(2));
11991 // SSE2/AVX2 sub with unsigned saturation intrinsics
11992 case Intrinsic::x86_sse2_psubus_b:
11993 case Intrinsic::x86_sse2_psubus_w:
11994 case Intrinsic::x86_avx2_psubus_b:
11995 case Intrinsic::x86_avx2_psubus_w:
11996 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11997 Op.getOperand(1), Op.getOperand(2));
11999 // SSE3/AVX horizontal add/sub intrinsics
12000 case Intrinsic::x86_sse3_hadd_ps:
12001 case Intrinsic::x86_sse3_hadd_pd:
12002 case Intrinsic::x86_avx_hadd_ps_256:
12003 case Intrinsic::x86_avx_hadd_pd_256:
12004 case Intrinsic::x86_sse3_hsub_ps:
12005 case Intrinsic::x86_sse3_hsub_pd:
12006 case Intrinsic::x86_avx_hsub_ps_256:
12007 case Intrinsic::x86_avx_hsub_pd_256:
12008 case Intrinsic::x86_ssse3_phadd_w_128:
12009 case Intrinsic::x86_ssse3_phadd_d_128:
12010 case Intrinsic::x86_avx2_phadd_w:
12011 case Intrinsic::x86_avx2_phadd_d:
12012 case Intrinsic::x86_ssse3_phsub_w_128:
12013 case Intrinsic::x86_ssse3_phsub_d_128:
12014 case Intrinsic::x86_avx2_phsub_w:
12015 case Intrinsic::x86_avx2_phsub_d: {
12018 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12019 case Intrinsic::x86_sse3_hadd_ps:
12020 case Intrinsic::x86_sse3_hadd_pd:
12021 case Intrinsic::x86_avx_hadd_ps_256:
12022 case Intrinsic::x86_avx_hadd_pd_256:
12023 Opcode = X86ISD::FHADD;
12025 case Intrinsic::x86_sse3_hsub_ps:
12026 case Intrinsic::x86_sse3_hsub_pd:
12027 case Intrinsic::x86_avx_hsub_ps_256:
12028 case Intrinsic::x86_avx_hsub_pd_256:
12029 Opcode = X86ISD::FHSUB;
12031 case Intrinsic::x86_ssse3_phadd_w_128:
12032 case Intrinsic::x86_ssse3_phadd_d_128:
12033 case Intrinsic::x86_avx2_phadd_w:
12034 case Intrinsic::x86_avx2_phadd_d:
12035 Opcode = X86ISD::HADD;
12037 case Intrinsic::x86_ssse3_phsub_w_128:
12038 case Intrinsic::x86_ssse3_phsub_d_128:
12039 case Intrinsic::x86_avx2_phsub_w:
12040 case Intrinsic::x86_avx2_phsub_d:
12041 Opcode = X86ISD::HSUB;
12044 return DAG.getNode(Opcode, dl, Op.getValueType(),
12045 Op.getOperand(1), Op.getOperand(2));
12048 // SSE2/SSE41/AVX2 integer max/min intrinsics.
12049 case Intrinsic::x86_sse2_pmaxu_b:
12050 case Intrinsic::x86_sse41_pmaxuw:
12051 case Intrinsic::x86_sse41_pmaxud:
12052 case Intrinsic::x86_avx2_pmaxu_b:
12053 case Intrinsic::x86_avx2_pmaxu_w:
12054 case Intrinsic::x86_avx2_pmaxu_d:
12055 case Intrinsic::x86_sse2_pminu_b:
12056 case Intrinsic::x86_sse41_pminuw:
12057 case Intrinsic::x86_sse41_pminud:
12058 case Intrinsic::x86_avx2_pminu_b:
12059 case Intrinsic::x86_avx2_pminu_w:
12060 case Intrinsic::x86_avx2_pminu_d:
12061 case Intrinsic::x86_sse41_pmaxsb:
12062 case Intrinsic::x86_sse2_pmaxs_w:
12063 case Intrinsic::x86_sse41_pmaxsd:
12064 case Intrinsic::x86_avx2_pmaxs_b:
12065 case Intrinsic::x86_avx2_pmaxs_w:
12066 case Intrinsic::x86_avx2_pmaxs_d:
12067 case Intrinsic::x86_sse41_pminsb:
12068 case Intrinsic::x86_sse2_pmins_w:
12069 case Intrinsic::x86_sse41_pminsd:
12070 case Intrinsic::x86_avx2_pmins_b:
12071 case Intrinsic::x86_avx2_pmins_w:
12072 case Intrinsic::x86_avx2_pmins_d: {
12075 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12076 case Intrinsic::x86_sse2_pmaxu_b:
12077 case Intrinsic::x86_sse41_pmaxuw:
12078 case Intrinsic::x86_sse41_pmaxud:
12079 case Intrinsic::x86_avx2_pmaxu_b:
12080 case Intrinsic::x86_avx2_pmaxu_w:
12081 case Intrinsic::x86_avx2_pmaxu_d:
12082 Opcode = X86ISD::UMAX;
12084 case Intrinsic::x86_sse2_pminu_b:
12085 case Intrinsic::x86_sse41_pminuw:
12086 case Intrinsic::x86_sse41_pminud:
12087 case Intrinsic::x86_avx2_pminu_b:
12088 case Intrinsic::x86_avx2_pminu_w:
12089 case Intrinsic::x86_avx2_pminu_d:
12090 Opcode = X86ISD::UMIN;
12092 case Intrinsic::x86_sse41_pmaxsb:
12093 case Intrinsic::x86_sse2_pmaxs_w:
12094 case Intrinsic::x86_sse41_pmaxsd:
12095 case Intrinsic::x86_avx2_pmaxs_b:
12096 case Intrinsic::x86_avx2_pmaxs_w:
12097 case Intrinsic::x86_avx2_pmaxs_d:
12098 Opcode = X86ISD::SMAX;
12100 case Intrinsic::x86_sse41_pminsb:
12101 case Intrinsic::x86_sse2_pmins_w:
12102 case Intrinsic::x86_sse41_pminsd:
12103 case Intrinsic::x86_avx2_pmins_b:
12104 case Intrinsic::x86_avx2_pmins_w:
12105 case Intrinsic::x86_avx2_pmins_d:
12106 Opcode = X86ISD::SMIN;
12109 return DAG.getNode(Opcode, dl, Op.getValueType(),
12110 Op.getOperand(1), Op.getOperand(2));
12113 // SSE/SSE2/AVX floating point max/min intrinsics.
12114 case Intrinsic::x86_sse_max_ps:
12115 case Intrinsic::x86_sse2_max_pd:
12116 case Intrinsic::x86_avx_max_ps_256:
12117 case Intrinsic::x86_avx_max_pd_256:
12118 case Intrinsic::x86_sse_min_ps:
12119 case Intrinsic::x86_sse2_min_pd:
12120 case Intrinsic::x86_avx_min_ps_256:
12121 case Intrinsic::x86_avx_min_pd_256: {
12124 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12125 case Intrinsic::x86_sse_max_ps:
12126 case Intrinsic::x86_sse2_max_pd:
12127 case Intrinsic::x86_avx_max_ps_256:
12128 case Intrinsic::x86_avx_max_pd_256:
12129 Opcode = X86ISD::FMAX;
12131 case Intrinsic::x86_sse_min_ps:
12132 case Intrinsic::x86_sse2_min_pd:
12133 case Intrinsic::x86_avx_min_ps_256:
12134 case Intrinsic::x86_avx_min_pd_256:
12135 Opcode = X86ISD::FMIN;
12138 return DAG.getNode(Opcode, dl, Op.getValueType(),
12139 Op.getOperand(1), Op.getOperand(2));
12142 // AVX2 variable shift intrinsics
12143 case Intrinsic::x86_avx2_psllv_d:
12144 case Intrinsic::x86_avx2_psllv_q:
12145 case Intrinsic::x86_avx2_psllv_d_256:
12146 case Intrinsic::x86_avx2_psllv_q_256:
12147 case Intrinsic::x86_avx2_psrlv_d:
12148 case Intrinsic::x86_avx2_psrlv_q:
12149 case Intrinsic::x86_avx2_psrlv_d_256:
12150 case Intrinsic::x86_avx2_psrlv_q_256:
12151 case Intrinsic::x86_avx2_psrav_d:
12152 case Intrinsic::x86_avx2_psrav_d_256: {
12155 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12156 case Intrinsic::x86_avx2_psllv_d:
12157 case Intrinsic::x86_avx2_psllv_q:
12158 case Intrinsic::x86_avx2_psllv_d_256:
12159 case Intrinsic::x86_avx2_psllv_q_256:
12162 case Intrinsic::x86_avx2_psrlv_d:
12163 case Intrinsic::x86_avx2_psrlv_q:
12164 case Intrinsic::x86_avx2_psrlv_d_256:
12165 case Intrinsic::x86_avx2_psrlv_q_256:
12168 case Intrinsic::x86_avx2_psrav_d:
12169 case Intrinsic::x86_avx2_psrav_d_256:
12173 return DAG.getNode(Opcode, dl, Op.getValueType(),
12174 Op.getOperand(1), Op.getOperand(2));
12177 case Intrinsic::x86_ssse3_pshuf_b_128:
12178 case Intrinsic::x86_avx2_pshuf_b:
12179 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12180 Op.getOperand(1), Op.getOperand(2));
12182 case Intrinsic::x86_ssse3_psign_b_128:
12183 case Intrinsic::x86_ssse3_psign_w_128:
12184 case Intrinsic::x86_ssse3_psign_d_128:
12185 case Intrinsic::x86_avx2_psign_b:
12186 case Intrinsic::x86_avx2_psign_w:
12187 case Intrinsic::x86_avx2_psign_d:
12188 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12189 Op.getOperand(1), Op.getOperand(2));
12191 case Intrinsic::x86_sse41_insertps:
12192 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12193 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12195 case Intrinsic::x86_avx_vperm2f128_ps_256:
12196 case Intrinsic::x86_avx_vperm2f128_pd_256:
12197 case Intrinsic::x86_avx_vperm2f128_si_256:
12198 case Intrinsic::x86_avx2_vperm2i128:
12199 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12200 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12202 case Intrinsic::x86_avx2_permd:
12203 case Intrinsic::x86_avx2_permps:
12204 // Operands intentionally swapped. Mask is last operand to intrinsic,
12205 // but second operand for node/instruction.
12206 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12207 Op.getOperand(2), Op.getOperand(1));
12209 case Intrinsic::x86_sse_sqrt_ps:
12210 case Intrinsic::x86_sse2_sqrt_pd:
12211 case Intrinsic::x86_avx_sqrt_ps_256:
12212 case Intrinsic::x86_avx_sqrt_pd_256:
12213 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12215 // ptest and testp intrinsics. The intrinsic these come from are designed to
12216 // return an integer value, not just an instruction so lower it to the ptest
12217 // or testp pattern and a setcc for the result.
12218 case Intrinsic::x86_sse41_ptestz:
12219 case Intrinsic::x86_sse41_ptestc:
12220 case Intrinsic::x86_sse41_ptestnzc:
12221 case Intrinsic::x86_avx_ptestz_256:
12222 case Intrinsic::x86_avx_ptestc_256:
12223 case Intrinsic::x86_avx_ptestnzc_256:
12224 case Intrinsic::x86_avx_vtestz_ps:
12225 case Intrinsic::x86_avx_vtestc_ps:
12226 case Intrinsic::x86_avx_vtestnzc_ps:
12227 case Intrinsic::x86_avx_vtestz_pd:
12228 case Intrinsic::x86_avx_vtestc_pd:
12229 case Intrinsic::x86_avx_vtestnzc_pd:
12230 case Intrinsic::x86_avx_vtestz_ps_256:
12231 case Intrinsic::x86_avx_vtestc_ps_256:
12232 case Intrinsic::x86_avx_vtestnzc_ps_256:
12233 case Intrinsic::x86_avx_vtestz_pd_256:
12234 case Intrinsic::x86_avx_vtestc_pd_256:
12235 case Intrinsic::x86_avx_vtestnzc_pd_256: {
12236 bool IsTestPacked = false;
12239 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12240 case Intrinsic::x86_avx_vtestz_ps:
12241 case Intrinsic::x86_avx_vtestz_pd:
12242 case Intrinsic::x86_avx_vtestz_ps_256:
12243 case Intrinsic::x86_avx_vtestz_pd_256:
12244 IsTestPacked = true; // Fallthrough
12245 case Intrinsic::x86_sse41_ptestz:
12246 case Intrinsic::x86_avx_ptestz_256:
12248 X86CC = X86::COND_E;
12250 case Intrinsic::x86_avx_vtestc_ps:
12251 case Intrinsic::x86_avx_vtestc_pd:
12252 case Intrinsic::x86_avx_vtestc_ps_256:
12253 case Intrinsic::x86_avx_vtestc_pd_256:
12254 IsTestPacked = true; // Fallthrough
12255 case Intrinsic::x86_sse41_ptestc:
12256 case Intrinsic::x86_avx_ptestc_256:
12258 X86CC = X86::COND_B;
12260 case Intrinsic::x86_avx_vtestnzc_ps:
12261 case Intrinsic::x86_avx_vtestnzc_pd:
12262 case Intrinsic::x86_avx_vtestnzc_ps_256:
12263 case Intrinsic::x86_avx_vtestnzc_pd_256:
12264 IsTestPacked = true; // Fallthrough
12265 case Intrinsic::x86_sse41_ptestnzc:
12266 case Intrinsic::x86_avx_ptestnzc_256:
12268 X86CC = X86::COND_A;
12272 SDValue LHS = Op.getOperand(1);
12273 SDValue RHS = Op.getOperand(2);
12274 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12275 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12276 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12277 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12278 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12280 case Intrinsic::x86_avx512_kortestz_w:
12281 case Intrinsic::x86_avx512_kortestc_w: {
12282 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12283 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12284 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12285 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12286 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12287 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12288 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12291 // SSE/AVX shift intrinsics
12292 case Intrinsic::x86_sse2_psll_w:
12293 case Intrinsic::x86_sse2_psll_d:
12294 case Intrinsic::x86_sse2_psll_q:
12295 case Intrinsic::x86_avx2_psll_w:
12296 case Intrinsic::x86_avx2_psll_d:
12297 case Intrinsic::x86_avx2_psll_q:
12298 case Intrinsic::x86_sse2_psrl_w:
12299 case Intrinsic::x86_sse2_psrl_d:
12300 case Intrinsic::x86_sse2_psrl_q:
12301 case Intrinsic::x86_avx2_psrl_w:
12302 case Intrinsic::x86_avx2_psrl_d:
12303 case Intrinsic::x86_avx2_psrl_q:
12304 case Intrinsic::x86_sse2_psra_w:
12305 case Intrinsic::x86_sse2_psra_d:
12306 case Intrinsic::x86_avx2_psra_w:
12307 case Intrinsic::x86_avx2_psra_d: {
12310 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12311 case Intrinsic::x86_sse2_psll_w:
12312 case Intrinsic::x86_sse2_psll_d:
12313 case Intrinsic::x86_sse2_psll_q:
12314 case Intrinsic::x86_avx2_psll_w:
12315 case Intrinsic::x86_avx2_psll_d:
12316 case Intrinsic::x86_avx2_psll_q:
12317 Opcode = X86ISD::VSHL;
12319 case Intrinsic::x86_sse2_psrl_w:
12320 case Intrinsic::x86_sse2_psrl_d:
12321 case Intrinsic::x86_sse2_psrl_q:
12322 case Intrinsic::x86_avx2_psrl_w:
12323 case Intrinsic::x86_avx2_psrl_d:
12324 case Intrinsic::x86_avx2_psrl_q:
12325 Opcode = X86ISD::VSRL;
12327 case Intrinsic::x86_sse2_psra_w:
12328 case Intrinsic::x86_sse2_psra_d:
12329 case Intrinsic::x86_avx2_psra_w:
12330 case Intrinsic::x86_avx2_psra_d:
12331 Opcode = X86ISD::VSRA;
12334 return DAG.getNode(Opcode, dl, Op.getValueType(),
12335 Op.getOperand(1), Op.getOperand(2));
12338 // SSE/AVX immediate shift intrinsics
12339 case Intrinsic::x86_sse2_pslli_w:
12340 case Intrinsic::x86_sse2_pslli_d:
12341 case Intrinsic::x86_sse2_pslli_q:
12342 case Intrinsic::x86_avx2_pslli_w:
12343 case Intrinsic::x86_avx2_pslli_d:
12344 case Intrinsic::x86_avx2_pslli_q:
12345 case Intrinsic::x86_sse2_psrli_w:
12346 case Intrinsic::x86_sse2_psrli_d:
12347 case Intrinsic::x86_sse2_psrli_q:
12348 case Intrinsic::x86_avx2_psrli_w:
12349 case Intrinsic::x86_avx2_psrli_d:
12350 case Intrinsic::x86_avx2_psrli_q:
12351 case Intrinsic::x86_sse2_psrai_w:
12352 case Intrinsic::x86_sse2_psrai_d:
12353 case Intrinsic::x86_avx2_psrai_w:
12354 case Intrinsic::x86_avx2_psrai_d: {
12357 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12358 case Intrinsic::x86_sse2_pslli_w:
12359 case Intrinsic::x86_sse2_pslli_d:
12360 case Intrinsic::x86_sse2_pslli_q:
12361 case Intrinsic::x86_avx2_pslli_w:
12362 case Intrinsic::x86_avx2_pslli_d:
12363 case Intrinsic::x86_avx2_pslli_q:
12364 Opcode = X86ISD::VSHLI;
12366 case Intrinsic::x86_sse2_psrli_w:
12367 case Intrinsic::x86_sse2_psrli_d:
12368 case Intrinsic::x86_sse2_psrli_q:
12369 case Intrinsic::x86_avx2_psrli_w:
12370 case Intrinsic::x86_avx2_psrli_d:
12371 case Intrinsic::x86_avx2_psrli_q:
12372 Opcode = X86ISD::VSRLI;
12374 case Intrinsic::x86_sse2_psrai_w:
12375 case Intrinsic::x86_sse2_psrai_d:
12376 case Intrinsic::x86_avx2_psrai_w:
12377 case Intrinsic::x86_avx2_psrai_d:
12378 Opcode = X86ISD::VSRAI;
12381 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12382 Op.getOperand(1), Op.getOperand(2), DAG);
12385 case Intrinsic::x86_sse42_pcmpistria128:
12386 case Intrinsic::x86_sse42_pcmpestria128:
12387 case Intrinsic::x86_sse42_pcmpistric128:
12388 case Intrinsic::x86_sse42_pcmpestric128:
12389 case Intrinsic::x86_sse42_pcmpistrio128:
12390 case Intrinsic::x86_sse42_pcmpestrio128:
12391 case Intrinsic::x86_sse42_pcmpistris128:
12392 case Intrinsic::x86_sse42_pcmpestris128:
12393 case Intrinsic::x86_sse42_pcmpistriz128:
12394 case Intrinsic::x86_sse42_pcmpestriz128: {
12398 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12399 case Intrinsic::x86_sse42_pcmpistria128:
12400 Opcode = X86ISD::PCMPISTRI;
12401 X86CC = X86::COND_A;
12403 case Intrinsic::x86_sse42_pcmpestria128:
12404 Opcode = X86ISD::PCMPESTRI;
12405 X86CC = X86::COND_A;
12407 case Intrinsic::x86_sse42_pcmpistric128:
12408 Opcode = X86ISD::PCMPISTRI;
12409 X86CC = X86::COND_B;
12411 case Intrinsic::x86_sse42_pcmpestric128:
12412 Opcode = X86ISD::PCMPESTRI;
12413 X86CC = X86::COND_B;
12415 case Intrinsic::x86_sse42_pcmpistrio128:
12416 Opcode = X86ISD::PCMPISTRI;
12417 X86CC = X86::COND_O;
12419 case Intrinsic::x86_sse42_pcmpestrio128:
12420 Opcode = X86ISD::PCMPESTRI;
12421 X86CC = X86::COND_O;
12423 case Intrinsic::x86_sse42_pcmpistris128:
12424 Opcode = X86ISD::PCMPISTRI;
12425 X86CC = X86::COND_S;
12427 case Intrinsic::x86_sse42_pcmpestris128:
12428 Opcode = X86ISD::PCMPESTRI;
12429 X86CC = X86::COND_S;
12431 case Intrinsic::x86_sse42_pcmpistriz128:
12432 Opcode = X86ISD::PCMPISTRI;
12433 X86CC = X86::COND_E;
12435 case Intrinsic::x86_sse42_pcmpestriz128:
12436 Opcode = X86ISD::PCMPESTRI;
12437 X86CC = X86::COND_E;
12440 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12441 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12442 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12443 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12444 DAG.getConstant(X86CC, MVT::i8),
12445 SDValue(PCMP.getNode(), 1));
12446 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12449 case Intrinsic::x86_sse42_pcmpistri128:
12450 case Intrinsic::x86_sse42_pcmpestri128: {
12452 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12453 Opcode = X86ISD::PCMPISTRI;
12455 Opcode = X86ISD::PCMPESTRI;
12457 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12458 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12459 return DAG.getNode(Opcode, dl, VTs, NewOps);
12461 case Intrinsic::x86_fma_vfmadd_ps:
12462 case Intrinsic::x86_fma_vfmadd_pd:
12463 case Intrinsic::x86_fma_vfmsub_ps:
12464 case Intrinsic::x86_fma_vfmsub_pd:
12465 case Intrinsic::x86_fma_vfnmadd_ps:
12466 case Intrinsic::x86_fma_vfnmadd_pd:
12467 case Intrinsic::x86_fma_vfnmsub_ps:
12468 case Intrinsic::x86_fma_vfnmsub_pd:
12469 case Intrinsic::x86_fma_vfmaddsub_ps:
12470 case Intrinsic::x86_fma_vfmaddsub_pd:
12471 case Intrinsic::x86_fma_vfmsubadd_ps:
12472 case Intrinsic::x86_fma_vfmsubadd_pd:
12473 case Intrinsic::x86_fma_vfmadd_ps_256:
12474 case Intrinsic::x86_fma_vfmadd_pd_256:
12475 case Intrinsic::x86_fma_vfmsub_ps_256:
12476 case Intrinsic::x86_fma_vfmsub_pd_256:
12477 case Intrinsic::x86_fma_vfnmadd_ps_256:
12478 case Intrinsic::x86_fma_vfnmadd_pd_256:
12479 case Intrinsic::x86_fma_vfnmsub_ps_256:
12480 case Intrinsic::x86_fma_vfnmsub_pd_256:
12481 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12482 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12483 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12484 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12485 case Intrinsic::x86_fma_vfmadd_ps_512:
12486 case Intrinsic::x86_fma_vfmadd_pd_512:
12487 case Intrinsic::x86_fma_vfmsub_ps_512:
12488 case Intrinsic::x86_fma_vfmsub_pd_512:
12489 case Intrinsic::x86_fma_vfnmadd_ps_512:
12490 case Intrinsic::x86_fma_vfnmadd_pd_512:
12491 case Intrinsic::x86_fma_vfnmsub_ps_512:
12492 case Intrinsic::x86_fma_vfnmsub_pd_512:
12493 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12494 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12495 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12496 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12499 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12500 case Intrinsic::x86_fma_vfmadd_ps:
12501 case Intrinsic::x86_fma_vfmadd_pd:
12502 case Intrinsic::x86_fma_vfmadd_ps_256:
12503 case Intrinsic::x86_fma_vfmadd_pd_256:
12504 case Intrinsic::x86_fma_vfmadd_ps_512:
12505 case Intrinsic::x86_fma_vfmadd_pd_512:
12506 Opc = X86ISD::FMADD;
12508 case Intrinsic::x86_fma_vfmsub_ps:
12509 case Intrinsic::x86_fma_vfmsub_pd:
12510 case Intrinsic::x86_fma_vfmsub_ps_256:
12511 case Intrinsic::x86_fma_vfmsub_pd_256:
12512 case Intrinsic::x86_fma_vfmsub_ps_512:
12513 case Intrinsic::x86_fma_vfmsub_pd_512:
12514 Opc = X86ISD::FMSUB;
12516 case Intrinsic::x86_fma_vfnmadd_ps:
12517 case Intrinsic::x86_fma_vfnmadd_pd:
12518 case Intrinsic::x86_fma_vfnmadd_ps_256:
12519 case Intrinsic::x86_fma_vfnmadd_pd_256:
12520 case Intrinsic::x86_fma_vfnmadd_ps_512:
12521 case Intrinsic::x86_fma_vfnmadd_pd_512:
12522 Opc = X86ISD::FNMADD;
12524 case Intrinsic::x86_fma_vfnmsub_ps:
12525 case Intrinsic::x86_fma_vfnmsub_pd:
12526 case Intrinsic::x86_fma_vfnmsub_ps_256:
12527 case Intrinsic::x86_fma_vfnmsub_pd_256:
12528 case Intrinsic::x86_fma_vfnmsub_ps_512:
12529 case Intrinsic::x86_fma_vfnmsub_pd_512:
12530 Opc = X86ISD::FNMSUB;
12532 case Intrinsic::x86_fma_vfmaddsub_ps:
12533 case Intrinsic::x86_fma_vfmaddsub_pd:
12534 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12535 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12536 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12537 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12538 Opc = X86ISD::FMADDSUB;
12540 case Intrinsic::x86_fma_vfmsubadd_ps:
12541 case Intrinsic::x86_fma_vfmsubadd_pd:
12542 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12543 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12544 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12545 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12546 Opc = X86ISD::FMSUBADD;
12550 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12551 Op.getOperand(2), Op.getOperand(3));
12556 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12557 SDValue Src, SDValue Mask, SDValue Base,
12558 SDValue Index, SDValue ScaleOp, SDValue Chain,
12559 const X86Subtarget * Subtarget) {
12561 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12562 assert(C && "Invalid scale type");
12563 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12564 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12565 Index.getSimpleValueType().getVectorNumElements());
12567 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12569 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12571 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12572 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12573 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12574 SDValue Segment = DAG.getRegister(0, MVT::i32);
12575 if (Src.getOpcode() == ISD::UNDEF)
12576 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12577 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12578 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12579 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12580 return DAG.getMergeValues(RetOps, dl);
12583 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12584 SDValue Src, SDValue Mask, SDValue Base,
12585 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12587 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12588 assert(C && "Invalid scale type");
12589 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12590 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12591 SDValue Segment = DAG.getRegister(0, MVT::i32);
12592 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12593 Index.getSimpleValueType().getVectorNumElements());
12595 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12597 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12599 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12600 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12601 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12602 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12603 return SDValue(Res, 1);
12606 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12607 SDValue Mask, SDValue Base, SDValue Index,
12608 SDValue ScaleOp, SDValue Chain) {
12610 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12611 assert(C && "Invalid scale type");
12612 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12613 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12614 SDValue Segment = DAG.getRegister(0, MVT::i32);
12616 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12618 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12620 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12622 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12623 //SDVTList VTs = DAG.getVTList(MVT::Other);
12624 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12625 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12626 return SDValue(Res, 0);
12629 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12630 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12631 // also used to custom lower READCYCLECOUNTER nodes.
12632 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12633 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12634 SmallVectorImpl<SDValue> &Results) {
12635 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12636 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12639 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12640 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12641 // and the EAX register is loaded with the low-order 32 bits.
12642 if (Subtarget->is64Bit()) {
12643 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12644 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12647 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12648 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12651 SDValue Chain = HI.getValue(1);
12653 if (Opcode == X86ISD::RDTSCP_DAG) {
12654 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12656 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12657 // the ECX register. Add 'ecx' explicitly to the chain.
12658 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12660 // Explicitly store the content of ECX at the location passed in input
12661 // to the 'rdtscp' intrinsic.
12662 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12663 MachinePointerInfo(), false, false, 0);
12666 if (Subtarget->is64Bit()) {
12667 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12668 // the EAX register is loaded with the low-order 32 bits.
12669 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12670 DAG.getConstant(32, MVT::i8));
12671 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12672 Results.push_back(Chain);
12676 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12677 SDValue Ops[] = { LO, HI };
12678 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12679 Results.push_back(Pair);
12680 Results.push_back(Chain);
12683 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12684 SelectionDAG &DAG) {
12685 SmallVector<SDValue, 2> Results;
12687 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12689 return DAG.getMergeValues(Results, DL);
12692 enum IntrinsicType {
12693 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12696 struct IntrinsicData {
12697 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12698 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12699 IntrinsicType Type;
12704 std::map < unsigned, IntrinsicData> IntrMap;
12705 static void InitIntinsicsMap() {
12706 static bool Initialized = false;
12709 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12710 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12711 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12712 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12713 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12714 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12715 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12716 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12717 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12718 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12719 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
12720 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12721 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
12722 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12723 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
12724 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12725 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
12726 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12728 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12729 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12730 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
12731 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12732 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
12733 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12734 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
12735 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12736 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
12737 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12738 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
12739 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12740 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
12741 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12742 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
12743 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12745 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
12746 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12747 X86::VGATHERPF1QPSm)));
12748 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
12749 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12750 X86::VGATHERPF1QPDm)));
12751 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
12752 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12753 X86::VGATHERPF1DPDm)));
12754 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
12755 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12756 X86::VGATHERPF1DPSm)));
12757 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
12758 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12759 X86::VSCATTERPF1QPSm)));
12760 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
12761 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12762 X86::VSCATTERPF1QPDm)));
12763 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
12764 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12765 X86::VSCATTERPF1DPDm)));
12766 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
12767 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12768 X86::VSCATTERPF1DPSm)));
12769 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12770 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12771 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12772 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12773 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12774 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12775 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12776 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12777 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12778 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12779 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12780 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12781 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12782 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
12783 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12784 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
12785 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12786 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
12787 Initialized = true;
12790 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12791 SelectionDAG &DAG) {
12792 InitIntinsicsMap();
12793 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12794 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12795 if (itr == IntrMap.end())
12799 IntrinsicData Intr = itr->second;
12800 switch(Intr.Type) {
12803 // Emit the node with the right value type.
12804 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12805 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12807 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12808 // Otherwise return the value from Rand, which is always 0, casted to i32.
12809 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12810 DAG.getConstant(1, Op->getValueType(1)),
12811 DAG.getConstant(X86::COND_B, MVT::i32),
12812 SDValue(Result.getNode(), 1) };
12813 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12814 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12817 // Return { result, isValid, chain }.
12818 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12819 SDValue(Result.getNode(), 2));
12822 //gather(v1, mask, index, base, scale);
12823 SDValue Chain = Op.getOperand(0);
12824 SDValue Src = Op.getOperand(2);
12825 SDValue Base = Op.getOperand(3);
12826 SDValue Index = Op.getOperand(4);
12827 SDValue Mask = Op.getOperand(5);
12828 SDValue Scale = Op.getOperand(6);
12829 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12833 //scatter(base, mask, index, v1, scale);
12834 SDValue Chain = Op.getOperand(0);
12835 SDValue Base = Op.getOperand(2);
12836 SDValue Mask = Op.getOperand(3);
12837 SDValue Index = Op.getOperand(4);
12838 SDValue Src = Op.getOperand(5);
12839 SDValue Scale = Op.getOperand(6);
12840 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12843 SDValue Hint = Op.getOperand(6);
12845 if (dyn_cast<ConstantSDNode> (Hint) == 0 ||
12846 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12847 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12848 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12849 SDValue Chain = Op.getOperand(0);
12850 SDValue Mask = Op.getOperand(2);
12851 SDValue Index = Op.getOperand(3);
12852 SDValue Base = Op.getOperand(4);
12853 SDValue Scale = Op.getOperand(5);
12854 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12856 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12858 SmallVector<SDValue, 2> Results;
12859 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12860 return DAG.getMergeValues(Results, dl);
12862 // XTEST intrinsics.
12864 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12865 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12866 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12867 DAG.getConstant(X86::COND_NE, MVT::i8),
12869 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12870 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12871 Ret, SDValue(InTrans.getNode(), 1));
12874 llvm_unreachable("Unknown Intrinsic Type");
12877 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12878 SelectionDAG &DAG) const {
12879 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12880 MFI->setReturnAddressIsTaken(true);
12882 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12885 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12887 EVT PtrVT = getPointerTy();
12890 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12891 const X86RegisterInfo *RegInfo =
12892 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12893 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12894 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12895 DAG.getNode(ISD::ADD, dl, PtrVT,
12896 FrameAddr, Offset),
12897 MachinePointerInfo(), false, false, false, 0);
12900 // Just load the return address.
12901 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12902 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12903 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12906 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12907 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12908 MFI->setFrameAddressIsTaken(true);
12910 EVT VT = Op.getValueType();
12911 SDLoc dl(Op); // FIXME probably not meaningful
12912 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12913 const X86RegisterInfo *RegInfo =
12914 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12915 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12916 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12917 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12918 "Invalid Frame Register!");
12919 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12921 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12922 MachinePointerInfo(),
12923 false, false, false, 0);
12927 // FIXME? Maybe this could be a TableGen attribute on some registers and
12928 // this table could be generated automatically from RegInfo.
12929 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12931 unsigned Reg = StringSwitch<unsigned>(RegName)
12932 .Case("esp", X86::ESP)
12933 .Case("rsp", X86::RSP)
12937 report_fatal_error("Invalid register name global variable");
12940 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12941 SelectionDAG &DAG) const {
12942 const X86RegisterInfo *RegInfo =
12943 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12944 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12947 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12948 SDValue Chain = Op.getOperand(0);
12949 SDValue Offset = Op.getOperand(1);
12950 SDValue Handler = Op.getOperand(2);
12953 EVT PtrVT = getPointerTy();
12954 const X86RegisterInfo *RegInfo =
12955 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12956 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12957 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12958 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12959 "Invalid Frame Register!");
12960 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12961 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12963 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12964 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12965 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12966 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12968 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12970 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12971 DAG.getRegister(StoreAddrReg, PtrVT));
12974 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12975 SelectionDAG &DAG) const {
12977 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12978 DAG.getVTList(MVT::i32, MVT::Other),
12979 Op.getOperand(0), Op.getOperand(1));
12982 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12983 SelectionDAG &DAG) const {
12985 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12986 Op.getOperand(0), Op.getOperand(1));
12989 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12990 return Op.getOperand(0);
12993 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12994 SelectionDAG &DAG) const {
12995 SDValue Root = Op.getOperand(0);
12996 SDValue Trmp = Op.getOperand(1); // trampoline
12997 SDValue FPtr = Op.getOperand(2); // nested function
12998 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13001 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13002 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13004 if (Subtarget->is64Bit()) {
13005 SDValue OutChains[6];
13007 // Large code-model.
13008 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
13009 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13011 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13012 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13014 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13016 // Load the pointer to the nested function into R11.
13017 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13018 SDValue Addr = Trmp;
13019 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13020 Addr, MachinePointerInfo(TrmpAddr),
13023 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13024 DAG.getConstant(2, MVT::i64));
13025 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13026 MachinePointerInfo(TrmpAddr, 2),
13029 // Load the 'nest' parameter value into R10.
13030 // R10 is specified in X86CallingConv.td
13031 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13032 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13033 DAG.getConstant(10, MVT::i64));
13034 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13035 Addr, MachinePointerInfo(TrmpAddr, 10),
13038 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13039 DAG.getConstant(12, MVT::i64));
13040 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13041 MachinePointerInfo(TrmpAddr, 12),
13044 // Jump to the nested function.
13045 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13046 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13047 DAG.getConstant(20, MVT::i64));
13048 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13049 Addr, MachinePointerInfo(TrmpAddr, 20),
13052 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13053 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13054 DAG.getConstant(22, MVT::i64));
13055 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13056 MachinePointerInfo(TrmpAddr, 22),
13059 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13061 const Function *Func =
13062 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13063 CallingConv::ID CC = Func->getCallingConv();
13068 llvm_unreachable("Unsupported calling convention");
13069 case CallingConv::C:
13070 case CallingConv::X86_StdCall: {
13071 // Pass 'nest' parameter in ECX.
13072 // Must be kept in sync with X86CallingConv.td
13073 NestReg = X86::ECX;
13075 // Check that ECX wasn't needed by an 'inreg' parameter.
13076 FunctionType *FTy = Func->getFunctionType();
13077 const AttributeSet &Attrs = Func->getAttributes();
13079 if (!Attrs.isEmpty() && !Func->isVarArg()) {
13080 unsigned InRegCount = 0;
13083 for (FunctionType::param_iterator I = FTy->param_begin(),
13084 E = FTy->param_end(); I != E; ++I, ++Idx)
13085 if (Attrs.hasAttribute(Idx, Attribute::InReg))
13086 // FIXME: should only count parameters that are lowered to integers.
13087 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13089 if (InRegCount > 2) {
13090 report_fatal_error("Nest register in use - reduce number of inreg"
13096 case CallingConv::X86_FastCall:
13097 case CallingConv::X86_ThisCall:
13098 case CallingConv::Fast:
13099 // Pass 'nest' parameter in EAX.
13100 // Must be kept in sync with X86CallingConv.td
13101 NestReg = X86::EAX;
13105 SDValue OutChains[4];
13106 SDValue Addr, Disp;
13108 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13109 DAG.getConstant(10, MVT::i32));
13110 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13112 // This is storing the opcode for MOV32ri.
13113 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13114 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13115 OutChains[0] = DAG.getStore(Root, dl,
13116 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13117 Trmp, MachinePointerInfo(TrmpAddr),
13120 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13121 DAG.getConstant(1, MVT::i32));
13122 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13123 MachinePointerInfo(TrmpAddr, 1),
13126 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13127 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13128 DAG.getConstant(5, MVT::i32));
13129 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13130 MachinePointerInfo(TrmpAddr, 5),
13133 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13134 DAG.getConstant(6, MVT::i32));
13135 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13136 MachinePointerInfo(TrmpAddr, 6),
13139 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13143 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13144 SelectionDAG &DAG) const {
13146 The rounding mode is in bits 11:10 of FPSR, and has the following
13148 00 Round to nearest
13153 FLT_ROUNDS, on the other hand, expects the following:
13160 To perform the conversion, we do:
13161 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13164 MachineFunction &MF = DAG.getMachineFunction();
13165 const TargetMachine &TM = MF.getTarget();
13166 const TargetFrameLowering &TFI = *TM.getFrameLowering();
13167 unsigned StackAlignment = TFI.getStackAlignment();
13168 MVT VT = Op.getSimpleValueType();
13171 // Save FP Control Word to stack slot
13172 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13173 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13175 MachineMemOperand *MMO =
13176 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13177 MachineMemOperand::MOStore, 2, 2);
13179 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13180 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13181 DAG.getVTList(MVT::Other),
13182 Ops, MVT::i16, MMO);
13184 // Load FP Control Word from stack slot
13185 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13186 MachinePointerInfo(), false, false, false, 0);
13188 // Transform as necessary
13190 DAG.getNode(ISD::SRL, DL, MVT::i16,
13191 DAG.getNode(ISD::AND, DL, MVT::i16,
13192 CWD, DAG.getConstant(0x800, MVT::i16)),
13193 DAG.getConstant(11, MVT::i8));
13195 DAG.getNode(ISD::SRL, DL, MVT::i16,
13196 DAG.getNode(ISD::AND, DL, MVT::i16,
13197 CWD, DAG.getConstant(0x400, MVT::i16)),
13198 DAG.getConstant(9, MVT::i8));
13201 DAG.getNode(ISD::AND, DL, MVT::i16,
13202 DAG.getNode(ISD::ADD, DL, MVT::i16,
13203 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13204 DAG.getConstant(1, MVT::i16)),
13205 DAG.getConstant(3, MVT::i16));
13207 return DAG.getNode((VT.getSizeInBits() < 16 ?
13208 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13211 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13212 MVT VT = Op.getSimpleValueType();
13214 unsigned NumBits = VT.getSizeInBits();
13217 Op = Op.getOperand(0);
13218 if (VT == MVT::i8) {
13219 // Zero extend to i32 since there is not an i8 bsr.
13221 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13224 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13225 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13226 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13228 // If src is zero (i.e. bsr sets ZF), returns NumBits.
13231 DAG.getConstant(NumBits+NumBits-1, OpVT),
13232 DAG.getConstant(X86::COND_E, MVT::i8),
13235 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13237 // Finally xor with NumBits-1.
13238 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13241 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13245 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13246 MVT VT = Op.getSimpleValueType();
13248 unsigned NumBits = VT.getSizeInBits();
13251 Op = Op.getOperand(0);
13252 if (VT == MVT::i8) {
13253 // Zero extend to i32 since there is not an i8 bsr.
13255 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13258 // Issue a bsr (scan bits in reverse).
13259 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13260 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13262 // And xor with NumBits-1.
13263 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13266 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13270 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13271 MVT VT = Op.getSimpleValueType();
13272 unsigned NumBits = VT.getSizeInBits();
13274 Op = Op.getOperand(0);
13276 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13277 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13278 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13280 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13283 DAG.getConstant(NumBits, VT),
13284 DAG.getConstant(X86::COND_E, MVT::i8),
13287 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13290 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13291 // ones, and then concatenate the result back.
13292 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13293 MVT VT = Op.getSimpleValueType();
13295 assert(VT.is256BitVector() && VT.isInteger() &&
13296 "Unsupported value type for operation");
13298 unsigned NumElems = VT.getVectorNumElements();
13301 // Extract the LHS vectors
13302 SDValue LHS = Op.getOperand(0);
13303 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13304 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13306 // Extract the RHS vectors
13307 SDValue RHS = Op.getOperand(1);
13308 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13309 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13311 MVT EltVT = VT.getVectorElementType();
13312 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13314 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13315 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13316 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13319 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13320 assert(Op.getSimpleValueType().is256BitVector() &&
13321 Op.getSimpleValueType().isInteger() &&
13322 "Only handle AVX 256-bit vector integer operation");
13323 return Lower256IntArith(Op, DAG);
13326 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13327 assert(Op.getSimpleValueType().is256BitVector() &&
13328 Op.getSimpleValueType().isInteger() &&
13329 "Only handle AVX 256-bit vector integer operation");
13330 return Lower256IntArith(Op, DAG);
13333 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13334 SelectionDAG &DAG) {
13336 MVT VT = Op.getSimpleValueType();
13338 // Decompose 256-bit ops into smaller 128-bit ops.
13339 if (VT.is256BitVector() && !Subtarget->hasInt256())
13340 return Lower256IntArith(Op, DAG);
13342 SDValue A = Op.getOperand(0);
13343 SDValue B = Op.getOperand(1);
13345 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13346 if (VT == MVT::v4i32) {
13347 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13348 "Should not custom lower when pmuldq is available!");
13350 // Extract the odd parts.
13351 static const int UnpackMask[] = { 1, -1, 3, -1 };
13352 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13353 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13355 // Multiply the even parts.
13356 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13357 // Now multiply odd parts.
13358 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13360 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13361 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13363 // Merge the two vectors back together with a shuffle. This expands into 2
13365 static const int ShufMask[] = { 0, 4, 2, 6 };
13366 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13369 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13370 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13372 // Ahi = psrlqi(a, 32);
13373 // Bhi = psrlqi(b, 32);
13375 // AloBlo = pmuludq(a, b);
13376 // AloBhi = pmuludq(a, Bhi);
13377 // AhiBlo = pmuludq(Ahi, b);
13379 // AloBhi = psllqi(AloBhi, 32);
13380 // AhiBlo = psllqi(AhiBlo, 32);
13381 // return AloBlo + AloBhi + AhiBlo;
13383 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13384 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13386 // Bit cast to 32-bit vectors for MULUDQ
13387 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13388 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13389 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13390 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13391 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13392 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13394 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13395 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13396 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13398 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13399 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13401 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13402 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13405 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13406 assert(Subtarget->isTargetWin64() && "Unexpected target");
13407 EVT VT = Op.getValueType();
13408 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13409 "Unexpected return type for lowering");
13413 switch (Op->getOpcode()) {
13414 default: llvm_unreachable("Unexpected request for libcall!");
13415 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
13416 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
13417 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
13418 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
13419 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
13420 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13424 SDValue InChain = DAG.getEntryNode();
13426 TargetLowering::ArgListTy Args;
13427 TargetLowering::ArgListEntry Entry;
13428 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13429 EVT ArgVT = Op->getOperand(i).getValueType();
13430 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13431 "Unexpected argument type for lowering");
13432 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13433 Entry.Node = StackPtr;
13434 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13436 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13437 Entry.Ty = PointerType::get(ArgTy,0);
13438 Entry.isSExt = false;
13439 Entry.isZExt = false;
13440 Args.push_back(Entry);
13443 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13446 TargetLowering::CallLoweringInfo CLI(DAG);
13447 CLI.setDebugLoc(dl).setChain(InChain)
13448 .setCallee(getLibcallCallingConv(LC),
13449 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13451 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13453 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13454 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13457 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13458 SelectionDAG &DAG) {
13459 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13460 EVT VT = Op0.getValueType();
13463 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13464 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13466 // Get the high parts.
13467 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13468 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13469 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13471 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13473 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13474 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13476 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13477 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13478 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13479 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13480 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13482 // Shuffle it back into the right order.
13483 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13484 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13485 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13486 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13488 // If we have a signed multiply but no PMULDQ fix up the high parts of a
13489 // unsigned multiply.
13490 if (IsSigned && !Subtarget->hasSSE41()) {
13492 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13493 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13494 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13495 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13496 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13498 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13499 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13502 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13505 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13506 const X86Subtarget *Subtarget) {
13507 MVT VT = Op.getSimpleValueType();
13509 SDValue R = Op.getOperand(0);
13510 SDValue Amt = Op.getOperand(1);
13512 // Optimize shl/srl/sra with constant shift amount.
13513 if (isSplatVector(Amt.getNode())) {
13514 SDValue SclrAmt = Amt->getOperand(0);
13515 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13516 uint64_t ShiftAmt = C->getZExtValue();
13518 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13519 (Subtarget->hasInt256() &&
13520 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13521 (Subtarget->hasAVX512() &&
13522 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13523 if (Op.getOpcode() == ISD::SHL)
13524 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13526 if (Op.getOpcode() == ISD::SRL)
13527 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13529 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13530 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13534 if (VT == MVT::v16i8) {
13535 if (Op.getOpcode() == ISD::SHL) {
13536 // Make a large shift.
13537 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13538 MVT::v8i16, R, ShiftAmt,
13540 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13541 // Zero out the rightmost bits.
13542 SmallVector<SDValue, 16> V(16,
13543 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13545 return DAG.getNode(ISD::AND, dl, VT, SHL,
13546 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13548 if (Op.getOpcode() == ISD::SRL) {
13549 // Make a large shift.
13550 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13551 MVT::v8i16, R, ShiftAmt,
13553 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13554 // Zero out the leftmost bits.
13555 SmallVector<SDValue, 16> V(16,
13556 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13558 return DAG.getNode(ISD::AND, dl, VT, SRL,
13559 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13561 if (Op.getOpcode() == ISD::SRA) {
13562 if (ShiftAmt == 7) {
13563 // R s>> 7 === R s< 0
13564 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13565 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13568 // R s>> a === ((R u>> a) ^ m) - m
13569 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13570 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13572 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13573 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13574 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13577 llvm_unreachable("Unknown shift opcode.");
13580 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13581 if (Op.getOpcode() == ISD::SHL) {
13582 // Make a large shift.
13583 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13584 MVT::v16i16, R, ShiftAmt,
13586 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13587 // Zero out the rightmost bits.
13588 SmallVector<SDValue, 32> V(32,
13589 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13591 return DAG.getNode(ISD::AND, dl, VT, SHL,
13592 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13594 if (Op.getOpcode() == ISD::SRL) {
13595 // Make a large shift.
13596 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13597 MVT::v16i16, R, ShiftAmt,
13599 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13600 // Zero out the leftmost bits.
13601 SmallVector<SDValue, 32> V(32,
13602 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13604 return DAG.getNode(ISD::AND, dl, VT, SRL,
13605 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13607 if (Op.getOpcode() == ISD::SRA) {
13608 if (ShiftAmt == 7) {
13609 // R s>> 7 === R s< 0
13610 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13611 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13614 // R s>> a === ((R u>> a) ^ m) - m
13615 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13616 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13618 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13619 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13620 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13623 llvm_unreachable("Unknown shift opcode.");
13628 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13629 if (!Subtarget->is64Bit() &&
13630 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13631 Amt.getOpcode() == ISD::BITCAST &&
13632 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13633 Amt = Amt.getOperand(0);
13634 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13635 VT.getVectorNumElements();
13636 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13637 uint64_t ShiftAmt = 0;
13638 for (unsigned i = 0; i != Ratio; ++i) {
13639 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13643 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13645 // Check remaining shift amounts.
13646 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13647 uint64_t ShAmt = 0;
13648 for (unsigned j = 0; j != Ratio; ++j) {
13649 ConstantSDNode *C =
13650 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13654 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13656 if (ShAmt != ShiftAmt)
13659 switch (Op.getOpcode()) {
13661 llvm_unreachable("Unknown shift opcode!");
13663 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13666 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13669 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13677 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13678 const X86Subtarget* Subtarget) {
13679 MVT VT = Op.getSimpleValueType();
13681 SDValue R = Op.getOperand(0);
13682 SDValue Amt = Op.getOperand(1);
13684 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13685 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13686 (Subtarget->hasInt256() &&
13687 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13688 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13689 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13691 EVT EltVT = VT.getVectorElementType();
13693 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13694 unsigned NumElts = VT.getVectorNumElements();
13696 for (i = 0; i != NumElts; ++i) {
13697 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13701 for (j = i; j != NumElts; ++j) {
13702 SDValue Arg = Amt.getOperand(j);
13703 if (Arg.getOpcode() == ISD::UNDEF) continue;
13704 if (Arg != Amt.getOperand(i))
13707 if (i != NumElts && j == NumElts)
13708 BaseShAmt = Amt.getOperand(i);
13710 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13711 Amt = Amt.getOperand(0);
13712 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13713 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13714 SDValue InVec = Amt.getOperand(0);
13715 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13716 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13718 for (; i != NumElts; ++i) {
13719 SDValue Arg = InVec.getOperand(i);
13720 if (Arg.getOpcode() == ISD::UNDEF) continue;
13724 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13725 if (ConstantSDNode *C =
13726 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13727 unsigned SplatIdx =
13728 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13729 if (C->getZExtValue() == SplatIdx)
13730 BaseShAmt = InVec.getOperand(1);
13733 if (!BaseShAmt.getNode())
13734 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13735 DAG.getIntPtrConstant(0));
13739 if (BaseShAmt.getNode()) {
13740 if (EltVT.bitsGT(MVT::i32))
13741 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13742 else if (EltVT.bitsLT(MVT::i32))
13743 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13745 switch (Op.getOpcode()) {
13747 llvm_unreachable("Unknown shift opcode!");
13749 switch (VT.SimpleTy) {
13750 default: return SDValue();
13759 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13762 switch (VT.SimpleTy) {
13763 default: return SDValue();
13770 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13773 switch (VT.SimpleTy) {
13774 default: return SDValue();
13783 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13789 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13790 if (!Subtarget->is64Bit() &&
13791 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13792 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13793 Amt.getOpcode() == ISD::BITCAST &&
13794 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13795 Amt = Amt.getOperand(0);
13796 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13797 VT.getVectorNumElements();
13798 std::vector<SDValue> Vals(Ratio);
13799 for (unsigned i = 0; i != Ratio; ++i)
13800 Vals[i] = Amt.getOperand(i);
13801 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13802 for (unsigned j = 0; j != Ratio; ++j)
13803 if (Vals[j] != Amt.getOperand(i + j))
13806 switch (Op.getOpcode()) {
13808 llvm_unreachable("Unknown shift opcode!");
13810 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13812 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13814 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13821 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13822 SelectionDAG &DAG) {
13824 MVT VT = Op.getSimpleValueType();
13826 SDValue R = Op.getOperand(0);
13827 SDValue Amt = Op.getOperand(1);
13830 if (!Subtarget->hasSSE2())
13833 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13837 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13841 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13843 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13844 if (Subtarget->hasInt256()) {
13845 if (Op.getOpcode() == ISD::SRL &&
13846 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13847 VT == MVT::v4i64 || VT == MVT::v8i32))
13849 if (Op.getOpcode() == ISD::SHL &&
13850 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13851 VT == MVT::v4i64 || VT == MVT::v8i32))
13853 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13857 // If possible, lower this packed shift into a vector multiply instead of
13858 // expanding it into a sequence of scalar shifts.
13859 // Do this only if the vector shift count is a constant build_vector.
13860 if (Op.getOpcode() == ISD::SHL &&
13861 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13862 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13863 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13864 SmallVector<SDValue, 8> Elts;
13865 EVT SVT = VT.getScalarType();
13866 unsigned SVTBits = SVT.getSizeInBits();
13867 const APInt &One = APInt(SVTBits, 1);
13868 unsigned NumElems = VT.getVectorNumElements();
13870 for (unsigned i=0; i !=NumElems; ++i) {
13871 SDValue Op = Amt->getOperand(i);
13872 if (Op->getOpcode() == ISD::UNDEF) {
13873 Elts.push_back(Op);
13877 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13878 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13879 uint64_t ShAmt = C.getZExtValue();
13880 if (ShAmt >= SVTBits) {
13881 Elts.push_back(DAG.getUNDEF(SVT));
13884 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13886 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13887 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13890 // Lower SHL with variable shift amount.
13891 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13892 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13894 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13895 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13896 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13897 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13900 // If possible, lower this shift as a sequence of two shifts by
13901 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13903 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13905 // Could be rewritten as:
13906 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13908 // The advantage is that the two shifts from the example would be
13909 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13910 // the vector shift into four scalar shifts plus four pairs of vector
13912 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13913 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13914 unsigned TargetOpcode = X86ISD::MOVSS;
13915 bool CanBeSimplified;
13916 // The splat value for the first packed shift (the 'X' from the example).
13917 SDValue Amt1 = Amt->getOperand(0);
13918 // The splat value for the second packed shift (the 'Y' from the example).
13919 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13920 Amt->getOperand(2);
13922 // See if it is possible to replace this node with a sequence of
13923 // two shifts followed by a MOVSS/MOVSD
13924 if (VT == MVT::v4i32) {
13925 // Check if it is legal to use a MOVSS.
13926 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13927 Amt2 == Amt->getOperand(3);
13928 if (!CanBeSimplified) {
13929 // Otherwise, check if we can still simplify this node using a MOVSD.
13930 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13931 Amt->getOperand(2) == Amt->getOperand(3);
13932 TargetOpcode = X86ISD::MOVSD;
13933 Amt2 = Amt->getOperand(2);
13936 // Do similar checks for the case where the machine value type
13938 CanBeSimplified = Amt1 == Amt->getOperand(1);
13939 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13940 CanBeSimplified = Amt2 == Amt->getOperand(i);
13942 if (!CanBeSimplified) {
13943 TargetOpcode = X86ISD::MOVSD;
13944 CanBeSimplified = true;
13945 Amt2 = Amt->getOperand(4);
13946 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13947 CanBeSimplified = Amt1 == Amt->getOperand(i);
13948 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13949 CanBeSimplified = Amt2 == Amt->getOperand(j);
13953 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13954 isa<ConstantSDNode>(Amt2)) {
13955 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13956 EVT CastVT = MVT::v4i32;
13958 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13959 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13961 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13962 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13963 if (TargetOpcode == X86ISD::MOVSD)
13964 CastVT = MVT::v2i64;
13965 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13966 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13967 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13969 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13973 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13974 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13977 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13978 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13980 // Turn 'a' into a mask suitable for VSELECT
13981 SDValue VSelM = DAG.getConstant(0x80, VT);
13982 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13983 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13985 SDValue CM1 = DAG.getConstant(0x0f, VT);
13986 SDValue CM2 = DAG.getConstant(0x3f, VT);
13988 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13989 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13990 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13991 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13992 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13995 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13996 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13997 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13999 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14000 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14001 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14002 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14003 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14006 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14007 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14008 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14010 // return VSELECT(r, r+r, a);
14011 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14012 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14016 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14017 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14018 // solution better.
14019 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14020 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14022 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14023 R = DAG.getNode(ExtOpc, dl, NewVT, R);
14024 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14025 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14026 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14029 // Decompose 256-bit shifts into smaller 128-bit shifts.
14030 if (VT.is256BitVector()) {
14031 unsigned NumElems = VT.getVectorNumElements();
14032 MVT EltVT = VT.getVectorElementType();
14033 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14035 // Extract the two vectors
14036 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14037 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14039 // Recreate the shift amount vectors
14040 SDValue Amt1, Amt2;
14041 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14042 // Constant shift amount
14043 SmallVector<SDValue, 4> Amt1Csts;
14044 SmallVector<SDValue, 4> Amt2Csts;
14045 for (unsigned i = 0; i != NumElems/2; ++i)
14046 Amt1Csts.push_back(Amt->getOperand(i));
14047 for (unsigned i = NumElems/2; i != NumElems; ++i)
14048 Amt2Csts.push_back(Amt->getOperand(i));
14050 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14051 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14053 // Variable shift amount
14054 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14055 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14058 // Issue new vector shifts for the smaller types
14059 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14060 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14062 // Concatenate the result back
14063 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14069 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14070 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14071 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14072 // looks for this combo and may remove the "setcc" instruction if the "setcc"
14073 // has only one use.
14074 SDNode *N = Op.getNode();
14075 SDValue LHS = N->getOperand(0);
14076 SDValue RHS = N->getOperand(1);
14077 unsigned BaseOp = 0;
14080 switch (Op.getOpcode()) {
14081 default: llvm_unreachable("Unknown ovf instruction!");
14083 // A subtract of one will be selected as a INC. Note that INC doesn't
14084 // set CF, so we can't do this for UADDO.
14085 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14087 BaseOp = X86ISD::INC;
14088 Cond = X86::COND_O;
14091 BaseOp = X86ISD::ADD;
14092 Cond = X86::COND_O;
14095 BaseOp = X86ISD::ADD;
14096 Cond = X86::COND_B;
14099 // A subtract of one will be selected as a DEC. Note that DEC doesn't
14100 // set CF, so we can't do this for USUBO.
14101 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14103 BaseOp = X86ISD::DEC;
14104 Cond = X86::COND_O;
14107 BaseOp = X86ISD::SUB;
14108 Cond = X86::COND_O;
14111 BaseOp = X86ISD::SUB;
14112 Cond = X86::COND_B;
14115 BaseOp = X86ISD::SMUL;
14116 Cond = X86::COND_O;
14118 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14119 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14121 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14124 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14125 DAG.getConstant(X86::COND_O, MVT::i32),
14126 SDValue(Sum.getNode(), 2));
14128 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14132 // Also sets EFLAGS.
14133 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14134 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14137 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14138 DAG.getConstant(Cond, MVT::i32),
14139 SDValue(Sum.getNode(), 1));
14141 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14144 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14145 SelectionDAG &DAG) const {
14147 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14148 MVT VT = Op.getSimpleValueType();
14150 if (!Subtarget->hasSSE2() || !VT.isVector())
14153 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14154 ExtraVT.getScalarType().getSizeInBits();
14156 switch (VT.SimpleTy) {
14157 default: return SDValue();
14160 if (!Subtarget->hasFp256())
14162 if (!Subtarget->hasInt256()) {
14163 // needs to be split
14164 unsigned NumElems = VT.getVectorNumElements();
14166 // Extract the LHS vectors
14167 SDValue LHS = Op.getOperand(0);
14168 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14169 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14171 MVT EltVT = VT.getVectorElementType();
14172 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14174 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14175 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14176 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14178 SDValue Extra = DAG.getValueType(ExtraVT);
14180 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14181 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14183 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14188 SDValue Op0 = Op.getOperand(0);
14189 SDValue Op00 = Op0.getOperand(0);
14191 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14192 if (Op0.getOpcode() == ISD::BITCAST &&
14193 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14194 // (sext (vzext x)) -> (vsext x)
14195 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14196 if (Tmp1.getNode()) {
14197 EVT ExtraEltVT = ExtraVT.getVectorElementType();
14198 // This folding is only valid when the in-reg type is a vector of i8,
14200 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14201 ExtraEltVT == MVT::i32) {
14202 SDValue Tmp1Op0 = Tmp1.getOperand(0);
14203 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14204 "This optimization is invalid without a VZEXT.");
14205 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14211 // If the above didn't work, then just use Shift-Left + Shift-Right.
14212 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14214 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14220 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14221 SelectionDAG &DAG) {
14223 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14224 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14225 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14226 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14228 // The only fence that needs an instruction is a sequentially-consistent
14229 // cross-thread fence.
14230 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14231 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14232 // no-sse2). There isn't any reason to disable it if the target processor
14234 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14235 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14237 SDValue Chain = Op.getOperand(0);
14238 SDValue Zero = DAG.getConstant(0, MVT::i32);
14240 DAG.getRegister(X86::ESP, MVT::i32), // Base
14241 DAG.getTargetConstant(1, MVT::i8), // Scale
14242 DAG.getRegister(0, MVT::i32), // Index
14243 DAG.getTargetConstant(0, MVT::i32), // Disp
14244 DAG.getRegister(0, MVT::i32), // Segment.
14248 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14249 return SDValue(Res, 0);
14252 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14253 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14256 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14257 SelectionDAG &DAG) {
14258 MVT T = Op.getSimpleValueType();
14262 switch(T.SimpleTy) {
14263 default: llvm_unreachable("Invalid value type!");
14264 case MVT::i8: Reg = X86::AL; size = 1; break;
14265 case MVT::i16: Reg = X86::AX; size = 2; break;
14266 case MVT::i32: Reg = X86::EAX; size = 4; break;
14268 assert(Subtarget->is64Bit() && "Node not type legal!");
14269 Reg = X86::RAX; size = 8;
14272 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14273 Op.getOperand(2), SDValue());
14274 SDValue Ops[] = { cpIn.getValue(0),
14277 DAG.getTargetConstant(size, MVT::i8),
14278 cpIn.getValue(1) };
14279 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14280 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14281 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14284 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14288 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14289 SelectionDAG &DAG) {
14290 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14291 MVT DstVT = Op.getSimpleValueType();
14293 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14294 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14295 if (DstVT != MVT::f64)
14296 // This conversion needs to be expanded.
14299 SDValue InVec = Op->getOperand(0);
14301 unsigned NumElts = SrcVT.getVectorNumElements();
14302 EVT SVT = SrcVT.getVectorElementType();
14304 // Widen the vector in input in the case of MVT::v2i32.
14305 // Example: from MVT::v2i32 to MVT::v4i32.
14306 SmallVector<SDValue, 16> Elts;
14307 for (unsigned i = 0, e = NumElts; i != e; ++i)
14308 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14309 DAG.getIntPtrConstant(i)));
14311 // Explicitly mark the extra elements as Undef.
14312 SDValue Undef = DAG.getUNDEF(SVT);
14313 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14314 Elts.push_back(Undef);
14316 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14317 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14318 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14319 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14320 DAG.getIntPtrConstant(0));
14323 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14324 Subtarget->hasMMX() && "Unexpected custom BITCAST");
14325 assert((DstVT == MVT::i64 ||
14326 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14327 "Unexpected custom BITCAST");
14328 // i64 <=> MMX conversions are Legal.
14329 if (SrcVT==MVT::i64 && DstVT.isVector())
14331 if (DstVT==MVT::i64 && SrcVT.isVector())
14333 // MMX <=> MMX conversions are Legal.
14334 if (SrcVT.isVector() && DstVT.isVector())
14336 // All other conversions need to be expanded.
14340 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14341 SDNode *Node = Op.getNode();
14343 EVT T = Node->getValueType(0);
14344 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14345 DAG.getConstant(0, T), Node->getOperand(2));
14346 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14347 cast<AtomicSDNode>(Node)->getMemoryVT(),
14348 Node->getOperand(0),
14349 Node->getOperand(1), negOp,
14350 cast<AtomicSDNode>(Node)->getMemOperand(),
14351 cast<AtomicSDNode>(Node)->getOrdering(),
14352 cast<AtomicSDNode>(Node)->getSynchScope());
14355 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14356 SDNode *Node = Op.getNode();
14358 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14360 // Convert seq_cst store -> xchg
14361 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14362 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14363 // (The only way to get a 16-byte store is cmpxchg16b)
14364 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14365 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14366 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14367 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14368 cast<AtomicSDNode>(Node)->getMemoryVT(),
14369 Node->getOperand(0),
14370 Node->getOperand(1), Node->getOperand(2),
14371 cast<AtomicSDNode>(Node)->getMemOperand(),
14372 cast<AtomicSDNode>(Node)->getOrdering(),
14373 cast<AtomicSDNode>(Node)->getSynchScope());
14374 return Swap.getValue(1);
14376 // Other atomic stores have a simple pattern.
14380 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14381 EVT VT = Op.getNode()->getSimpleValueType(0);
14383 // Let legalize expand this if it isn't a legal type yet.
14384 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14387 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14390 bool ExtraOp = false;
14391 switch (Op.getOpcode()) {
14392 default: llvm_unreachable("Invalid code");
14393 case ISD::ADDC: Opc = X86ISD::ADD; break;
14394 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14395 case ISD::SUBC: Opc = X86ISD::SUB; break;
14396 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14400 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14402 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14403 Op.getOperand(1), Op.getOperand(2));
14406 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14407 SelectionDAG &DAG) {
14408 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14410 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14411 // which returns the values as { float, float } (in XMM0) or
14412 // { double, double } (which is returned in XMM0, XMM1).
14414 SDValue Arg = Op.getOperand(0);
14415 EVT ArgVT = Arg.getValueType();
14416 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14418 TargetLowering::ArgListTy Args;
14419 TargetLowering::ArgListEntry Entry;
14423 Entry.isSExt = false;
14424 Entry.isZExt = false;
14425 Args.push_back(Entry);
14427 bool isF64 = ArgVT == MVT::f64;
14428 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14429 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14430 // the results are returned via SRet in memory.
14431 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14433 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14435 Type *RetTy = isF64
14436 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14437 : (Type*)VectorType::get(ArgTy, 4);
14439 TargetLowering::CallLoweringInfo CLI(DAG);
14440 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14441 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14443 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14446 // Returned in xmm0 and xmm1.
14447 return CallResult.first;
14449 // Returned in bits 0:31 and 32:64 xmm0.
14450 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14451 CallResult.first, DAG.getIntPtrConstant(0));
14452 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14453 CallResult.first, DAG.getIntPtrConstant(1));
14454 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14455 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14458 /// LowerOperation - Provide custom lowering hooks for some operations.
14460 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14461 switch (Op.getOpcode()) {
14462 default: llvm_unreachable("Should not custom lower this!");
14463 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14464 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14465 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14466 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14467 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14468 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14469 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14470 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14471 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
14472 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14473 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14474 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14475 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14476 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14477 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14478 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14479 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14480 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14481 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14482 case ISD::SHL_PARTS:
14483 case ISD::SRA_PARTS:
14484 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14485 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14486 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14487 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14488 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14489 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14490 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14491 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14492 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14493 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14494 case ISD::FABS: return LowerFABS(Op, DAG);
14495 case ISD::FNEG: return LowerFNEG(Op, DAG);
14496 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14497 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14498 case ISD::SETCC: return LowerSETCC(Op, DAG);
14499 case ISD::SELECT: return LowerSELECT(Op, DAG);
14500 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14501 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14502 case ISD::VASTART: return LowerVASTART(Op, DAG);
14503 case ISD::VAARG: return LowerVAARG(Op, DAG);
14504 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14505 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14506 case ISD::INTRINSIC_VOID:
14507 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14508 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14509 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14510 case ISD::FRAME_TO_ARGS_OFFSET:
14511 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14512 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14513 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14514 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14515 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14516 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14517 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14518 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14519 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14520 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14521 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14522 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14523 case ISD::UMUL_LOHI:
14524 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14527 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14533 case ISD::UMULO: return LowerXALUO(Op, DAG);
14534 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14535 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14539 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14540 case ISD::ADD: return LowerADD(Op, DAG);
14541 case ISD::SUB: return LowerSUB(Op, DAG);
14542 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14546 static void ReplaceATOMIC_LOAD(SDNode *Node,
14547 SmallVectorImpl<SDValue> &Results,
14548 SelectionDAG &DAG) {
14550 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14552 // Convert wide load -> cmpxchg8b/cmpxchg16b
14553 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14554 // (The only way to get a 16-byte load is cmpxchg16b)
14555 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14556 SDValue Zero = DAG.getConstant(0, VT);
14557 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14558 Node->getOperand(0),
14559 Node->getOperand(1), Zero, Zero,
14560 cast<AtomicSDNode>(Node)->getMemOperand(),
14561 cast<AtomicSDNode>(Node)->getOrdering(),
14562 cast<AtomicSDNode>(Node)->getOrdering(),
14563 cast<AtomicSDNode>(Node)->getSynchScope());
14564 Results.push_back(Swap.getValue(0));
14565 Results.push_back(Swap.getValue(1));
14569 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14570 SelectionDAG &DAG, unsigned NewOp) {
14572 assert (Node->getValueType(0) == MVT::i64 &&
14573 "Only know how to expand i64 atomics");
14575 SDValue Chain = Node->getOperand(0);
14576 SDValue In1 = Node->getOperand(1);
14577 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14578 Node->getOperand(2), DAG.getIntPtrConstant(0));
14579 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14580 Node->getOperand(2), DAG.getIntPtrConstant(1));
14581 SDValue Ops[] = { Chain, In1, In2L, In2H };
14582 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14584 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14585 cast<MemSDNode>(Node)->getMemOperand());
14586 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14587 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14588 Results.push_back(Result.getValue(2));
14591 /// ReplaceNodeResults - Replace a node with an illegal result type
14592 /// with a new node built out of custom code.
14593 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14594 SmallVectorImpl<SDValue>&Results,
14595 SelectionDAG &DAG) const {
14597 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14598 switch (N->getOpcode()) {
14600 llvm_unreachable("Do not know how to custom type legalize this operation!");
14601 case ISD::SIGN_EXTEND_INREG:
14606 // We don't want to expand or promote these.
14613 case ISD::UDIVREM: {
14614 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14615 Results.push_back(V);
14618 case ISD::FP_TO_SINT:
14619 case ISD::FP_TO_UINT: {
14620 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14622 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14625 std::pair<SDValue,SDValue> Vals =
14626 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14627 SDValue FIST = Vals.first, StackSlot = Vals.second;
14628 if (FIST.getNode()) {
14629 EVT VT = N->getValueType(0);
14630 // Return a load from the stack slot.
14631 if (StackSlot.getNode())
14632 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14633 MachinePointerInfo(),
14634 false, false, false, 0));
14636 Results.push_back(FIST);
14640 case ISD::UINT_TO_FP: {
14641 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14642 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14643 N->getValueType(0) != MVT::v2f32)
14645 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14647 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14649 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14650 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14651 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14652 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14653 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14654 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14657 case ISD::FP_ROUND: {
14658 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14660 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14661 Results.push_back(V);
14664 case ISD::INTRINSIC_W_CHAIN: {
14665 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14667 default : llvm_unreachable("Do not know how to custom type "
14668 "legalize this intrinsic operation!");
14669 case Intrinsic::x86_rdtsc:
14670 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14672 case Intrinsic::x86_rdtscp:
14673 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14677 case ISD::READCYCLECOUNTER: {
14678 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14681 case ISD::ATOMIC_CMP_SWAP: {
14682 EVT T = N->getValueType(0);
14683 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14684 bool Regs64bit = T == MVT::i128;
14685 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14686 SDValue cpInL, cpInH;
14687 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14688 DAG.getConstant(0, HalfT));
14689 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14690 DAG.getConstant(1, HalfT));
14691 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14692 Regs64bit ? X86::RAX : X86::EAX,
14694 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14695 Regs64bit ? X86::RDX : X86::EDX,
14696 cpInH, cpInL.getValue(1));
14697 SDValue swapInL, swapInH;
14698 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14699 DAG.getConstant(0, HalfT));
14700 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14701 DAG.getConstant(1, HalfT));
14702 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14703 Regs64bit ? X86::RBX : X86::EBX,
14704 swapInL, cpInH.getValue(1));
14705 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14706 Regs64bit ? X86::RCX : X86::ECX,
14707 swapInH, swapInL.getValue(1));
14708 SDValue Ops[] = { swapInH.getValue(0),
14710 swapInH.getValue(1) };
14711 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14712 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14713 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14714 X86ISD::LCMPXCHG8_DAG;
14715 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14716 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14717 Regs64bit ? X86::RAX : X86::EAX,
14718 HalfT, Result.getValue(1));
14719 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14720 Regs64bit ? X86::RDX : X86::EDX,
14721 HalfT, cpOutL.getValue(2));
14722 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14723 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14724 Results.push_back(cpOutH.getValue(1));
14727 case ISD::ATOMIC_LOAD_ADD:
14728 case ISD::ATOMIC_LOAD_AND:
14729 case ISD::ATOMIC_LOAD_NAND:
14730 case ISD::ATOMIC_LOAD_OR:
14731 case ISD::ATOMIC_LOAD_SUB:
14732 case ISD::ATOMIC_LOAD_XOR:
14733 case ISD::ATOMIC_LOAD_MAX:
14734 case ISD::ATOMIC_LOAD_MIN:
14735 case ISD::ATOMIC_LOAD_UMAX:
14736 case ISD::ATOMIC_LOAD_UMIN:
14737 case ISD::ATOMIC_SWAP: {
14739 switch (N->getOpcode()) {
14740 default: llvm_unreachable("Unexpected opcode");
14741 case ISD::ATOMIC_LOAD_ADD:
14742 Opc = X86ISD::ATOMADD64_DAG;
14744 case ISD::ATOMIC_LOAD_AND:
14745 Opc = X86ISD::ATOMAND64_DAG;
14747 case ISD::ATOMIC_LOAD_NAND:
14748 Opc = X86ISD::ATOMNAND64_DAG;
14750 case ISD::ATOMIC_LOAD_OR:
14751 Opc = X86ISD::ATOMOR64_DAG;
14753 case ISD::ATOMIC_LOAD_SUB:
14754 Opc = X86ISD::ATOMSUB64_DAG;
14756 case ISD::ATOMIC_LOAD_XOR:
14757 Opc = X86ISD::ATOMXOR64_DAG;
14759 case ISD::ATOMIC_LOAD_MAX:
14760 Opc = X86ISD::ATOMMAX64_DAG;
14762 case ISD::ATOMIC_LOAD_MIN:
14763 Opc = X86ISD::ATOMMIN64_DAG;
14765 case ISD::ATOMIC_LOAD_UMAX:
14766 Opc = X86ISD::ATOMUMAX64_DAG;
14768 case ISD::ATOMIC_LOAD_UMIN:
14769 Opc = X86ISD::ATOMUMIN64_DAG;
14771 case ISD::ATOMIC_SWAP:
14772 Opc = X86ISD::ATOMSWAP64_DAG;
14775 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14778 case ISD::ATOMIC_LOAD: {
14779 ReplaceATOMIC_LOAD(N, Results, DAG);
14782 case ISD::BITCAST: {
14783 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14784 EVT DstVT = N->getValueType(0);
14785 EVT SrcVT = N->getOperand(0)->getValueType(0);
14787 if (SrcVT != MVT::f64 ||
14788 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14791 unsigned NumElts = DstVT.getVectorNumElements();
14792 EVT SVT = DstVT.getVectorElementType();
14793 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14794 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14795 MVT::v2f64, N->getOperand(0));
14796 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14798 SmallVector<SDValue, 8> Elts;
14799 for (unsigned i = 0, e = NumElts; i != e; ++i)
14800 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14801 ToVecInt, DAG.getIntPtrConstant(i)));
14803 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14808 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14810 default: return nullptr;
14811 case X86ISD::BSF: return "X86ISD::BSF";
14812 case X86ISD::BSR: return "X86ISD::BSR";
14813 case X86ISD::SHLD: return "X86ISD::SHLD";
14814 case X86ISD::SHRD: return "X86ISD::SHRD";
14815 case X86ISD::FAND: return "X86ISD::FAND";
14816 case X86ISD::FANDN: return "X86ISD::FANDN";
14817 case X86ISD::FOR: return "X86ISD::FOR";
14818 case X86ISD::FXOR: return "X86ISD::FXOR";
14819 case X86ISD::FSRL: return "X86ISD::FSRL";
14820 case X86ISD::FILD: return "X86ISD::FILD";
14821 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14822 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14823 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14824 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14825 case X86ISD::FLD: return "X86ISD::FLD";
14826 case X86ISD::FST: return "X86ISD::FST";
14827 case X86ISD::CALL: return "X86ISD::CALL";
14828 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14829 case X86ISD::BT: return "X86ISD::BT";
14830 case X86ISD::CMP: return "X86ISD::CMP";
14831 case X86ISD::COMI: return "X86ISD::COMI";
14832 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14833 case X86ISD::CMPM: return "X86ISD::CMPM";
14834 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14835 case X86ISD::SETCC: return "X86ISD::SETCC";
14836 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14837 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14838 case X86ISD::CMOV: return "X86ISD::CMOV";
14839 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14840 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14841 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14842 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14843 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14844 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14845 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14846 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14847 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14848 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14849 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14850 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14851 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14852 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14853 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14854 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14855 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14856 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14857 case X86ISD::HADD: return "X86ISD::HADD";
14858 case X86ISD::HSUB: return "X86ISD::HSUB";
14859 case X86ISD::FHADD: return "X86ISD::FHADD";
14860 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14861 case X86ISD::UMAX: return "X86ISD::UMAX";
14862 case X86ISD::UMIN: return "X86ISD::UMIN";
14863 case X86ISD::SMAX: return "X86ISD::SMAX";
14864 case X86ISD::SMIN: return "X86ISD::SMIN";
14865 case X86ISD::FMAX: return "X86ISD::FMAX";
14866 case X86ISD::FMIN: return "X86ISD::FMIN";
14867 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14868 case X86ISD::FMINC: return "X86ISD::FMINC";
14869 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14870 case X86ISD::FRCP: return "X86ISD::FRCP";
14871 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14872 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14873 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14874 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14875 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14876 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14877 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14878 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14879 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14880 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14881 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14882 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14883 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14884 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14885 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14886 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14887 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14888 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14889 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14890 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14891 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14892 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14893 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14894 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14895 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14896 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14897 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14898 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14899 case X86ISD::VSHL: return "X86ISD::VSHL";
14900 case X86ISD::VSRL: return "X86ISD::VSRL";
14901 case X86ISD::VSRA: return "X86ISD::VSRA";
14902 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14903 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14904 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14905 case X86ISD::CMPP: return "X86ISD::CMPP";
14906 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14907 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14908 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14909 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14910 case X86ISD::ADD: return "X86ISD::ADD";
14911 case X86ISD::SUB: return "X86ISD::SUB";
14912 case X86ISD::ADC: return "X86ISD::ADC";
14913 case X86ISD::SBB: return "X86ISD::SBB";
14914 case X86ISD::SMUL: return "X86ISD::SMUL";
14915 case X86ISD::UMUL: return "X86ISD::UMUL";
14916 case X86ISD::INC: return "X86ISD::INC";
14917 case X86ISD::DEC: return "X86ISD::DEC";
14918 case X86ISD::OR: return "X86ISD::OR";
14919 case X86ISD::XOR: return "X86ISD::XOR";
14920 case X86ISD::AND: return "X86ISD::AND";
14921 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14922 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14923 case X86ISD::PTEST: return "X86ISD::PTEST";
14924 case X86ISD::TESTP: return "X86ISD::TESTP";
14925 case X86ISD::TESTM: return "X86ISD::TESTM";
14926 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14927 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14928 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14929 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14930 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14931 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14932 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14933 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14934 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14935 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14936 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14937 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14938 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14939 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14940 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14941 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14942 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14943 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14944 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14945 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14946 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14947 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14948 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14949 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14950 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14951 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14952 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14953 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14954 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14955 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14956 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14957 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14958 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14959 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14960 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14961 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14962 case X86ISD::SAHF: return "X86ISD::SAHF";
14963 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14964 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14965 case X86ISD::FMADD: return "X86ISD::FMADD";
14966 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14967 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14968 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14969 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14970 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14971 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14972 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14973 case X86ISD::XTEST: return "X86ISD::XTEST";
14977 // isLegalAddressingMode - Return true if the addressing mode represented
14978 // by AM is legal for this target, for a load/store of the specified type.
14979 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14981 // X86 supports extremely general addressing modes.
14982 CodeModel::Model M = getTargetMachine().getCodeModel();
14983 Reloc::Model R = getTargetMachine().getRelocationModel();
14985 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14986 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14991 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14993 // If a reference to this global requires an extra load, we can't fold it.
14994 if (isGlobalStubReference(GVFlags))
14997 // If BaseGV requires a register for the PIC base, we cannot also have a
14998 // BaseReg specified.
14999 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15002 // If lower 4G is not available, then we must use rip-relative addressing.
15003 if ((M != CodeModel::Small || R != Reloc::Static) &&
15004 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15008 switch (AM.Scale) {
15014 // These scales always work.
15019 // These scales are formed with basereg+scalereg. Only accept if there is
15024 default: // Other stuff never works.
15031 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15032 unsigned Bits = Ty->getScalarSizeInBits();
15034 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15035 // particularly cheaper than those without.
15039 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15040 // variable shifts just as cheap as scalar ones.
15041 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15044 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15045 // fully general vector.
15049 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15050 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15052 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15053 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15054 return NumBits1 > NumBits2;
15057 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15058 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15061 if (!isTypeLegal(EVT::getEVT(Ty1)))
15064 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15066 // Assuming the caller doesn't have a zeroext or signext return parameter,
15067 // truncation all the way down to i1 is valid.
15071 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15072 return isInt<32>(Imm);
15075 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15076 // Can also use sub to handle negated immediates.
15077 return isInt<32>(Imm);
15080 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15081 if (!VT1.isInteger() || !VT2.isInteger())
15083 unsigned NumBits1 = VT1.getSizeInBits();
15084 unsigned NumBits2 = VT2.getSizeInBits();
15085 return NumBits1 > NumBits2;
15088 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15089 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15090 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15093 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15094 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15095 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15098 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15099 EVT VT1 = Val.getValueType();
15100 if (isZExtFree(VT1, VT2))
15103 if (Val.getOpcode() != ISD::LOAD)
15106 if (!VT1.isSimple() || !VT1.isInteger() ||
15107 !VT2.isSimple() || !VT2.isInteger())
15110 switch (VT1.getSimpleVT().SimpleTy) {
15115 // X86 has 8, 16, and 32-bit zero-extending loads.
15123 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15124 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15127 VT = VT.getScalarType();
15129 if (!VT.isSimple())
15132 switch (VT.getSimpleVT().SimpleTy) {
15143 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15144 // i16 instructions are longer (0x66 prefix) and potentially slower.
15145 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15148 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15149 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15150 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15151 /// are assumed to be legal.
15153 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15155 if (!VT.isSimple())
15158 MVT SVT = VT.getSimpleVT();
15160 // Very little shuffling can be done for 64-bit vectors right now.
15161 if (VT.getSizeInBits() == 64)
15164 // If this is a single-input shuffle with no 128 bit lane crossings we can
15165 // lower it into pshufb.
15166 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15167 (SVT.is256BitVector() && Subtarget->hasInt256())) {
15168 bool isLegal = true;
15169 for (unsigned I = 0, E = M.size(); I != E; ++I) {
15170 if (M[I] >= (int)SVT.getVectorNumElements() ||
15171 ShuffleCrosses128bitLane(SVT, I, M[I])) {
15180 // FIXME: blends, shifts.
15181 return (SVT.getVectorNumElements() == 2 ||
15182 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15183 isMOVLMask(M, SVT) ||
15184 isSHUFPMask(M, SVT) ||
15185 isPSHUFDMask(M, SVT) ||
15186 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15187 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15188 isPALIGNRMask(M, SVT, Subtarget) ||
15189 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15190 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15191 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15192 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15193 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15197 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15199 if (!VT.isSimple())
15202 MVT SVT = VT.getSimpleVT();
15203 unsigned NumElts = SVT.getVectorNumElements();
15204 // FIXME: This collection of masks seems suspect.
15207 if (NumElts == 4 && SVT.is128BitVector()) {
15208 return (isMOVLMask(Mask, SVT) ||
15209 isCommutedMOVLMask(Mask, SVT, true) ||
15210 isSHUFPMask(Mask, SVT) ||
15211 isSHUFPMask(Mask, SVT, /* Commuted */ true));
15216 //===----------------------------------------------------------------------===//
15217 // X86 Scheduler Hooks
15218 //===----------------------------------------------------------------------===//
15220 /// Utility function to emit xbegin specifying the start of an RTM region.
15221 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15222 const TargetInstrInfo *TII) {
15223 DebugLoc DL = MI->getDebugLoc();
15225 const BasicBlock *BB = MBB->getBasicBlock();
15226 MachineFunction::iterator I = MBB;
15229 // For the v = xbegin(), we generate
15240 MachineBasicBlock *thisMBB = MBB;
15241 MachineFunction *MF = MBB->getParent();
15242 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15243 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15244 MF->insert(I, mainMBB);
15245 MF->insert(I, sinkMBB);
15247 // Transfer the remainder of BB and its successor edges to sinkMBB.
15248 sinkMBB->splice(sinkMBB->begin(), MBB,
15249 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15250 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15254 // # fallthrough to mainMBB
15255 // # abortion to sinkMBB
15256 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15257 thisMBB->addSuccessor(mainMBB);
15258 thisMBB->addSuccessor(sinkMBB);
15262 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15263 mainMBB->addSuccessor(sinkMBB);
15266 // EAX is live into the sinkMBB
15267 sinkMBB->addLiveIn(X86::EAX);
15268 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15269 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15272 MI->eraseFromParent();
15276 // Get CMPXCHG opcode for the specified data type.
15277 static unsigned getCmpXChgOpcode(EVT VT) {
15278 switch (VT.getSimpleVT().SimpleTy) {
15279 case MVT::i8: return X86::LCMPXCHG8;
15280 case MVT::i16: return X86::LCMPXCHG16;
15281 case MVT::i32: return X86::LCMPXCHG32;
15282 case MVT::i64: return X86::LCMPXCHG64;
15286 llvm_unreachable("Invalid operand size!");
15289 // Get LOAD opcode for the specified data type.
15290 static unsigned getLoadOpcode(EVT VT) {
15291 switch (VT.getSimpleVT().SimpleTy) {
15292 case MVT::i8: return X86::MOV8rm;
15293 case MVT::i16: return X86::MOV16rm;
15294 case MVT::i32: return X86::MOV32rm;
15295 case MVT::i64: return X86::MOV64rm;
15299 llvm_unreachable("Invalid operand size!");
15302 // Get opcode of the non-atomic one from the specified atomic instruction.
15303 static unsigned getNonAtomicOpcode(unsigned Opc) {
15305 case X86::ATOMAND8: return X86::AND8rr;
15306 case X86::ATOMAND16: return X86::AND16rr;
15307 case X86::ATOMAND32: return X86::AND32rr;
15308 case X86::ATOMAND64: return X86::AND64rr;
15309 case X86::ATOMOR8: return X86::OR8rr;
15310 case X86::ATOMOR16: return X86::OR16rr;
15311 case X86::ATOMOR32: return X86::OR32rr;
15312 case X86::ATOMOR64: return X86::OR64rr;
15313 case X86::ATOMXOR8: return X86::XOR8rr;
15314 case X86::ATOMXOR16: return X86::XOR16rr;
15315 case X86::ATOMXOR32: return X86::XOR32rr;
15316 case X86::ATOMXOR64: return X86::XOR64rr;
15318 llvm_unreachable("Unhandled atomic-load-op opcode!");
15321 // Get opcode of the non-atomic one from the specified atomic instruction with
15323 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15324 unsigned &ExtraOpc) {
15326 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
15327 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
15328 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
15329 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
15330 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
15331 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15332 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15333 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15334 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
15335 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15336 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15337 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15338 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
15339 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15340 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15341 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15342 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
15343 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15344 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15345 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15347 llvm_unreachable("Unhandled atomic-load-op opcode!");
15350 // Get opcode of the non-atomic one from the specified atomic instruction for
15351 // 64-bit data type on 32-bit target.
15352 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15354 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
15355 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
15356 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
15357 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
15358 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
15359 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15360 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
15361 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
15362 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
15363 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
15365 llvm_unreachable("Unhandled atomic-load-op opcode!");
15368 // Get opcode of the non-atomic one from the specified atomic instruction for
15369 // 64-bit data type on 32-bit target with extra opcode.
15370 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15372 unsigned &ExtraOpc) {
15374 case X86::ATOMNAND6432:
15375 ExtraOpc = X86::NOT32r;
15376 HiOpc = X86::AND32rr;
15377 return X86::AND32rr;
15379 llvm_unreachable("Unhandled atomic-load-op opcode!");
15382 // Get pseudo CMOV opcode from the specified data type.
15383 static unsigned getPseudoCMOVOpc(EVT VT) {
15384 switch (VT.getSimpleVT().SimpleTy) {
15385 case MVT::i8: return X86::CMOV_GR8;
15386 case MVT::i16: return X86::CMOV_GR16;
15387 case MVT::i32: return X86::CMOV_GR32;
15391 llvm_unreachable("Unknown CMOV opcode!");
15394 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15395 // They will be translated into a spin-loop or compare-exchange loop from
15398 // dst = atomic-fetch-op MI.addr, MI.val
15404 // t1 = LOAD MI.addr
15406 // t4 = phi(t1, t3 / loop)
15407 // t2 = OP MI.val, t4
15409 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15415 MachineBasicBlock *
15416 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15417 MachineBasicBlock *MBB) const {
15418 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15419 DebugLoc DL = MI->getDebugLoc();
15421 MachineFunction *MF = MBB->getParent();
15422 MachineRegisterInfo &MRI = MF->getRegInfo();
15424 const BasicBlock *BB = MBB->getBasicBlock();
15425 MachineFunction::iterator I = MBB;
15428 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15429 "Unexpected number of operands");
15431 assert(MI->hasOneMemOperand() &&
15432 "Expected atomic-load-op to have one memoperand");
15434 // Memory Reference
15435 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15436 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15438 unsigned DstReg, SrcReg;
15439 unsigned MemOpndSlot;
15441 unsigned CurOp = 0;
15443 DstReg = MI->getOperand(CurOp++).getReg();
15444 MemOpndSlot = CurOp;
15445 CurOp += X86::AddrNumOperands;
15446 SrcReg = MI->getOperand(CurOp++).getReg();
15448 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15449 MVT::SimpleValueType VT = *RC->vt_begin();
15450 unsigned t1 = MRI.createVirtualRegister(RC);
15451 unsigned t2 = MRI.createVirtualRegister(RC);
15452 unsigned t3 = MRI.createVirtualRegister(RC);
15453 unsigned t4 = MRI.createVirtualRegister(RC);
15454 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15456 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15457 unsigned LOADOpc = getLoadOpcode(VT);
15459 // For the atomic load-arith operator, we generate
15462 // t1 = LOAD [MI.addr]
15464 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15465 // t1 = OP MI.val, EAX
15467 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15473 MachineBasicBlock *thisMBB = MBB;
15474 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15475 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15476 MF->insert(I, mainMBB);
15477 MF->insert(I, sinkMBB);
15479 MachineInstrBuilder MIB;
15481 // Transfer the remainder of BB and its successor edges to sinkMBB.
15482 sinkMBB->splice(sinkMBB->begin(), MBB,
15483 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15484 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15487 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15488 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15489 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15491 NewMO.setIsKill(false);
15492 MIB.addOperand(NewMO);
15494 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15495 unsigned flags = (*MMOI)->getFlags();
15496 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15497 MachineMemOperand *MMO =
15498 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15499 (*MMOI)->getSize(),
15500 (*MMOI)->getBaseAlignment(),
15501 (*MMOI)->getTBAAInfo(),
15502 (*MMOI)->getRanges());
15503 MIB.addMemOperand(MMO);
15506 thisMBB->addSuccessor(mainMBB);
15509 MachineBasicBlock *origMainMBB = mainMBB;
15512 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15513 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15515 unsigned Opc = MI->getOpcode();
15518 llvm_unreachable("Unhandled atomic-load-op opcode!");
15519 case X86::ATOMAND8:
15520 case X86::ATOMAND16:
15521 case X86::ATOMAND32:
15522 case X86::ATOMAND64:
15524 case X86::ATOMOR16:
15525 case X86::ATOMOR32:
15526 case X86::ATOMOR64:
15527 case X86::ATOMXOR8:
15528 case X86::ATOMXOR16:
15529 case X86::ATOMXOR32:
15530 case X86::ATOMXOR64: {
15531 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15532 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15536 case X86::ATOMNAND8:
15537 case X86::ATOMNAND16:
15538 case X86::ATOMNAND32:
15539 case X86::ATOMNAND64: {
15540 unsigned Tmp = MRI.createVirtualRegister(RC);
15542 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15543 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15545 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15548 case X86::ATOMMAX8:
15549 case X86::ATOMMAX16:
15550 case X86::ATOMMAX32:
15551 case X86::ATOMMAX64:
15552 case X86::ATOMMIN8:
15553 case X86::ATOMMIN16:
15554 case X86::ATOMMIN32:
15555 case X86::ATOMMIN64:
15556 case X86::ATOMUMAX8:
15557 case X86::ATOMUMAX16:
15558 case X86::ATOMUMAX32:
15559 case X86::ATOMUMAX64:
15560 case X86::ATOMUMIN8:
15561 case X86::ATOMUMIN16:
15562 case X86::ATOMUMIN32:
15563 case X86::ATOMUMIN64: {
15565 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15567 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15571 if (Subtarget->hasCMov()) {
15572 if (VT != MVT::i8) {
15574 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15578 // Promote i8 to i32 to use CMOV32
15579 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15580 const TargetRegisterClass *RC32 =
15581 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15582 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15583 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15584 unsigned Tmp = MRI.createVirtualRegister(RC32);
15586 unsigned Undef = MRI.createVirtualRegister(RC32);
15587 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15589 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15592 .addImm(X86::sub_8bit);
15593 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15596 .addImm(X86::sub_8bit);
15598 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15602 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15603 .addReg(Tmp, 0, X86::sub_8bit);
15606 // Use pseudo select and lower them.
15607 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15608 "Invalid atomic-load-op transformation!");
15609 unsigned SelOpc = getPseudoCMOVOpc(VT);
15610 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15611 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15612 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15613 .addReg(SrcReg).addReg(t4)
15615 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15616 // Replace the original PHI node as mainMBB is changed after CMOV
15618 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15619 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15620 Phi->eraseFromParent();
15626 // Copy PhyReg back from virtual register.
15627 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15630 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15631 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15632 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15634 NewMO.setIsKill(false);
15635 MIB.addOperand(NewMO);
15638 MIB.setMemRefs(MMOBegin, MMOEnd);
15640 // Copy PhyReg back to virtual register.
15641 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15644 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15646 mainMBB->addSuccessor(origMainMBB);
15647 mainMBB->addSuccessor(sinkMBB);
15650 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15651 TII->get(TargetOpcode::COPY), DstReg)
15654 MI->eraseFromParent();
15658 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15659 // instructions. They will be translated into a spin-loop or compare-exchange
15663 // dst = atomic-fetch-op MI.addr, MI.val
15669 // t1L = LOAD [MI.addr + 0]
15670 // t1H = LOAD [MI.addr + 4]
15672 // t4L = phi(t1L, t3L / loop)
15673 // t4H = phi(t1H, t3H / loop)
15674 // t2L = OP MI.val.lo, t4L
15675 // t2H = OP MI.val.hi, t4H
15680 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15688 MachineBasicBlock *
15689 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15690 MachineBasicBlock *MBB) const {
15691 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15692 DebugLoc DL = MI->getDebugLoc();
15694 MachineFunction *MF = MBB->getParent();
15695 MachineRegisterInfo &MRI = MF->getRegInfo();
15697 const BasicBlock *BB = MBB->getBasicBlock();
15698 MachineFunction::iterator I = MBB;
15701 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15702 "Unexpected number of operands");
15704 assert(MI->hasOneMemOperand() &&
15705 "Expected atomic-load-op32 to have one memoperand");
15707 // Memory Reference
15708 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15709 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15711 unsigned DstLoReg, DstHiReg;
15712 unsigned SrcLoReg, SrcHiReg;
15713 unsigned MemOpndSlot;
15715 unsigned CurOp = 0;
15717 DstLoReg = MI->getOperand(CurOp++).getReg();
15718 DstHiReg = MI->getOperand(CurOp++).getReg();
15719 MemOpndSlot = CurOp;
15720 CurOp += X86::AddrNumOperands;
15721 SrcLoReg = MI->getOperand(CurOp++).getReg();
15722 SrcHiReg = MI->getOperand(CurOp++).getReg();
15724 const TargetRegisterClass *RC = &X86::GR32RegClass;
15725 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15727 unsigned t1L = MRI.createVirtualRegister(RC);
15728 unsigned t1H = MRI.createVirtualRegister(RC);
15729 unsigned t2L = MRI.createVirtualRegister(RC);
15730 unsigned t2H = MRI.createVirtualRegister(RC);
15731 unsigned t3L = MRI.createVirtualRegister(RC);
15732 unsigned t3H = MRI.createVirtualRegister(RC);
15733 unsigned t4L = MRI.createVirtualRegister(RC);
15734 unsigned t4H = MRI.createVirtualRegister(RC);
15736 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15737 unsigned LOADOpc = X86::MOV32rm;
15739 // For the atomic load-arith operator, we generate
15742 // t1L = LOAD [MI.addr + 0]
15743 // t1H = LOAD [MI.addr + 4]
15745 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15746 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15747 // t2L = OP MI.val.lo, t4L
15748 // t2H = OP MI.val.hi, t4H
15751 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15759 MachineBasicBlock *thisMBB = MBB;
15760 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15761 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15762 MF->insert(I, mainMBB);
15763 MF->insert(I, sinkMBB);
15765 MachineInstrBuilder MIB;
15767 // Transfer the remainder of BB and its successor edges to sinkMBB.
15768 sinkMBB->splice(sinkMBB->begin(), MBB,
15769 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15770 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15774 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15775 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15776 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15778 NewMO.setIsKill(false);
15779 MIB.addOperand(NewMO);
15781 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15782 unsigned flags = (*MMOI)->getFlags();
15783 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15784 MachineMemOperand *MMO =
15785 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15786 (*MMOI)->getSize(),
15787 (*MMOI)->getBaseAlignment(),
15788 (*MMOI)->getTBAAInfo(),
15789 (*MMOI)->getRanges());
15790 MIB.addMemOperand(MMO);
15792 MachineInstr *LowMI = MIB;
15795 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15796 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15797 if (i == X86::AddrDisp) {
15798 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15800 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15802 NewMO.setIsKill(false);
15803 MIB.addOperand(NewMO);
15806 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15808 thisMBB->addSuccessor(mainMBB);
15811 MachineBasicBlock *origMainMBB = mainMBB;
15814 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15815 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15816 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15817 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15819 unsigned Opc = MI->getOpcode();
15822 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15823 case X86::ATOMAND6432:
15824 case X86::ATOMOR6432:
15825 case X86::ATOMXOR6432:
15826 case X86::ATOMADD6432:
15827 case X86::ATOMSUB6432: {
15829 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15830 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15832 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15836 case X86::ATOMNAND6432: {
15837 unsigned HiOpc, NOTOpc;
15838 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15839 unsigned TmpL = MRI.createVirtualRegister(RC);
15840 unsigned TmpH = MRI.createVirtualRegister(RC);
15841 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15843 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15845 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15846 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15849 case X86::ATOMMAX6432:
15850 case X86::ATOMMIN6432:
15851 case X86::ATOMUMAX6432:
15852 case X86::ATOMUMIN6432: {
15854 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15855 unsigned cL = MRI.createVirtualRegister(RC8);
15856 unsigned cH = MRI.createVirtualRegister(RC8);
15857 unsigned cL32 = MRI.createVirtualRegister(RC);
15858 unsigned cH32 = MRI.createVirtualRegister(RC);
15859 unsigned cc = MRI.createVirtualRegister(RC);
15860 // cl := cmp src_lo, lo
15861 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15862 .addReg(SrcLoReg).addReg(t4L);
15863 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15864 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15865 // ch := cmp src_hi, hi
15866 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15867 .addReg(SrcHiReg).addReg(t4H);
15868 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15869 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15870 // cc := if (src_hi == hi) ? cl : ch;
15871 if (Subtarget->hasCMov()) {
15872 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15873 .addReg(cH32).addReg(cL32);
15875 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15876 .addReg(cH32).addReg(cL32)
15877 .addImm(X86::COND_E);
15878 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15880 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15881 if (Subtarget->hasCMov()) {
15882 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15883 .addReg(SrcLoReg).addReg(t4L);
15884 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15885 .addReg(SrcHiReg).addReg(t4H);
15887 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15888 .addReg(SrcLoReg).addReg(t4L)
15889 .addImm(X86::COND_NE);
15890 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15891 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15892 // 2nd CMOV lowering.
15893 mainMBB->addLiveIn(X86::EFLAGS);
15894 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15895 .addReg(SrcHiReg).addReg(t4H)
15896 .addImm(X86::COND_NE);
15897 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15898 // Replace the original PHI node as mainMBB is changed after CMOV
15900 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15901 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15902 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15903 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15904 PhiL->eraseFromParent();
15905 PhiH->eraseFromParent();
15909 case X86::ATOMSWAP6432: {
15911 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15912 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15913 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15918 // Copy EDX:EAX back from HiReg:LoReg
15919 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15920 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15921 // Copy ECX:EBX from t1H:t1L
15922 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15923 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15925 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15926 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15927 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15929 NewMO.setIsKill(false);
15930 MIB.addOperand(NewMO);
15932 MIB.setMemRefs(MMOBegin, MMOEnd);
15934 // Copy EDX:EAX back to t3H:t3L
15935 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15936 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15938 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15940 mainMBB->addSuccessor(origMainMBB);
15941 mainMBB->addSuccessor(sinkMBB);
15944 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15945 TII->get(TargetOpcode::COPY), DstLoReg)
15947 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15948 TII->get(TargetOpcode::COPY), DstHiReg)
15951 MI->eraseFromParent();
15955 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15956 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15957 // in the .td file.
15958 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15959 const TargetInstrInfo *TII) {
15961 switch (MI->getOpcode()) {
15962 default: llvm_unreachable("illegal opcode!");
15963 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15964 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15965 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15966 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15967 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15968 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15969 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15970 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15973 DebugLoc dl = MI->getDebugLoc();
15974 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15976 unsigned NumArgs = MI->getNumOperands();
15977 for (unsigned i = 1; i < NumArgs; ++i) {
15978 MachineOperand &Op = MI->getOperand(i);
15979 if (!(Op.isReg() && Op.isImplicit()))
15980 MIB.addOperand(Op);
15982 if (MI->hasOneMemOperand())
15983 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15985 BuildMI(*BB, MI, dl,
15986 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15987 .addReg(X86::XMM0);
15989 MI->eraseFromParent();
15993 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15994 // defs in an instruction pattern
15995 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15996 const TargetInstrInfo *TII) {
15998 switch (MI->getOpcode()) {
15999 default: llvm_unreachable("illegal opcode!");
16000 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16001 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16002 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16003 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16004 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16005 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16006 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16007 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16010 DebugLoc dl = MI->getDebugLoc();
16011 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16013 unsigned NumArgs = MI->getNumOperands(); // remove the results
16014 for (unsigned i = 1; i < NumArgs; ++i) {
16015 MachineOperand &Op = MI->getOperand(i);
16016 if (!(Op.isReg() && Op.isImplicit()))
16017 MIB.addOperand(Op);
16019 if (MI->hasOneMemOperand())
16020 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16022 BuildMI(*BB, MI, dl,
16023 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16026 MI->eraseFromParent();
16030 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16031 const TargetInstrInfo *TII,
16032 const X86Subtarget* Subtarget) {
16033 DebugLoc dl = MI->getDebugLoc();
16035 // Address into RAX/EAX, other two args into ECX, EDX.
16036 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16037 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16038 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16039 for (int i = 0; i < X86::AddrNumOperands; ++i)
16040 MIB.addOperand(MI->getOperand(i));
16042 unsigned ValOps = X86::AddrNumOperands;
16043 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16044 .addReg(MI->getOperand(ValOps).getReg());
16045 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16046 .addReg(MI->getOperand(ValOps+1).getReg());
16048 // The instruction doesn't actually take any operands though.
16049 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16051 MI->eraseFromParent(); // The pseudo is gone now.
16055 MachineBasicBlock *
16056 X86TargetLowering::EmitVAARG64WithCustomInserter(
16058 MachineBasicBlock *MBB) const {
16059 // Emit va_arg instruction on X86-64.
16061 // Operands to this pseudo-instruction:
16062 // 0 ) Output : destination address (reg)
16063 // 1-5) Input : va_list address (addr, i64mem)
16064 // 6 ) ArgSize : Size (in bytes) of vararg type
16065 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16066 // 8 ) Align : Alignment of type
16067 // 9 ) EFLAGS (implicit-def)
16069 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16070 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16072 unsigned DestReg = MI->getOperand(0).getReg();
16073 MachineOperand &Base = MI->getOperand(1);
16074 MachineOperand &Scale = MI->getOperand(2);
16075 MachineOperand &Index = MI->getOperand(3);
16076 MachineOperand &Disp = MI->getOperand(4);
16077 MachineOperand &Segment = MI->getOperand(5);
16078 unsigned ArgSize = MI->getOperand(6).getImm();
16079 unsigned ArgMode = MI->getOperand(7).getImm();
16080 unsigned Align = MI->getOperand(8).getImm();
16082 // Memory Reference
16083 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16084 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16085 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16087 // Machine Information
16088 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16089 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16090 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16091 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16092 DebugLoc DL = MI->getDebugLoc();
16094 // struct va_list {
16097 // i64 overflow_area (address)
16098 // i64 reg_save_area (address)
16100 // sizeof(va_list) = 24
16101 // alignment(va_list) = 8
16103 unsigned TotalNumIntRegs = 6;
16104 unsigned TotalNumXMMRegs = 8;
16105 bool UseGPOffset = (ArgMode == 1);
16106 bool UseFPOffset = (ArgMode == 2);
16107 unsigned MaxOffset = TotalNumIntRegs * 8 +
16108 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16110 /* Align ArgSize to a multiple of 8 */
16111 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16112 bool NeedsAlign = (Align > 8);
16114 MachineBasicBlock *thisMBB = MBB;
16115 MachineBasicBlock *overflowMBB;
16116 MachineBasicBlock *offsetMBB;
16117 MachineBasicBlock *endMBB;
16119 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
16120 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
16121 unsigned OffsetReg = 0;
16123 if (!UseGPOffset && !UseFPOffset) {
16124 // If we only pull from the overflow region, we don't create a branch.
16125 // We don't need to alter control flow.
16126 OffsetDestReg = 0; // unused
16127 OverflowDestReg = DestReg;
16129 offsetMBB = nullptr;
16130 overflowMBB = thisMBB;
16133 // First emit code to check if gp_offset (or fp_offset) is below the bound.
16134 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16135 // If not, pull from overflow_area. (branch to overflowMBB)
16140 // offsetMBB overflowMBB
16145 // Registers for the PHI in endMBB
16146 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16147 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16149 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16150 MachineFunction *MF = MBB->getParent();
16151 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16152 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16153 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16155 MachineFunction::iterator MBBIter = MBB;
16158 // Insert the new basic blocks
16159 MF->insert(MBBIter, offsetMBB);
16160 MF->insert(MBBIter, overflowMBB);
16161 MF->insert(MBBIter, endMBB);
16163 // Transfer the remainder of MBB and its successor edges to endMBB.
16164 endMBB->splice(endMBB->begin(), thisMBB,
16165 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16166 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16168 // Make offsetMBB and overflowMBB successors of thisMBB
16169 thisMBB->addSuccessor(offsetMBB);
16170 thisMBB->addSuccessor(overflowMBB);
16172 // endMBB is a successor of both offsetMBB and overflowMBB
16173 offsetMBB->addSuccessor(endMBB);
16174 overflowMBB->addSuccessor(endMBB);
16176 // Load the offset value into a register
16177 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16178 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16182 .addDisp(Disp, UseFPOffset ? 4 : 0)
16183 .addOperand(Segment)
16184 .setMemRefs(MMOBegin, MMOEnd);
16186 // Check if there is enough room left to pull this argument.
16187 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16189 .addImm(MaxOffset + 8 - ArgSizeA8);
16191 // Branch to "overflowMBB" if offset >= max
16192 // Fall through to "offsetMBB" otherwise
16193 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16194 .addMBB(overflowMBB);
16197 // In offsetMBB, emit code to use the reg_save_area.
16199 assert(OffsetReg != 0);
16201 // Read the reg_save_area address.
16202 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16203 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16208 .addOperand(Segment)
16209 .setMemRefs(MMOBegin, MMOEnd);
16211 // Zero-extend the offset
16212 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16213 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16216 .addImm(X86::sub_32bit);
16218 // Add the offset to the reg_save_area to get the final address.
16219 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16220 .addReg(OffsetReg64)
16221 .addReg(RegSaveReg);
16223 // Compute the offset for the next argument
16224 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16225 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16227 .addImm(UseFPOffset ? 16 : 8);
16229 // Store it back into the va_list.
16230 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16234 .addDisp(Disp, UseFPOffset ? 4 : 0)
16235 .addOperand(Segment)
16236 .addReg(NextOffsetReg)
16237 .setMemRefs(MMOBegin, MMOEnd);
16240 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16245 // Emit code to use overflow area
16248 // Load the overflow_area address into a register.
16249 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16250 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16255 .addOperand(Segment)
16256 .setMemRefs(MMOBegin, MMOEnd);
16258 // If we need to align it, do so. Otherwise, just copy the address
16259 // to OverflowDestReg.
16261 // Align the overflow address
16262 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16263 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16265 // aligned_addr = (addr + (align-1)) & ~(align-1)
16266 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16267 .addReg(OverflowAddrReg)
16270 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16272 .addImm(~(uint64_t)(Align-1));
16274 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16275 .addReg(OverflowAddrReg);
16278 // Compute the next overflow address after this argument.
16279 // (the overflow address should be kept 8-byte aligned)
16280 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16281 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16282 .addReg(OverflowDestReg)
16283 .addImm(ArgSizeA8);
16285 // Store the new overflow address.
16286 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16291 .addOperand(Segment)
16292 .addReg(NextAddrReg)
16293 .setMemRefs(MMOBegin, MMOEnd);
16295 // If we branched, emit the PHI to the front of endMBB.
16297 BuildMI(*endMBB, endMBB->begin(), DL,
16298 TII->get(X86::PHI), DestReg)
16299 .addReg(OffsetDestReg).addMBB(offsetMBB)
16300 .addReg(OverflowDestReg).addMBB(overflowMBB);
16303 // Erase the pseudo instruction
16304 MI->eraseFromParent();
16309 MachineBasicBlock *
16310 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16312 MachineBasicBlock *MBB) const {
16313 // Emit code to save XMM registers to the stack. The ABI says that the
16314 // number of registers to save is given in %al, so it's theoretically
16315 // possible to do an indirect jump trick to avoid saving all of them,
16316 // however this code takes a simpler approach and just executes all
16317 // of the stores if %al is non-zero. It's less code, and it's probably
16318 // easier on the hardware branch predictor, and stores aren't all that
16319 // expensive anyway.
16321 // Create the new basic blocks. One block contains all the XMM stores,
16322 // and one block is the final destination regardless of whether any
16323 // stores were performed.
16324 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16325 MachineFunction *F = MBB->getParent();
16326 MachineFunction::iterator MBBIter = MBB;
16328 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16329 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16330 F->insert(MBBIter, XMMSaveMBB);
16331 F->insert(MBBIter, EndMBB);
16333 // Transfer the remainder of MBB and its successor edges to EndMBB.
16334 EndMBB->splice(EndMBB->begin(), MBB,
16335 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16336 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16338 // The original block will now fall through to the XMM save block.
16339 MBB->addSuccessor(XMMSaveMBB);
16340 // The XMMSaveMBB will fall through to the end block.
16341 XMMSaveMBB->addSuccessor(EndMBB);
16343 // Now add the instructions.
16344 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16345 DebugLoc DL = MI->getDebugLoc();
16347 unsigned CountReg = MI->getOperand(0).getReg();
16348 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16349 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16351 if (!Subtarget->isTargetWin64()) {
16352 // If %al is 0, branch around the XMM save block.
16353 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16354 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16355 MBB->addSuccessor(EndMBB);
16358 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16359 // that was just emitted, but clearly shouldn't be "saved".
16360 assert((MI->getNumOperands() <= 3 ||
16361 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16362 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16363 && "Expected last argument to be EFLAGS");
16364 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16365 // In the XMM save block, save all the XMM argument registers.
16366 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16367 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16368 MachineMemOperand *MMO =
16369 F->getMachineMemOperand(
16370 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16371 MachineMemOperand::MOStore,
16372 /*Size=*/16, /*Align=*/16);
16373 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16374 .addFrameIndex(RegSaveFrameIndex)
16375 .addImm(/*Scale=*/1)
16376 .addReg(/*IndexReg=*/0)
16377 .addImm(/*Disp=*/Offset)
16378 .addReg(/*Segment=*/0)
16379 .addReg(MI->getOperand(i).getReg())
16380 .addMemOperand(MMO);
16383 MI->eraseFromParent(); // The pseudo instruction is gone now.
16388 // The EFLAGS operand of SelectItr might be missing a kill marker
16389 // because there were multiple uses of EFLAGS, and ISel didn't know
16390 // which to mark. Figure out whether SelectItr should have had a
16391 // kill marker, and set it if it should. Returns the correct kill
16393 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16394 MachineBasicBlock* BB,
16395 const TargetRegisterInfo* TRI) {
16396 // Scan forward through BB for a use/def of EFLAGS.
16397 MachineBasicBlock::iterator miI(std::next(SelectItr));
16398 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16399 const MachineInstr& mi = *miI;
16400 if (mi.readsRegister(X86::EFLAGS))
16402 if (mi.definesRegister(X86::EFLAGS))
16403 break; // Should have kill-flag - update below.
16406 // If we hit the end of the block, check whether EFLAGS is live into a
16408 if (miI == BB->end()) {
16409 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16410 sEnd = BB->succ_end();
16411 sItr != sEnd; ++sItr) {
16412 MachineBasicBlock* succ = *sItr;
16413 if (succ->isLiveIn(X86::EFLAGS))
16418 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16419 // out. SelectMI should have a kill flag on EFLAGS.
16420 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16424 MachineBasicBlock *
16425 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16426 MachineBasicBlock *BB) const {
16427 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16428 DebugLoc DL = MI->getDebugLoc();
16430 // To "insert" a SELECT_CC instruction, we actually have to insert the
16431 // diamond control-flow pattern. The incoming instruction knows the
16432 // destination vreg to set, the condition code register to branch on, the
16433 // true/false values to select between, and a branch opcode to use.
16434 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16435 MachineFunction::iterator It = BB;
16441 // cmpTY ccX, r1, r2
16443 // fallthrough --> copy0MBB
16444 MachineBasicBlock *thisMBB = BB;
16445 MachineFunction *F = BB->getParent();
16446 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16447 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16448 F->insert(It, copy0MBB);
16449 F->insert(It, sinkMBB);
16451 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16452 // live into the sink and copy blocks.
16453 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16454 if (!MI->killsRegister(X86::EFLAGS) &&
16455 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16456 copy0MBB->addLiveIn(X86::EFLAGS);
16457 sinkMBB->addLiveIn(X86::EFLAGS);
16460 // Transfer the remainder of BB and its successor edges to sinkMBB.
16461 sinkMBB->splice(sinkMBB->begin(), BB,
16462 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16463 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16465 // Add the true and fallthrough blocks as its successors.
16466 BB->addSuccessor(copy0MBB);
16467 BB->addSuccessor(sinkMBB);
16469 // Create the conditional branch instruction.
16471 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16472 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16475 // %FalseValue = ...
16476 // # fallthrough to sinkMBB
16477 copy0MBB->addSuccessor(sinkMBB);
16480 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16482 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16483 TII->get(X86::PHI), MI->getOperand(0).getReg())
16484 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16485 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16487 MI->eraseFromParent(); // The pseudo instruction is gone now.
16491 MachineBasicBlock *
16492 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16493 bool Is64Bit) const {
16494 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16495 DebugLoc DL = MI->getDebugLoc();
16496 MachineFunction *MF = BB->getParent();
16497 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16499 assert(MF->shouldSplitStack());
16501 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16502 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16505 // ... [Till the alloca]
16506 // If stacklet is not large enough, jump to mallocMBB
16509 // Allocate by subtracting from RSP
16510 // Jump to continueMBB
16513 // Allocate by call to runtime
16517 // [rest of original BB]
16520 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16521 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16522 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16524 MachineRegisterInfo &MRI = MF->getRegInfo();
16525 const TargetRegisterClass *AddrRegClass =
16526 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16528 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16529 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16530 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16531 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16532 sizeVReg = MI->getOperand(1).getReg(),
16533 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16535 MachineFunction::iterator MBBIter = BB;
16538 MF->insert(MBBIter, bumpMBB);
16539 MF->insert(MBBIter, mallocMBB);
16540 MF->insert(MBBIter, continueMBB);
16542 continueMBB->splice(continueMBB->begin(), BB,
16543 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16544 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16546 // Add code to the main basic block to check if the stack limit has been hit,
16547 // and if so, jump to mallocMBB otherwise to bumpMBB.
16548 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16549 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16550 .addReg(tmpSPVReg).addReg(sizeVReg);
16551 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16552 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16553 .addReg(SPLimitVReg);
16554 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16556 // bumpMBB simply decreases the stack pointer, since we know the current
16557 // stacklet has enough space.
16558 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16559 .addReg(SPLimitVReg);
16560 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16561 .addReg(SPLimitVReg);
16562 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16564 // Calls into a routine in libgcc to allocate more space from the heap.
16565 const uint32_t *RegMask =
16566 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16568 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16570 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16571 .addExternalSymbol("__morestack_allocate_stack_space")
16572 .addRegMask(RegMask)
16573 .addReg(X86::RDI, RegState::Implicit)
16574 .addReg(X86::RAX, RegState::ImplicitDefine);
16576 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16578 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16579 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16580 .addExternalSymbol("__morestack_allocate_stack_space")
16581 .addRegMask(RegMask)
16582 .addReg(X86::EAX, RegState::ImplicitDefine);
16586 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16589 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16590 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16591 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16593 // Set up the CFG correctly.
16594 BB->addSuccessor(bumpMBB);
16595 BB->addSuccessor(mallocMBB);
16596 mallocMBB->addSuccessor(continueMBB);
16597 bumpMBB->addSuccessor(continueMBB);
16599 // Take care of the PHI nodes.
16600 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16601 MI->getOperand(0).getReg())
16602 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16603 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16605 // Delete the original pseudo instruction.
16606 MI->eraseFromParent();
16609 return continueMBB;
16612 MachineBasicBlock *
16613 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16614 MachineBasicBlock *BB) const {
16615 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16616 DebugLoc DL = MI->getDebugLoc();
16618 assert(!Subtarget->isTargetMacho());
16620 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16621 // non-trivial part is impdef of ESP.
16623 if (Subtarget->isTargetWin64()) {
16624 if (Subtarget->isTargetCygMing()) {
16625 // ___chkstk(Mingw64):
16626 // Clobbers R10, R11, RAX and EFLAGS.
16628 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16629 .addExternalSymbol("___chkstk")
16630 .addReg(X86::RAX, RegState::Implicit)
16631 .addReg(X86::RSP, RegState::Implicit)
16632 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16633 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16634 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16636 // __chkstk(MSVCRT): does not update stack pointer.
16637 // Clobbers R10, R11 and EFLAGS.
16638 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16639 .addExternalSymbol("__chkstk")
16640 .addReg(X86::RAX, RegState::Implicit)
16641 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16642 // RAX has the offset to be subtracted from RSP.
16643 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16648 const char *StackProbeSymbol =
16649 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16651 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16652 .addExternalSymbol(StackProbeSymbol)
16653 .addReg(X86::EAX, RegState::Implicit)
16654 .addReg(X86::ESP, RegState::Implicit)
16655 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16656 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16657 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16660 MI->eraseFromParent(); // The pseudo instruction is gone now.
16664 MachineBasicBlock *
16665 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16666 MachineBasicBlock *BB) const {
16667 // This is pretty easy. We're taking the value that we received from
16668 // our load from the relocation, sticking it in either RDI (x86-64)
16669 // or EAX and doing an indirect call. The return value will then
16670 // be in the normal return register.
16671 const X86InstrInfo *TII
16672 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16673 DebugLoc DL = MI->getDebugLoc();
16674 MachineFunction *F = BB->getParent();
16676 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16677 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16679 // Get a register mask for the lowered call.
16680 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16681 // proper register mask.
16682 const uint32_t *RegMask =
16683 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16684 if (Subtarget->is64Bit()) {
16685 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16686 TII->get(X86::MOV64rm), X86::RDI)
16688 .addImm(0).addReg(0)
16689 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16690 MI->getOperand(3).getTargetFlags())
16692 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16693 addDirectMem(MIB, X86::RDI);
16694 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16695 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16696 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16697 TII->get(X86::MOV32rm), X86::EAX)
16699 .addImm(0).addReg(0)
16700 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16701 MI->getOperand(3).getTargetFlags())
16703 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16704 addDirectMem(MIB, X86::EAX);
16705 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16707 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16708 TII->get(X86::MOV32rm), X86::EAX)
16709 .addReg(TII->getGlobalBaseReg(F))
16710 .addImm(0).addReg(0)
16711 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16712 MI->getOperand(3).getTargetFlags())
16714 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16715 addDirectMem(MIB, X86::EAX);
16716 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16719 MI->eraseFromParent(); // The pseudo instruction is gone now.
16723 MachineBasicBlock *
16724 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16725 MachineBasicBlock *MBB) const {
16726 DebugLoc DL = MI->getDebugLoc();
16727 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16729 MachineFunction *MF = MBB->getParent();
16730 MachineRegisterInfo &MRI = MF->getRegInfo();
16732 const BasicBlock *BB = MBB->getBasicBlock();
16733 MachineFunction::iterator I = MBB;
16736 // Memory Reference
16737 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16738 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16741 unsigned MemOpndSlot = 0;
16743 unsigned CurOp = 0;
16745 DstReg = MI->getOperand(CurOp++).getReg();
16746 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16747 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16748 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16749 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16751 MemOpndSlot = CurOp;
16753 MVT PVT = getPointerTy();
16754 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16755 "Invalid Pointer Size!");
16757 // For v = setjmp(buf), we generate
16760 // buf[LabelOffset] = restoreMBB
16761 // SjLjSetup restoreMBB
16767 // v = phi(main, restore)
16772 MachineBasicBlock *thisMBB = MBB;
16773 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16774 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16775 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16776 MF->insert(I, mainMBB);
16777 MF->insert(I, sinkMBB);
16778 MF->push_back(restoreMBB);
16780 MachineInstrBuilder MIB;
16782 // Transfer the remainder of BB and its successor edges to sinkMBB.
16783 sinkMBB->splice(sinkMBB->begin(), MBB,
16784 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16785 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16788 unsigned PtrStoreOpc = 0;
16789 unsigned LabelReg = 0;
16790 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16791 Reloc::Model RM = getTargetMachine().getRelocationModel();
16792 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16793 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16795 // Prepare IP either in reg or imm.
16796 if (!UseImmLabel) {
16797 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16798 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16799 LabelReg = MRI.createVirtualRegister(PtrRC);
16800 if (Subtarget->is64Bit()) {
16801 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16805 .addMBB(restoreMBB)
16808 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16809 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16810 .addReg(XII->getGlobalBaseReg(MF))
16813 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16817 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16819 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16820 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16821 if (i == X86::AddrDisp)
16822 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16824 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16827 MIB.addReg(LabelReg);
16829 MIB.addMBB(restoreMBB);
16830 MIB.setMemRefs(MMOBegin, MMOEnd);
16832 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16833 .addMBB(restoreMBB);
16835 const X86RegisterInfo *RegInfo =
16836 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16837 MIB.addRegMask(RegInfo->getNoPreservedMask());
16838 thisMBB->addSuccessor(mainMBB);
16839 thisMBB->addSuccessor(restoreMBB);
16843 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16844 mainMBB->addSuccessor(sinkMBB);
16847 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16848 TII->get(X86::PHI), DstReg)
16849 .addReg(mainDstReg).addMBB(mainMBB)
16850 .addReg(restoreDstReg).addMBB(restoreMBB);
16853 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16854 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16855 restoreMBB->addSuccessor(sinkMBB);
16857 MI->eraseFromParent();
16861 MachineBasicBlock *
16862 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16863 MachineBasicBlock *MBB) const {
16864 DebugLoc DL = MI->getDebugLoc();
16865 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16867 MachineFunction *MF = MBB->getParent();
16868 MachineRegisterInfo &MRI = MF->getRegInfo();
16870 // Memory Reference
16871 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16872 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16874 MVT PVT = getPointerTy();
16875 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16876 "Invalid Pointer Size!");
16878 const TargetRegisterClass *RC =
16879 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16880 unsigned Tmp = MRI.createVirtualRegister(RC);
16881 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16882 const X86RegisterInfo *RegInfo =
16883 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16884 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16885 unsigned SP = RegInfo->getStackRegister();
16887 MachineInstrBuilder MIB;
16889 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16890 const int64_t SPOffset = 2 * PVT.getStoreSize();
16892 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16893 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16896 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16897 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16898 MIB.addOperand(MI->getOperand(i));
16899 MIB.setMemRefs(MMOBegin, MMOEnd);
16901 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16902 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16903 if (i == X86::AddrDisp)
16904 MIB.addDisp(MI->getOperand(i), LabelOffset);
16906 MIB.addOperand(MI->getOperand(i));
16908 MIB.setMemRefs(MMOBegin, MMOEnd);
16910 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16911 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16912 if (i == X86::AddrDisp)
16913 MIB.addDisp(MI->getOperand(i), SPOffset);
16915 MIB.addOperand(MI->getOperand(i));
16917 MIB.setMemRefs(MMOBegin, MMOEnd);
16919 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16921 MI->eraseFromParent();
16925 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16926 // accumulator loops. Writing back to the accumulator allows the coalescer
16927 // to remove extra copies in the loop.
16928 MachineBasicBlock *
16929 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16930 MachineBasicBlock *MBB) const {
16931 MachineOperand &AddendOp = MI->getOperand(3);
16933 // Bail out early if the addend isn't a register - we can't switch these.
16934 if (!AddendOp.isReg())
16937 MachineFunction &MF = *MBB->getParent();
16938 MachineRegisterInfo &MRI = MF.getRegInfo();
16940 // Check whether the addend is defined by a PHI:
16941 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16942 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16943 if (!AddendDef.isPHI())
16946 // Look for the following pattern:
16948 // %addend = phi [%entry, 0], [%loop, %result]
16950 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16954 // %addend = phi [%entry, 0], [%loop, %result]
16956 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16958 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16959 assert(AddendDef.getOperand(i).isReg());
16960 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16961 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16962 if (&PHISrcInst == MI) {
16963 // Found a matching instruction.
16964 unsigned NewFMAOpc = 0;
16965 switch (MI->getOpcode()) {
16966 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16967 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16968 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16969 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16970 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16971 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16972 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16973 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16974 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16975 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16976 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16977 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16978 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16979 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16980 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16981 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16982 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16983 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16984 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16985 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16986 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16987 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16988 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16989 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16990 default: llvm_unreachable("Unrecognized FMA variant.");
16993 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16994 MachineInstrBuilder MIB =
16995 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16996 .addOperand(MI->getOperand(0))
16997 .addOperand(MI->getOperand(3))
16998 .addOperand(MI->getOperand(2))
16999 .addOperand(MI->getOperand(1));
17000 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17001 MI->eraseFromParent();
17008 MachineBasicBlock *
17009 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17010 MachineBasicBlock *BB) const {
17011 switch (MI->getOpcode()) {
17012 default: llvm_unreachable("Unexpected instr type to insert");
17013 case X86::TAILJMPd64:
17014 case X86::TAILJMPr64:
17015 case X86::TAILJMPm64:
17016 llvm_unreachable("TAILJMP64 would not be touched here.");
17017 case X86::TCRETURNdi64:
17018 case X86::TCRETURNri64:
17019 case X86::TCRETURNmi64:
17021 case X86::WIN_ALLOCA:
17022 return EmitLoweredWinAlloca(MI, BB);
17023 case X86::SEG_ALLOCA_32:
17024 return EmitLoweredSegAlloca(MI, BB, false);
17025 case X86::SEG_ALLOCA_64:
17026 return EmitLoweredSegAlloca(MI, BB, true);
17027 case X86::TLSCall_32:
17028 case X86::TLSCall_64:
17029 return EmitLoweredTLSCall(MI, BB);
17030 case X86::CMOV_GR8:
17031 case X86::CMOV_FR32:
17032 case X86::CMOV_FR64:
17033 case X86::CMOV_V4F32:
17034 case X86::CMOV_V2F64:
17035 case X86::CMOV_V2I64:
17036 case X86::CMOV_V8F32:
17037 case X86::CMOV_V4F64:
17038 case X86::CMOV_V4I64:
17039 case X86::CMOV_V16F32:
17040 case X86::CMOV_V8F64:
17041 case X86::CMOV_V8I64:
17042 case X86::CMOV_GR16:
17043 case X86::CMOV_GR32:
17044 case X86::CMOV_RFP32:
17045 case X86::CMOV_RFP64:
17046 case X86::CMOV_RFP80:
17047 return EmitLoweredSelect(MI, BB);
17049 case X86::FP32_TO_INT16_IN_MEM:
17050 case X86::FP32_TO_INT32_IN_MEM:
17051 case X86::FP32_TO_INT64_IN_MEM:
17052 case X86::FP64_TO_INT16_IN_MEM:
17053 case X86::FP64_TO_INT32_IN_MEM:
17054 case X86::FP64_TO_INT64_IN_MEM:
17055 case X86::FP80_TO_INT16_IN_MEM:
17056 case X86::FP80_TO_INT32_IN_MEM:
17057 case X86::FP80_TO_INT64_IN_MEM: {
17058 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17059 DebugLoc DL = MI->getDebugLoc();
17061 // Change the floating point control register to use "round towards zero"
17062 // mode when truncating to an integer value.
17063 MachineFunction *F = BB->getParent();
17064 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17065 addFrameReference(BuildMI(*BB, MI, DL,
17066 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17068 // Load the old value of the high byte of the control word...
17070 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17071 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17074 // Set the high part to be round to zero...
17075 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17078 // Reload the modified control word now...
17079 addFrameReference(BuildMI(*BB, MI, DL,
17080 TII->get(X86::FLDCW16m)), CWFrameIdx);
17082 // Restore the memory image of control word to original value
17083 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17086 // Get the X86 opcode to use.
17088 switch (MI->getOpcode()) {
17089 default: llvm_unreachable("illegal opcode!");
17090 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17091 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17092 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17093 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17094 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17095 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17096 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17097 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17098 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17102 MachineOperand &Op = MI->getOperand(0);
17104 AM.BaseType = X86AddressMode::RegBase;
17105 AM.Base.Reg = Op.getReg();
17107 AM.BaseType = X86AddressMode::FrameIndexBase;
17108 AM.Base.FrameIndex = Op.getIndex();
17110 Op = MI->getOperand(1);
17112 AM.Scale = Op.getImm();
17113 Op = MI->getOperand(2);
17115 AM.IndexReg = Op.getImm();
17116 Op = MI->getOperand(3);
17117 if (Op.isGlobal()) {
17118 AM.GV = Op.getGlobal();
17120 AM.Disp = Op.getImm();
17122 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17123 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17125 // Reload the original control word now.
17126 addFrameReference(BuildMI(*BB, MI, DL,
17127 TII->get(X86::FLDCW16m)), CWFrameIdx);
17129 MI->eraseFromParent(); // The pseudo instruction is gone now.
17132 // String/text processing lowering.
17133 case X86::PCMPISTRM128REG:
17134 case X86::VPCMPISTRM128REG:
17135 case X86::PCMPISTRM128MEM:
17136 case X86::VPCMPISTRM128MEM:
17137 case X86::PCMPESTRM128REG:
17138 case X86::VPCMPESTRM128REG:
17139 case X86::PCMPESTRM128MEM:
17140 case X86::VPCMPESTRM128MEM:
17141 assert(Subtarget->hasSSE42() &&
17142 "Target must have SSE4.2 or AVX features enabled");
17143 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17145 // String/text processing lowering.
17146 case X86::PCMPISTRIREG:
17147 case X86::VPCMPISTRIREG:
17148 case X86::PCMPISTRIMEM:
17149 case X86::VPCMPISTRIMEM:
17150 case X86::PCMPESTRIREG:
17151 case X86::VPCMPESTRIREG:
17152 case X86::PCMPESTRIMEM:
17153 case X86::VPCMPESTRIMEM:
17154 assert(Subtarget->hasSSE42() &&
17155 "Target must have SSE4.2 or AVX features enabled");
17156 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17158 // Thread synchronization.
17160 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17164 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17166 // Atomic Lowering.
17167 case X86::ATOMAND8:
17168 case X86::ATOMAND16:
17169 case X86::ATOMAND32:
17170 case X86::ATOMAND64:
17173 case X86::ATOMOR16:
17174 case X86::ATOMOR32:
17175 case X86::ATOMOR64:
17177 case X86::ATOMXOR16:
17178 case X86::ATOMXOR8:
17179 case X86::ATOMXOR32:
17180 case X86::ATOMXOR64:
17182 case X86::ATOMNAND8:
17183 case X86::ATOMNAND16:
17184 case X86::ATOMNAND32:
17185 case X86::ATOMNAND64:
17187 case X86::ATOMMAX8:
17188 case X86::ATOMMAX16:
17189 case X86::ATOMMAX32:
17190 case X86::ATOMMAX64:
17192 case X86::ATOMMIN8:
17193 case X86::ATOMMIN16:
17194 case X86::ATOMMIN32:
17195 case X86::ATOMMIN64:
17197 case X86::ATOMUMAX8:
17198 case X86::ATOMUMAX16:
17199 case X86::ATOMUMAX32:
17200 case X86::ATOMUMAX64:
17202 case X86::ATOMUMIN8:
17203 case X86::ATOMUMIN16:
17204 case X86::ATOMUMIN32:
17205 case X86::ATOMUMIN64:
17206 return EmitAtomicLoadArith(MI, BB);
17208 // This group does 64-bit operations on a 32-bit host.
17209 case X86::ATOMAND6432:
17210 case X86::ATOMOR6432:
17211 case X86::ATOMXOR6432:
17212 case X86::ATOMNAND6432:
17213 case X86::ATOMADD6432:
17214 case X86::ATOMSUB6432:
17215 case X86::ATOMMAX6432:
17216 case X86::ATOMMIN6432:
17217 case X86::ATOMUMAX6432:
17218 case X86::ATOMUMIN6432:
17219 case X86::ATOMSWAP6432:
17220 return EmitAtomicLoadArith6432(MI, BB);
17222 case X86::VASTART_SAVE_XMM_REGS:
17223 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17225 case X86::VAARG_64:
17226 return EmitVAARG64WithCustomInserter(MI, BB);
17228 case X86::EH_SjLj_SetJmp32:
17229 case X86::EH_SjLj_SetJmp64:
17230 return emitEHSjLjSetJmp(MI, BB);
17232 case X86::EH_SjLj_LongJmp32:
17233 case X86::EH_SjLj_LongJmp64:
17234 return emitEHSjLjLongJmp(MI, BB);
17236 case TargetOpcode::STACKMAP:
17237 case TargetOpcode::PATCHPOINT:
17238 return emitPatchPoint(MI, BB);
17240 case X86::VFMADDPDr213r:
17241 case X86::VFMADDPSr213r:
17242 case X86::VFMADDSDr213r:
17243 case X86::VFMADDSSr213r:
17244 case X86::VFMSUBPDr213r:
17245 case X86::VFMSUBPSr213r:
17246 case X86::VFMSUBSDr213r:
17247 case X86::VFMSUBSSr213r:
17248 case X86::VFNMADDPDr213r:
17249 case X86::VFNMADDPSr213r:
17250 case X86::VFNMADDSDr213r:
17251 case X86::VFNMADDSSr213r:
17252 case X86::VFNMSUBPDr213r:
17253 case X86::VFNMSUBPSr213r:
17254 case X86::VFNMSUBSDr213r:
17255 case X86::VFNMSUBSSr213r:
17256 case X86::VFMADDPDr213rY:
17257 case X86::VFMADDPSr213rY:
17258 case X86::VFMSUBPDr213rY:
17259 case X86::VFMSUBPSr213rY:
17260 case X86::VFNMADDPDr213rY:
17261 case X86::VFNMADDPSr213rY:
17262 case X86::VFNMSUBPDr213rY:
17263 case X86::VFNMSUBPSr213rY:
17264 return emitFMA3Instr(MI, BB);
17268 //===----------------------------------------------------------------------===//
17269 // X86 Optimization Hooks
17270 //===----------------------------------------------------------------------===//
17272 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17275 const SelectionDAG &DAG,
17276 unsigned Depth) const {
17277 unsigned BitWidth = KnownZero.getBitWidth();
17278 unsigned Opc = Op.getOpcode();
17279 assert((Opc >= ISD::BUILTIN_OP_END ||
17280 Opc == ISD::INTRINSIC_WO_CHAIN ||
17281 Opc == ISD::INTRINSIC_W_CHAIN ||
17282 Opc == ISD::INTRINSIC_VOID) &&
17283 "Should use MaskedValueIsZero if you don't know whether Op"
17284 " is a target node!");
17286 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
17300 // These nodes' second result is a boolean.
17301 if (Op.getResNo() == 0)
17304 case X86ISD::SETCC:
17305 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17307 case ISD::INTRINSIC_WO_CHAIN: {
17308 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17309 unsigned NumLoBits = 0;
17312 case Intrinsic::x86_sse_movmsk_ps:
17313 case Intrinsic::x86_avx_movmsk_ps_256:
17314 case Intrinsic::x86_sse2_movmsk_pd:
17315 case Intrinsic::x86_avx_movmsk_pd_256:
17316 case Intrinsic::x86_mmx_pmovmskb:
17317 case Intrinsic::x86_sse2_pmovmskb_128:
17318 case Intrinsic::x86_avx2_pmovmskb: {
17319 // High bits of movmskp{s|d}, pmovmskb are known zero.
17321 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17322 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
17323 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
17324 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
17325 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
17326 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
17327 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
17328 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
17330 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17339 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17341 const SelectionDAG &,
17342 unsigned Depth) const {
17343 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17344 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17345 return Op.getValueType().getScalarType().getSizeInBits();
17351 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17352 /// node is a GlobalAddress + offset.
17353 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17354 const GlobalValue* &GA,
17355 int64_t &Offset) const {
17356 if (N->getOpcode() == X86ISD::Wrapper) {
17357 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17358 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17359 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17363 return TargetLowering::isGAPlusOffset(N, GA, Offset);
17366 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17367 /// same as extracting the high 128-bit part of 256-bit vector and then
17368 /// inserting the result into the low part of a new 256-bit vector
17369 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17370 EVT VT = SVOp->getValueType(0);
17371 unsigned NumElems = VT.getVectorNumElements();
17373 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17374 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17375 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17376 SVOp->getMaskElt(j) >= 0)
17382 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17383 /// same as extracting the low 128-bit part of 256-bit vector and then
17384 /// inserting the result into the high part of a new 256-bit vector
17385 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17386 EVT VT = SVOp->getValueType(0);
17387 unsigned NumElems = VT.getVectorNumElements();
17389 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17390 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17391 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17392 SVOp->getMaskElt(j) >= 0)
17398 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17399 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17400 TargetLowering::DAGCombinerInfo &DCI,
17401 const X86Subtarget* Subtarget) {
17403 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17404 SDValue V1 = SVOp->getOperand(0);
17405 SDValue V2 = SVOp->getOperand(1);
17406 EVT VT = SVOp->getValueType(0);
17407 unsigned NumElems = VT.getVectorNumElements();
17409 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17410 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17414 // V UNDEF BUILD_VECTOR UNDEF
17416 // CONCAT_VECTOR CONCAT_VECTOR
17419 // RESULT: V + zero extended
17421 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17422 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17423 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17426 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17429 // To match the shuffle mask, the first half of the mask should
17430 // be exactly the first vector, and all the rest a splat with the
17431 // first element of the second one.
17432 for (unsigned i = 0; i != NumElems/2; ++i)
17433 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17434 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17437 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17438 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17439 if (Ld->hasNUsesOfValue(1, 0)) {
17440 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17441 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17443 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17445 Ld->getPointerInfo(),
17446 Ld->getAlignment(),
17447 false/*isVolatile*/, true/*ReadMem*/,
17448 false/*WriteMem*/);
17450 // Make sure the newly-created LOAD is in the same position as Ld in
17451 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17452 // and update uses of Ld's output chain to use the TokenFactor.
17453 if (Ld->hasAnyUseOfValue(1)) {
17454 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17455 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17456 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17457 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17458 SDValue(ResNode.getNode(), 1));
17461 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17465 // Emit a zeroed vector and insert the desired subvector on its
17467 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17468 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17469 return DCI.CombineTo(N, InsV);
17472 //===--------------------------------------------------------------------===//
17473 // Combine some shuffles into subvector extracts and inserts:
17476 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17477 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17478 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17479 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17480 return DCI.CombineTo(N, InsV);
17483 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17484 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17485 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17486 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17487 return DCI.CombineTo(N, InsV);
17493 /// PerformShuffleCombine - Performs several different shuffle combines.
17494 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17495 TargetLowering::DAGCombinerInfo &DCI,
17496 const X86Subtarget *Subtarget) {
17498 SDValue N0 = N->getOperand(0);
17499 SDValue N1 = N->getOperand(1);
17500 EVT VT = N->getValueType(0);
17502 // Don't create instructions with illegal types after legalize types has run.
17503 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17504 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17507 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17508 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17509 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17510 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17512 // During Type Legalization, when promoting illegal vector types,
17513 // the backend might introduce new shuffle dag nodes and bitcasts.
17515 // This code performs the following transformation:
17516 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17517 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17519 // We do this only if both the bitcast and the BINOP dag nodes have
17520 // one use. Also, perform this transformation only if the new binary
17521 // operation is legal. This is to avoid introducing dag nodes that
17522 // potentially need to be further expanded (or custom lowered) into a
17523 // less optimal sequence of dag nodes.
17524 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17525 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17526 N0.getOpcode() == ISD::BITCAST) {
17527 SDValue BC0 = N0.getOperand(0);
17528 EVT SVT = BC0.getValueType();
17529 unsigned Opcode = BC0.getOpcode();
17530 unsigned NumElts = VT.getVectorNumElements();
17532 if (BC0.hasOneUse() && SVT.isVector() &&
17533 SVT.getVectorNumElements() * 2 == NumElts &&
17534 TLI.isOperationLegal(Opcode, VT)) {
17535 bool CanFold = false;
17547 unsigned SVTNumElts = SVT.getVectorNumElements();
17548 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17549 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17550 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17551 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17552 CanFold = SVOp->getMaskElt(i) < 0;
17555 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17556 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17557 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17558 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17563 // Only handle 128 wide vector from here on.
17564 if (!VT.is128BitVector())
17567 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17568 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17569 // consecutive, non-overlapping, and in the right order.
17570 SmallVector<SDValue, 16> Elts;
17571 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17572 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17574 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17577 /// PerformTruncateCombine - Converts truncate operation to
17578 /// a sequence of vector shuffle operations.
17579 /// It is possible when we truncate 256-bit vector to 128-bit vector
17580 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17581 TargetLowering::DAGCombinerInfo &DCI,
17582 const X86Subtarget *Subtarget) {
17586 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17587 /// specific shuffle of a load can be folded into a single element load.
17588 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17589 /// shuffles have been customed lowered so we need to handle those here.
17590 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17591 TargetLowering::DAGCombinerInfo &DCI) {
17592 if (DCI.isBeforeLegalizeOps())
17595 SDValue InVec = N->getOperand(0);
17596 SDValue EltNo = N->getOperand(1);
17598 if (!isa<ConstantSDNode>(EltNo))
17601 EVT VT = InVec.getValueType();
17603 bool HasShuffleIntoBitcast = false;
17604 if (InVec.getOpcode() == ISD::BITCAST) {
17605 // Don't duplicate a load with other uses.
17606 if (!InVec.hasOneUse())
17608 EVT BCVT = InVec.getOperand(0).getValueType();
17609 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17611 InVec = InVec.getOperand(0);
17612 HasShuffleIntoBitcast = true;
17615 if (!isTargetShuffle(InVec.getOpcode()))
17618 // Don't duplicate a load with other uses.
17619 if (!InVec.hasOneUse())
17622 SmallVector<int, 16> ShuffleMask;
17624 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17628 // Select the input vector, guarding against out of range extract vector.
17629 unsigned NumElems = VT.getVectorNumElements();
17630 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17631 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17632 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17633 : InVec.getOperand(1);
17635 // If inputs to shuffle are the same for both ops, then allow 2 uses
17636 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17638 if (LdNode.getOpcode() == ISD::BITCAST) {
17639 // Don't duplicate a load with other uses.
17640 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17643 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17644 LdNode = LdNode.getOperand(0);
17647 if (!ISD::isNormalLoad(LdNode.getNode()))
17650 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17652 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17655 if (HasShuffleIntoBitcast) {
17656 // If there's a bitcast before the shuffle, check if the load type and
17657 // alignment is valid.
17658 unsigned Align = LN0->getAlignment();
17659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17660 unsigned NewAlign = TLI.getDataLayout()->
17661 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17663 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17667 // All checks match so transform back to vector_shuffle so that DAG combiner
17668 // can finish the job
17671 // Create shuffle node taking into account the case that its a unary shuffle
17672 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17673 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17674 InVec.getOperand(0), Shuffle,
17676 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17677 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17681 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17682 /// generation and convert it from being a bunch of shuffles and extracts
17683 /// to a simple store and scalar loads to extract the elements.
17684 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17685 TargetLowering::DAGCombinerInfo &DCI) {
17686 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17687 if (NewOp.getNode())
17690 SDValue InputVector = N->getOperand(0);
17692 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17693 // from mmx to v2i32 has a single usage.
17694 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17695 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17696 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17697 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17698 N->getValueType(0),
17699 InputVector.getNode()->getOperand(0));
17701 // Only operate on vectors of 4 elements, where the alternative shuffling
17702 // gets to be more expensive.
17703 if (InputVector.getValueType() != MVT::v4i32)
17706 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17707 // single use which is a sign-extend or zero-extend, and all elements are
17709 SmallVector<SDNode *, 4> Uses;
17710 unsigned ExtractedElements = 0;
17711 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17712 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17713 if (UI.getUse().getResNo() != InputVector.getResNo())
17716 SDNode *Extract = *UI;
17717 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17720 if (Extract->getValueType(0) != MVT::i32)
17722 if (!Extract->hasOneUse())
17724 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17725 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17727 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17730 // Record which element was extracted.
17731 ExtractedElements |=
17732 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17734 Uses.push_back(Extract);
17737 // If not all the elements were used, this may not be worthwhile.
17738 if (ExtractedElements != 15)
17741 // Ok, we've now decided to do the transformation.
17742 SDLoc dl(InputVector);
17744 // Store the value to a temporary stack slot.
17745 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17746 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17747 MachinePointerInfo(), false, false, 0);
17749 // Replace each use (extract) with a load of the appropriate element.
17750 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17751 UE = Uses.end(); UI != UE; ++UI) {
17752 SDNode *Extract = *UI;
17754 // cOMpute the element's address.
17755 SDValue Idx = Extract->getOperand(1);
17757 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17758 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17759 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17760 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17762 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17763 StackPtr, OffsetVal);
17765 // Load the scalar.
17766 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17767 ScalarAddr, MachinePointerInfo(),
17768 false, false, false, 0);
17770 // Replace the exact with the load.
17771 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17774 // The replacement was made in place; don't return anything.
17778 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17779 static std::pair<unsigned, bool>
17780 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17781 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17782 if (!VT.isVector())
17783 return std::make_pair(0, false);
17785 bool NeedSplit = false;
17786 switch (VT.getSimpleVT().SimpleTy) {
17787 default: return std::make_pair(0, false);
17791 if (!Subtarget->hasAVX2())
17793 if (!Subtarget->hasAVX())
17794 return std::make_pair(0, false);
17799 if (!Subtarget->hasSSE2())
17800 return std::make_pair(0, false);
17803 // SSE2 has only a small subset of the operations.
17804 bool hasUnsigned = Subtarget->hasSSE41() ||
17805 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17806 bool hasSigned = Subtarget->hasSSE41() ||
17807 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17809 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17812 // Check for x CC y ? x : y.
17813 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17814 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17819 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17822 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17825 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17828 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17830 // Check for x CC y ? y : x -- a min/max with reversed arms.
17831 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17832 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17837 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17840 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17843 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17846 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17850 return std::make_pair(Opc, NeedSplit);
17854 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17855 const X86Subtarget *Subtarget) {
17857 SDValue Cond = N->getOperand(0);
17858 SDValue LHS = N->getOperand(1);
17859 SDValue RHS = N->getOperand(2);
17861 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17862 SDValue CondSrc = Cond->getOperand(0);
17863 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17864 Cond = CondSrc->getOperand(0);
17867 MVT VT = N->getSimpleValueType(0);
17868 MVT EltVT = VT.getVectorElementType();
17869 unsigned NumElems = VT.getVectorNumElements();
17870 // There is no blend with immediate in AVX-512.
17871 if (VT.is512BitVector())
17874 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17876 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17879 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17882 unsigned MaskValue = 0;
17883 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
17886 SmallVector<int, 8> ShuffleMask(NumElems, -1);
17887 for (unsigned i = 0; i < NumElems; ++i) {
17888 // Be sure we emit undef where we can.
17889 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
17890 ShuffleMask[i] = -1;
17892 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
17895 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
17898 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17900 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17901 TargetLowering::DAGCombinerInfo &DCI,
17902 const X86Subtarget *Subtarget) {
17904 SDValue Cond = N->getOperand(0);
17905 // Get the LHS/RHS of the select.
17906 SDValue LHS = N->getOperand(1);
17907 SDValue RHS = N->getOperand(2);
17908 EVT VT = LHS.getValueType();
17909 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17911 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17912 // instructions match the semantics of the common C idiom x<y?x:y but not
17913 // x<=y?x:y, because of how they handle negative zero (which can be
17914 // ignored in unsafe-math mode).
17915 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17916 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17917 (Subtarget->hasSSE2() ||
17918 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17919 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17921 unsigned Opcode = 0;
17922 // Check for x CC y ? x : y.
17923 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17924 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17928 // Converting this to a min would handle NaNs incorrectly, and swapping
17929 // the operands would cause it to handle comparisons between positive
17930 // and negative zero incorrectly.
17931 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17932 if (!DAG.getTarget().Options.UnsafeFPMath &&
17933 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17935 std::swap(LHS, RHS);
17937 Opcode = X86ISD::FMIN;
17940 // Converting this to a min would handle comparisons between positive
17941 // and negative zero incorrectly.
17942 if (!DAG.getTarget().Options.UnsafeFPMath &&
17943 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17945 Opcode = X86ISD::FMIN;
17948 // Converting this to a min would handle both negative zeros and NaNs
17949 // incorrectly, but we can swap the operands to fix both.
17950 std::swap(LHS, RHS);
17954 Opcode = X86ISD::FMIN;
17958 // Converting this to a max would handle comparisons between positive
17959 // and negative zero incorrectly.
17960 if (!DAG.getTarget().Options.UnsafeFPMath &&
17961 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17963 Opcode = X86ISD::FMAX;
17966 // Converting this to a max would handle NaNs incorrectly, and swapping
17967 // the operands would cause it to handle comparisons between positive
17968 // and negative zero incorrectly.
17969 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17970 if (!DAG.getTarget().Options.UnsafeFPMath &&
17971 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17973 std::swap(LHS, RHS);
17975 Opcode = X86ISD::FMAX;
17978 // Converting this to a max would handle both negative zeros and NaNs
17979 // incorrectly, but we can swap the operands to fix both.
17980 std::swap(LHS, RHS);
17984 Opcode = X86ISD::FMAX;
17987 // Check for x CC y ? y : x -- a min/max with reversed arms.
17988 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17989 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17993 // Converting this to a min would handle comparisons between positive
17994 // and negative zero incorrectly, and swapping the operands would
17995 // cause it to handle NaNs incorrectly.
17996 if (!DAG.getTarget().Options.UnsafeFPMath &&
17997 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17998 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18000 std::swap(LHS, RHS);
18002 Opcode = X86ISD::FMIN;
18005 // Converting this to a min would handle NaNs incorrectly.
18006 if (!DAG.getTarget().Options.UnsafeFPMath &&
18007 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18009 Opcode = X86ISD::FMIN;
18012 // Converting this to a min would handle both negative zeros and NaNs
18013 // incorrectly, but we can swap the operands to fix both.
18014 std::swap(LHS, RHS);
18018 Opcode = X86ISD::FMIN;
18022 // Converting this to a max would handle NaNs incorrectly.
18023 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18025 Opcode = X86ISD::FMAX;
18028 // Converting this to a max would handle comparisons between positive
18029 // and negative zero incorrectly, and swapping the operands would
18030 // cause it to handle NaNs incorrectly.
18031 if (!DAG.getTarget().Options.UnsafeFPMath &&
18032 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18033 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18035 std::swap(LHS, RHS);
18037 Opcode = X86ISD::FMAX;
18040 // Converting this to a max would handle both negative zeros and NaNs
18041 // incorrectly, but we can swap the operands to fix both.
18042 std::swap(LHS, RHS);
18046 Opcode = X86ISD::FMAX;
18052 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18055 EVT CondVT = Cond.getValueType();
18056 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18057 CondVT.getVectorElementType() == MVT::i1) {
18058 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18059 // lowering on AVX-512. In this case we convert it to
18060 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18061 // The same situation for all 128 and 256-bit vectors of i8 and i16
18062 EVT OpVT = LHS.getValueType();
18063 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18064 (OpVT.getVectorElementType() == MVT::i8 ||
18065 OpVT.getVectorElementType() == MVT::i16)) {
18066 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18067 DCI.AddToWorklist(Cond.getNode());
18068 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18071 // If this is a select between two integer constants, try to do some
18073 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18074 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18075 // Don't do this for crazy integer types.
18076 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18077 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18078 // so that TrueC (the true value) is larger than FalseC.
18079 bool NeedsCondInvert = false;
18081 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18082 // Efficiently invertible.
18083 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
18084 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
18085 isa<ConstantSDNode>(Cond.getOperand(1))))) {
18086 NeedsCondInvert = true;
18087 std::swap(TrueC, FalseC);
18090 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
18091 if (FalseC->getAPIntValue() == 0 &&
18092 TrueC->getAPIntValue().isPowerOf2()) {
18093 if (NeedsCondInvert) // Invert the condition if needed.
18094 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18095 DAG.getConstant(1, Cond.getValueType()));
18097 // Zero extend the condition if needed.
18098 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18100 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18101 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18102 DAG.getConstant(ShAmt, MVT::i8));
18105 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18106 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18107 if (NeedsCondInvert) // Invert the condition if needed.
18108 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18109 DAG.getConstant(1, Cond.getValueType()));
18111 // Zero extend the condition if needed.
18112 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18113 FalseC->getValueType(0), Cond);
18114 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18115 SDValue(FalseC, 0));
18118 // Optimize cases that will turn into an LEA instruction. This requires
18119 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18120 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18121 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18122 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18124 bool isFastMultiplier = false;
18126 switch ((unsigned char)Diff) {
18128 case 1: // result = add base, cond
18129 case 2: // result = lea base( , cond*2)
18130 case 3: // result = lea base(cond, cond*2)
18131 case 4: // result = lea base( , cond*4)
18132 case 5: // result = lea base(cond, cond*4)
18133 case 8: // result = lea base( , cond*8)
18134 case 9: // result = lea base(cond, cond*8)
18135 isFastMultiplier = true;
18140 if (isFastMultiplier) {
18141 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18142 if (NeedsCondInvert) // Invert the condition if needed.
18143 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18144 DAG.getConstant(1, Cond.getValueType()));
18146 // Zero extend the condition if needed.
18147 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18149 // Scale the condition by the difference.
18151 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18152 DAG.getConstant(Diff, Cond.getValueType()));
18154 // Add the base if non-zero.
18155 if (FalseC->getAPIntValue() != 0)
18156 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18157 SDValue(FalseC, 0));
18164 // Canonicalize max and min:
18165 // (x > y) ? x : y -> (x >= y) ? x : y
18166 // (x < y) ? x : y -> (x <= y) ? x : y
18167 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18168 // the need for an extra compare
18169 // against zero. e.g.
18170 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18172 // testl %edi, %edi
18174 // cmovgl %edi, %eax
18178 // cmovsl %eax, %edi
18179 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18180 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18181 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18182 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18187 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18188 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18189 Cond.getOperand(0), Cond.getOperand(1), NewCC);
18190 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18195 // Early exit check
18196 if (!TLI.isTypeLegal(VT))
18199 // Match VSELECTs into subs with unsigned saturation.
18200 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18201 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18202 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18203 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18204 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18206 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18207 // left side invert the predicate to simplify logic below.
18209 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18211 CC = ISD::getSetCCInverse(CC, true);
18212 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18216 if (Other.getNode() && Other->getNumOperands() == 2 &&
18217 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18218 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18219 SDValue CondRHS = Cond->getOperand(1);
18221 // Look for a general sub with unsigned saturation first.
18222 // x >= y ? x-y : 0 --> subus x, y
18223 // x > y ? x-y : 0 --> subus x, y
18224 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18225 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18226 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18228 // If the RHS is a constant we have to reverse the const canonicalization.
18229 // x > C-1 ? x+-C : 0 --> subus x, C
18230 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18231 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18232 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18233 if (CondRHS.getConstantOperandVal(0) == -A-1)
18234 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18235 DAG.getConstant(-A, VT));
18238 // Another special case: If C was a sign bit, the sub has been
18239 // canonicalized into a xor.
18240 // FIXME: Would it be better to use computeKnownBits to determine whether
18241 // it's safe to decanonicalize the xor?
18242 // x s< 0 ? x^C : 0 --> subus x, C
18243 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18244 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18245 isSplatVector(OpRHS.getNode())) {
18246 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18248 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18253 // Try to match a min/max vector operation.
18254 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18255 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18256 unsigned Opc = ret.first;
18257 bool NeedSplit = ret.second;
18259 if (Opc && NeedSplit) {
18260 unsigned NumElems = VT.getVectorNumElements();
18261 // Extract the LHS vectors
18262 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18263 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18265 // Extract the RHS vectors
18266 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18267 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18269 // Create min/max for each subvector
18270 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18271 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18273 // Merge the result
18274 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18276 return DAG.getNode(Opc, DL, VT, LHS, RHS);
18279 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18280 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18281 // Check if SETCC has already been promoted
18282 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18283 // Check that condition value type matches vselect operand type
18286 assert(Cond.getValueType().isVector() &&
18287 "vector select expects a vector selector!");
18289 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18290 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18292 if (!TValIsAllOnes && !FValIsAllZeros) {
18293 // Try invert the condition if true value is not all 1s and false value
18295 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18296 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18298 if (TValIsAllZeros || FValIsAllOnes) {
18299 SDValue CC = Cond.getOperand(2);
18300 ISD::CondCode NewCC =
18301 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18302 Cond.getOperand(0).getValueType().isInteger());
18303 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18304 std::swap(LHS, RHS);
18305 TValIsAllOnes = FValIsAllOnes;
18306 FValIsAllZeros = TValIsAllZeros;
18310 if (TValIsAllOnes || FValIsAllZeros) {
18313 if (TValIsAllOnes && FValIsAllZeros)
18315 else if (TValIsAllOnes)
18316 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18317 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18318 else if (FValIsAllZeros)
18319 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18320 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18322 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18326 // Try to fold this VSELECT into a MOVSS/MOVSD
18327 if (N->getOpcode() == ISD::VSELECT &&
18328 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18329 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18330 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18331 bool CanFold = false;
18332 unsigned NumElems = Cond.getNumOperands();
18336 if (isZero(Cond.getOperand(0))) {
18339 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18340 // fold (vselect <0,-1> -> (movsd A, B)
18341 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18342 CanFold = isAllOnes(Cond.getOperand(i));
18343 } else if (isAllOnes(Cond.getOperand(0))) {
18347 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18348 // fold (vselect <-1,0> -> (movsd B, A)
18349 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18350 CanFold = isZero(Cond.getOperand(i));
18354 if (VT == MVT::v4i32 || VT == MVT::v4f32)
18355 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18356 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18359 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18360 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18361 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18362 // (v2i64 (bitcast B)))))
18364 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18365 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18366 // (v2f64 (bitcast B)))))
18368 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18369 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18370 // (v2i64 (bitcast A)))))
18372 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18373 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18374 // (v2f64 (bitcast A)))))
18376 CanFold = (isZero(Cond.getOperand(0)) &&
18377 isZero(Cond.getOperand(1)) &&
18378 isAllOnes(Cond.getOperand(2)) &&
18379 isAllOnes(Cond.getOperand(3)));
18381 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18382 isAllOnes(Cond.getOperand(1)) &&
18383 isZero(Cond.getOperand(2)) &&
18384 isZero(Cond.getOperand(3))) {
18386 std::swap(LHS, RHS);
18390 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18391 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18392 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18393 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18395 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18401 // If we know that this node is legal then we know that it is going to be
18402 // matched by one of the SSE/AVX BLEND instructions. These instructions only
18403 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18404 // to simplify previous instructions.
18405 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18406 !DCI.isBeforeLegalize() &&
18407 // We explicitly check against v8i16 and v16i16 because, although
18408 // they're marked as Custom, they might only be legal when Cond is a
18409 // build_vector of constants. This will be taken care in a later
18411 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18412 VT != MVT::v8i16)) {
18413 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18415 // Don't optimize vector selects that map to mask-registers.
18419 // Check all uses of that condition operand to check whether it will be
18420 // consumed by non-BLEND instructions, which may depend on all bits are set
18422 for (SDNode::use_iterator I = Cond->use_begin(),
18423 E = Cond->use_end(); I != E; ++I)
18424 if (I->getOpcode() != ISD::VSELECT)
18425 // TODO: Add other opcodes eventually lowered into BLEND.
18428 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18429 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18431 APInt KnownZero, KnownOne;
18432 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18433 DCI.isBeforeLegalizeOps());
18434 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18435 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18436 DCI.CommitTargetLoweringOpt(TLO);
18439 // We should generate an X86ISD::BLENDI from a vselect if its argument
18440 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18441 // constants. This specific pattern gets generated when we split a
18442 // selector for a 512 bit vector in a machine without AVX512 (but with
18443 // 256-bit vectors), during legalization:
18445 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18447 // Iff we find this pattern and the build_vectors are built from
18448 // constants, we translate the vselect into a shuffle_vector that we
18449 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18450 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18451 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18452 if (Shuffle.getNode())
18459 // Check whether a boolean test is testing a boolean value generated by
18460 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18463 // Simplify the following patterns:
18464 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18465 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18466 // to (Op EFLAGS Cond)
18468 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18469 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18470 // to (Op EFLAGS !Cond)
18472 // where Op could be BRCOND or CMOV.
18474 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18475 // Quit if not CMP and SUB with its value result used.
18476 if (Cmp.getOpcode() != X86ISD::CMP &&
18477 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18480 // Quit if not used as a boolean value.
18481 if (CC != X86::COND_E && CC != X86::COND_NE)
18484 // Check CMP operands. One of them should be 0 or 1 and the other should be
18485 // an SetCC or extended from it.
18486 SDValue Op1 = Cmp.getOperand(0);
18487 SDValue Op2 = Cmp.getOperand(1);
18490 const ConstantSDNode* C = nullptr;
18491 bool needOppositeCond = (CC == X86::COND_E);
18492 bool checkAgainstTrue = false; // Is it a comparison against 1?
18494 if ((C = dyn_cast<ConstantSDNode>(Op1)))
18496 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18498 else // Quit if all operands are not constants.
18501 if (C->getZExtValue() == 1) {
18502 needOppositeCond = !needOppositeCond;
18503 checkAgainstTrue = true;
18504 } else if (C->getZExtValue() != 0)
18505 // Quit if the constant is neither 0 or 1.
18508 bool truncatedToBoolWithAnd = false;
18509 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18510 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18511 SetCC.getOpcode() == ISD::TRUNCATE ||
18512 SetCC.getOpcode() == ISD::AND) {
18513 if (SetCC.getOpcode() == ISD::AND) {
18515 ConstantSDNode *CS;
18516 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18517 CS->getZExtValue() == 1)
18519 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18520 CS->getZExtValue() == 1)
18524 SetCC = SetCC.getOperand(OpIdx);
18525 truncatedToBoolWithAnd = true;
18527 SetCC = SetCC.getOperand(0);
18530 switch (SetCC.getOpcode()) {
18531 case X86ISD::SETCC_CARRY:
18532 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18533 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18534 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18535 // truncated to i1 using 'and'.
18536 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18538 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18539 "Invalid use of SETCC_CARRY!");
18541 case X86ISD::SETCC:
18542 // Set the condition code or opposite one if necessary.
18543 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18544 if (needOppositeCond)
18545 CC = X86::GetOppositeBranchCondition(CC);
18546 return SetCC.getOperand(1);
18547 case X86ISD::CMOV: {
18548 // Check whether false/true value has canonical one, i.e. 0 or 1.
18549 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18550 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18551 // Quit if true value is not a constant.
18554 // Quit if false value is not a constant.
18556 SDValue Op = SetCC.getOperand(0);
18557 // Skip 'zext' or 'trunc' node.
18558 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18559 Op.getOpcode() == ISD::TRUNCATE)
18560 Op = Op.getOperand(0);
18561 // A special case for rdrand/rdseed, where 0 is set if false cond is
18563 if ((Op.getOpcode() != X86ISD::RDRAND &&
18564 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18567 // Quit if false value is not the constant 0 or 1.
18568 bool FValIsFalse = true;
18569 if (FVal && FVal->getZExtValue() != 0) {
18570 if (FVal->getZExtValue() != 1)
18572 // If FVal is 1, opposite cond is needed.
18573 needOppositeCond = !needOppositeCond;
18574 FValIsFalse = false;
18576 // Quit if TVal is not the constant opposite of FVal.
18577 if (FValIsFalse && TVal->getZExtValue() != 1)
18579 if (!FValIsFalse && TVal->getZExtValue() != 0)
18581 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18582 if (needOppositeCond)
18583 CC = X86::GetOppositeBranchCondition(CC);
18584 return SetCC.getOperand(3);
18591 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18592 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18593 TargetLowering::DAGCombinerInfo &DCI,
18594 const X86Subtarget *Subtarget) {
18597 // If the flag operand isn't dead, don't touch this CMOV.
18598 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18601 SDValue FalseOp = N->getOperand(0);
18602 SDValue TrueOp = N->getOperand(1);
18603 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18604 SDValue Cond = N->getOperand(3);
18606 if (CC == X86::COND_E || CC == X86::COND_NE) {
18607 switch (Cond.getOpcode()) {
18611 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18612 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18613 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18619 Flags = checkBoolTestSetCCCombine(Cond, CC);
18620 if (Flags.getNode() &&
18621 // Extra check as FCMOV only supports a subset of X86 cond.
18622 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18623 SDValue Ops[] = { FalseOp, TrueOp,
18624 DAG.getConstant(CC, MVT::i8), Flags };
18625 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18628 // If this is a select between two integer constants, try to do some
18629 // optimizations. Note that the operands are ordered the opposite of SELECT
18631 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18632 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18633 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18634 // larger than FalseC (the false value).
18635 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18636 CC = X86::GetOppositeBranchCondition(CC);
18637 std::swap(TrueC, FalseC);
18638 std::swap(TrueOp, FalseOp);
18641 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18642 // This is efficient for any integer data type (including i8/i16) and
18644 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18645 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18646 DAG.getConstant(CC, MVT::i8), Cond);
18648 // Zero extend the condition if needed.
18649 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18651 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18652 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18653 DAG.getConstant(ShAmt, MVT::i8));
18654 if (N->getNumValues() == 2) // Dead flag value?
18655 return DCI.CombineTo(N, Cond, SDValue());
18659 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18660 // for any integer data type, including i8/i16.
18661 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18662 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18663 DAG.getConstant(CC, MVT::i8), Cond);
18665 // Zero extend the condition if needed.
18666 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18667 FalseC->getValueType(0), Cond);
18668 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18669 SDValue(FalseC, 0));
18671 if (N->getNumValues() == 2) // Dead flag value?
18672 return DCI.CombineTo(N, Cond, SDValue());
18676 // Optimize cases that will turn into an LEA instruction. This requires
18677 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18678 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18679 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18680 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18682 bool isFastMultiplier = false;
18684 switch ((unsigned char)Diff) {
18686 case 1: // result = add base, cond
18687 case 2: // result = lea base( , cond*2)
18688 case 3: // result = lea base(cond, cond*2)
18689 case 4: // result = lea base( , cond*4)
18690 case 5: // result = lea base(cond, cond*4)
18691 case 8: // result = lea base( , cond*8)
18692 case 9: // result = lea base(cond, cond*8)
18693 isFastMultiplier = true;
18698 if (isFastMultiplier) {
18699 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18700 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18701 DAG.getConstant(CC, MVT::i8), Cond);
18702 // Zero extend the condition if needed.
18703 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18705 // Scale the condition by the difference.
18707 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18708 DAG.getConstant(Diff, Cond.getValueType()));
18710 // Add the base if non-zero.
18711 if (FalseC->getAPIntValue() != 0)
18712 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18713 SDValue(FalseC, 0));
18714 if (N->getNumValues() == 2) // Dead flag value?
18715 return DCI.CombineTo(N, Cond, SDValue());
18722 // Handle these cases:
18723 // (select (x != c), e, c) -> select (x != c), e, x),
18724 // (select (x == c), c, e) -> select (x == c), x, e)
18725 // where the c is an integer constant, and the "select" is the combination
18726 // of CMOV and CMP.
18728 // The rationale for this change is that the conditional-move from a constant
18729 // needs two instructions, however, conditional-move from a register needs
18730 // only one instruction.
18732 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18733 // some instruction-combining opportunities. This opt needs to be
18734 // postponed as late as possible.
18736 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18737 // the DCI.xxxx conditions are provided to postpone the optimization as
18738 // late as possible.
18740 ConstantSDNode *CmpAgainst = nullptr;
18741 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18742 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18743 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18745 if (CC == X86::COND_NE &&
18746 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18747 CC = X86::GetOppositeBranchCondition(CC);
18748 std::swap(TrueOp, FalseOp);
18751 if (CC == X86::COND_E &&
18752 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18753 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18754 DAG.getConstant(CC, MVT::i8), Cond };
18755 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18763 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18764 const X86Subtarget *Subtarget) {
18765 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18767 default: return SDValue();
18768 // SSE/AVX/AVX2 blend intrinsics.
18769 case Intrinsic::x86_avx2_pblendvb:
18770 case Intrinsic::x86_avx2_pblendw:
18771 case Intrinsic::x86_avx2_pblendd_128:
18772 case Intrinsic::x86_avx2_pblendd_256:
18773 // Don't try to simplify this intrinsic if we don't have AVX2.
18774 if (!Subtarget->hasAVX2())
18777 case Intrinsic::x86_avx_blend_pd_256:
18778 case Intrinsic::x86_avx_blend_ps_256:
18779 case Intrinsic::x86_avx_blendv_pd_256:
18780 case Intrinsic::x86_avx_blendv_ps_256:
18781 // Don't try to simplify this intrinsic if we don't have AVX.
18782 if (!Subtarget->hasAVX())
18785 case Intrinsic::x86_sse41_pblendw:
18786 case Intrinsic::x86_sse41_blendpd:
18787 case Intrinsic::x86_sse41_blendps:
18788 case Intrinsic::x86_sse41_blendvps:
18789 case Intrinsic::x86_sse41_blendvpd:
18790 case Intrinsic::x86_sse41_pblendvb: {
18791 SDValue Op0 = N->getOperand(1);
18792 SDValue Op1 = N->getOperand(2);
18793 SDValue Mask = N->getOperand(3);
18795 // Don't try to simplify this intrinsic if we don't have SSE4.1.
18796 if (!Subtarget->hasSSE41())
18799 // fold (blend A, A, Mask) -> A
18802 // fold (blend A, B, allZeros) -> A
18803 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18805 // fold (blend A, B, allOnes) -> B
18806 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18809 // Simplify the case where the mask is a constant i32 value.
18810 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18811 if (C->isNullValue())
18813 if (C->isAllOnesValue())
18818 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18819 case Intrinsic::x86_sse2_psrai_w:
18820 case Intrinsic::x86_sse2_psrai_d:
18821 case Intrinsic::x86_avx2_psrai_w:
18822 case Intrinsic::x86_avx2_psrai_d:
18823 case Intrinsic::x86_sse2_psra_w:
18824 case Intrinsic::x86_sse2_psra_d:
18825 case Intrinsic::x86_avx2_psra_w:
18826 case Intrinsic::x86_avx2_psra_d: {
18827 SDValue Op0 = N->getOperand(1);
18828 SDValue Op1 = N->getOperand(2);
18829 EVT VT = Op0.getValueType();
18830 assert(VT.isVector() && "Expected a vector type!");
18832 if (isa<BuildVectorSDNode>(Op1))
18833 Op1 = Op1.getOperand(0);
18835 if (!isa<ConstantSDNode>(Op1))
18838 EVT SVT = VT.getVectorElementType();
18839 unsigned SVTBits = SVT.getSizeInBits();
18841 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18842 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18843 uint64_t ShAmt = C.getZExtValue();
18845 // Don't try to convert this shift into a ISD::SRA if the shift
18846 // count is bigger than or equal to the element size.
18847 if (ShAmt >= SVTBits)
18850 // Trivial case: if the shift count is zero, then fold this
18851 // into the first operand.
18855 // Replace this packed shift intrinsic with a target independent
18857 SDValue Splat = DAG.getConstant(C, VT);
18858 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18863 /// PerformMulCombine - Optimize a single multiply with constant into two
18864 /// in order to implement it with two cheaper instructions, e.g.
18865 /// LEA + SHL, LEA + LEA.
18866 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18867 TargetLowering::DAGCombinerInfo &DCI) {
18868 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18871 EVT VT = N->getValueType(0);
18872 if (VT != MVT::i64)
18875 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18878 uint64_t MulAmt = C->getZExtValue();
18879 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18882 uint64_t MulAmt1 = 0;
18883 uint64_t MulAmt2 = 0;
18884 if ((MulAmt % 9) == 0) {
18886 MulAmt2 = MulAmt / 9;
18887 } else if ((MulAmt % 5) == 0) {
18889 MulAmt2 = MulAmt / 5;
18890 } else if ((MulAmt % 3) == 0) {
18892 MulAmt2 = MulAmt / 3;
18895 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18898 if (isPowerOf2_64(MulAmt2) &&
18899 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18900 // If second multiplifer is pow2, issue it first. We want the multiply by
18901 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18903 std::swap(MulAmt1, MulAmt2);
18906 if (isPowerOf2_64(MulAmt1))
18907 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18908 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18910 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18911 DAG.getConstant(MulAmt1, VT));
18913 if (isPowerOf2_64(MulAmt2))
18914 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18915 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18917 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18918 DAG.getConstant(MulAmt2, VT));
18920 // Do not add new nodes to DAG combiner worklist.
18921 DCI.CombineTo(N, NewMul, false);
18926 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18927 SDValue N0 = N->getOperand(0);
18928 SDValue N1 = N->getOperand(1);
18929 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18930 EVT VT = N0.getValueType();
18932 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18933 // since the result of setcc_c is all zero's or all ones.
18934 if (VT.isInteger() && !VT.isVector() &&
18935 N1C && N0.getOpcode() == ISD::AND &&
18936 N0.getOperand(1).getOpcode() == ISD::Constant) {
18937 SDValue N00 = N0.getOperand(0);
18938 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18939 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18940 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18941 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18942 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18943 APInt ShAmt = N1C->getAPIntValue();
18944 Mask = Mask.shl(ShAmt);
18946 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18947 N00, DAG.getConstant(Mask, VT));
18951 // Hardware support for vector shifts is sparse which makes us scalarize the
18952 // vector operations in many cases. Also, on sandybridge ADD is faster than
18954 // (shl V, 1) -> add V,V
18955 if (isSplatVector(N1.getNode())) {
18956 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18957 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18958 // We shift all of the values by one. In many cases we do not have
18959 // hardware support for this operation. This is better expressed as an ADD
18961 if (N1C && (1 == N1C->getZExtValue())) {
18962 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18969 /// \brief Returns a vector of 0s if the node in input is a vector logical
18970 /// shift by a constant amount which is known to be bigger than or equal
18971 /// to the vector element size in bits.
18972 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18973 const X86Subtarget *Subtarget) {
18974 EVT VT = N->getValueType(0);
18976 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18977 (!Subtarget->hasInt256() ||
18978 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18981 SDValue Amt = N->getOperand(1);
18983 if (isSplatVector(Amt.getNode())) {
18984 SDValue SclrAmt = Amt->getOperand(0);
18985 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18986 APInt ShiftAmt = C->getAPIntValue();
18987 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18989 // SSE2/AVX2 logical shifts always return a vector of 0s
18990 // if the shift amount is bigger than or equal to
18991 // the element size. The constant shift amount will be
18992 // encoded as a 8-bit immediate.
18993 if (ShiftAmt.trunc(8).uge(MaxAmount))
18994 return getZeroVector(VT, Subtarget, DAG, DL);
19001 /// PerformShiftCombine - Combine shifts.
19002 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19003 TargetLowering::DAGCombinerInfo &DCI,
19004 const X86Subtarget *Subtarget) {
19005 if (N->getOpcode() == ISD::SHL) {
19006 SDValue V = PerformSHLCombine(N, DAG);
19007 if (V.getNode()) return V;
19010 if (N->getOpcode() != ISD::SRA) {
19011 // Try to fold this logical shift into a zero vector.
19012 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19013 if (V.getNode()) return V;
19019 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
19020 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19021 // and friends. Likewise for OR -> CMPNEQSS.
19022 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19023 TargetLowering::DAGCombinerInfo &DCI,
19024 const X86Subtarget *Subtarget) {
19027 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19028 // we're requiring SSE2 for both.
19029 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19030 SDValue N0 = N->getOperand(0);
19031 SDValue N1 = N->getOperand(1);
19032 SDValue CMP0 = N0->getOperand(1);
19033 SDValue CMP1 = N1->getOperand(1);
19036 // The SETCCs should both refer to the same CMP.
19037 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19040 SDValue CMP00 = CMP0->getOperand(0);
19041 SDValue CMP01 = CMP0->getOperand(1);
19042 EVT VT = CMP00.getValueType();
19044 if (VT == MVT::f32 || VT == MVT::f64) {
19045 bool ExpectingFlags = false;
19046 // Check for any users that want flags:
19047 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19048 !ExpectingFlags && UI != UE; ++UI)
19049 switch (UI->getOpcode()) {
19054 ExpectingFlags = true;
19056 case ISD::CopyToReg:
19057 case ISD::SIGN_EXTEND:
19058 case ISD::ZERO_EXTEND:
19059 case ISD::ANY_EXTEND:
19063 if (!ExpectingFlags) {
19064 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19065 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19067 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19068 X86::CondCode tmp = cc0;
19073 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
19074 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19075 // FIXME: need symbolic constants for these magic numbers.
19076 // See X86ATTInstPrinter.cpp:printSSECC().
19077 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19078 if (Subtarget->hasAVX512()) {
19079 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19080 CMP01, DAG.getConstant(x86cc, MVT::i8));
19081 if (N->getValueType(0) != MVT::i1)
19082 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19086 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19087 CMP00.getValueType(), CMP00, CMP01,
19088 DAG.getConstant(x86cc, MVT::i8));
19090 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19091 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19093 if (is64BitFP && !Subtarget->is64Bit()) {
19094 // On a 32-bit target, we cannot bitcast the 64-bit float to a
19095 // 64-bit integer, since that's not a legal type. Since
19096 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19097 // bits, but can do this little dance to extract the lowest 32 bits
19098 // and work with those going forward.
19099 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19101 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19103 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19104 Vector32, DAG.getIntPtrConstant(0));
19108 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19109 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19110 DAG.getConstant(1, IntVT));
19111 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19112 return OneBitOfTruth;
19120 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19121 /// so it can be folded inside ANDNP.
19122 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19123 EVT VT = N->getValueType(0);
19125 // Match direct AllOnes for 128 and 256-bit vectors
19126 if (ISD::isBuildVectorAllOnes(N))
19129 // Look through a bit convert.
19130 if (N->getOpcode() == ISD::BITCAST)
19131 N = N->getOperand(0).getNode();
19133 // Sometimes the operand may come from a insert_subvector building a 256-bit
19135 if (VT.is256BitVector() &&
19136 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19137 SDValue V1 = N->getOperand(0);
19138 SDValue V2 = N->getOperand(1);
19140 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19141 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19142 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19143 ISD::isBuildVectorAllOnes(V2.getNode()))
19150 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19151 // register. In most cases we actually compare or select YMM-sized registers
19152 // and mixing the two types creates horrible code. This method optimizes
19153 // some of the transition sequences.
19154 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19155 TargetLowering::DAGCombinerInfo &DCI,
19156 const X86Subtarget *Subtarget) {
19157 EVT VT = N->getValueType(0);
19158 if (!VT.is256BitVector())
19161 assert((N->getOpcode() == ISD::ANY_EXTEND ||
19162 N->getOpcode() == ISD::ZERO_EXTEND ||
19163 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19165 SDValue Narrow = N->getOperand(0);
19166 EVT NarrowVT = Narrow->getValueType(0);
19167 if (!NarrowVT.is128BitVector())
19170 if (Narrow->getOpcode() != ISD::XOR &&
19171 Narrow->getOpcode() != ISD::AND &&
19172 Narrow->getOpcode() != ISD::OR)
19175 SDValue N0 = Narrow->getOperand(0);
19176 SDValue N1 = Narrow->getOperand(1);
19179 // The Left side has to be a trunc.
19180 if (N0.getOpcode() != ISD::TRUNCATE)
19183 // The type of the truncated inputs.
19184 EVT WideVT = N0->getOperand(0)->getValueType(0);
19188 // The right side has to be a 'trunc' or a constant vector.
19189 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19190 bool RHSConst = (isSplatVector(N1.getNode()) &&
19191 isa<ConstantSDNode>(N1->getOperand(0)));
19192 if (!RHSTrunc && !RHSConst)
19195 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19197 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19200 // Set N0 and N1 to hold the inputs to the new wide operation.
19201 N0 = N0->getOperand(0);
19203 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19204 N1->getOperand(0));
19205 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19206 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19207 } else if (RHSTrunc) {
19208 N1 = N1->getOperand(0);
19211 // Generate the wide operation.
19212 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19213 unsigned Opcode = N->getOpcode();
19215 case ISD::ANY_EXTEND:
19217 case ISD::ZERO_EXTEND: {
19218 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19219 APInt Mask = APInt::getAllOnesValue(InBits);
19220 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19221 return DAG.getNode(ISD::AND, DL, VT,
19222 Op, DAG.getConstant(Mask, VT));
19224 case ISD::SIGN_EXTEND:
19225 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19226 Op, DAG.getValueType(NarrowVT));
19228 llvm_unreachable("Unexpected opcode");
19232 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19233 TargetLowering::DAGCombinerInfo &DCI,
19234 const X86Subtarget *Subtarget) {
19235 EVT VT = N->getValueType(0);
19236 if (DCI.isBeforeLegalizeOps())
19239 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19243 // Create BEXTR instructions
19244 // BEXTR is ((X >> imm) & (2**size-1))
19245 if (VT == MVT::i32 || VT == MVT::i64) {
19246 SDValue N0 = N->getOperand(0);
19247 SDValue N1 = N->getOperand(1);
19250 // Check for BEXTR.
19251 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19252 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19253 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19254 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19255 if (MaskNode && ShiftNode) {
19256 uint64_t Mask = MaskNode->getZExtValue();
19257 uint64_t Shift = ShiftNode->getZExtValue();
19258 if (isMask_64(Mask)) {
19259 uint64_t MaskSize = CountPopulation_64(Mask);
19260 if (Shift + MaskSize <= VT.getSizeInBits())
19261 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19262 DAG.getConstant(Shift | (MaskSize << 8), VT));
19270 // Want to form ANDNP nodes:
19271 // 1) In the hopes of then easily combining them with OR and AND nodes
19272 // to form PBLEND/PSIGN.
19273 // 2) To match ANDN packed intrinsics
19274 if (VT != MVT::v2i64 && VT != MVT::v4i64)
19277 SDValue N0 = N->getOperand(0);
19278 SDValue N1 = N->getOperand(1);
19281 // Check LHS for vnot
19282 if (N0.getOpcode() == ISD::XOR &&
19283 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19284 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19285 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19287 // Check RHS for vnot
19288 if (N1.getOpcode() == ISD::XOR &&
19289 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19290 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19291 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19296 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19297 TargetLowering::DAGCombinerInfo &DCI,
19298 const X86Subtarget *Subtarget) {
19299 if (DCI.isBeforeLegalizeOps())
19302 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19306 SDValue N0 = N->getOperand(0);
19307 SDValue N1 = N->getOperand(1);
19308 EVT VT = N->getValueType(0);
19310 // look for psign/blend
19311 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19312 if (!Subtarget->hasSSSE3() ||
19313 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19316 // Canonicalize pandn to RHS
19317 if (N0.getOpcode() == X86ISD::ANDNP)
19319 // or (and (m, y), (pandn m, x))
19320 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19321 SDValue Mask = N1.getOperand(0);
19322 SDValue X = N1.getOperand(1);
19324 if (N0.getOperand(0) == Mask)
19325 Y = N0.getOperand(1);
19326 if (N0.getOperand(1) == Mask)
19327 Y = N0.getOperand(0);
19329 // Check to see if the mask appeared in both the AND and ANDNP and
19333 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19334 // Look through mask bitcast.
19335 if (Mask.getOpcode() == ISD::BITCAST)
19336 Mask = Mask.getOperand(0);
19337 if (X.getOpcode() == ISD::BITCAST)
19338 X = X.getOperand(0);
19339 if (Y.getOpcode() == ISD::BITCAST)
19340 Y = Y.getOperand(0);
19342 EVT MaskVT = Mask.getValueType();
19344 // Validate that the Mask operand is a vector sra node.
19345 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19346 // there is no psrai.b
19347 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19348 unsigned SraAmt = ~0;
19349 if (Mask.getOpcode() == ISD::SRA) {
19350 SDValue Amt = Mask.getOperand(1);
19351 if (isSplatVector(Amt.getNode())) {
19352 SDValue SclrAmt = Amt->getOperand(0);
19353 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19354 SraAmt = C->getZExtValue();
19356 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19357 SDValue SraC = Mask.getOperand(1);
19358 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
19360 if ((SraAmt + 1) != EltBits)
19365 // Now we know we at least have a plendvb with the mask val. See if
19366 // we can form a psignb/w/d.
19367 // psign = x.type == y.type == mask.type && y = sub(0, x);
19368 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19369 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19370 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19371 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19372 "Unsupported VT for PSIGN");
19373 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19374 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19376 // PBLENDVB only available on SSE 4.1
19377 if (!Subtarget->hasSSE41())
19380 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19382 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19383 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19384 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19385 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19386 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19390 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19393 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19394 MachineFunction &MF = DAG.getMachineFunction();
19395 bool OptForSize = MF.getFunction()->getAttributes().
19396 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19398 // SHLD/SHRD instructions have lower register pressure, but on some
19399 // platforms they have higher latency than the equivalent
19400 // series of shifts/or that would otherwise be generated.
19401 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19402 // have higher latencies and we are not optimizing for size.
19403 if (!OptForSize && Subtarget->isSHLDSlow())
19406 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19408 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19410 if (!N0.hasOneUse() || !N1.hasOneUse())
19413 SDValue ShAmt0 = N0.getOperand(1);
19414 if (ShAmt0.getValueType() != MVT::i8)
19416 SDValue ShAmt1 = N1.getOperand(1);
19417 if (ShAmt1.getValueType() != MVT::i8)
19419 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19420 ShAmt0 = ShAmt0.getOperand(0);
19421 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19422 ShAmt1 = ShAmt1.getOperand(0);
19425 unsigned Opc = X86ISD::SHLD;
19426 SDValue Op0 = N0.getOperand(0);
19427 SDValue Op1 = N1.getOperand(0);
19428 if (ShAmt0.getOpcode() == ISD::SUB) {
19429 Opc = X86ISD::SHRD;
19430 std::swap(Op0, Op1);
19431 std::swap(ShAmt0, ShAmt1);
19434 unsigned Bits = VT.getSizeInBits();
19435 if (ShAmt1.getOpcode() == ISD::SUB) {
19436 SDValue Sum = ShAmt1.getOperand(0);
19437 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19438 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19439 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19440 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19441 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19442 return DAG.getNode(Opc, DL, VT,
19444 DAG.getNode(ISD::TRUNCATE, DL,
19447 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19448 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19450 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19451 return DAG.getNode(Opc, DL, VT,
19452 N0.getOperand(0), N1.getOperand(0),
19453 DAG.getNode(ISD::TRUNCATE, DL,
19460 // Generate NEG and CMOV for integer abs.
19461 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19462 EVT VT = N->getValueType(0);
19464 // Since X86 does not have CMOV for 8-bit integer, we don't convert
19465 // 8-bit integer abs to NEG and CMOV.
19466 if (VT.isInteger() && VT.getSizeInBits() == 8)
19469 SDValue N0 = N->getOperand(0);
19470 SDValue N1 = N->getOperand(1);
19473 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19474 // and change it to SUB and CMOV.
19475 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19476 N0.getOpcode() == ISD::ADD &&
19477 N0.getOperand(1) == N1 &&
19478 N1.getOpcode() == ISD::SRA &&
19479 N1.getOperand(0) == N0.getOperand(0))
19480 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19481 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19482 // Generate SUB & CMOV.
19483 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19484 DAG.getConstant(0, VT), N0.getOperand(0));
19486 SDValue Ops[] = { N0.getOperand(0), Neg,
19487 DAG.getConstant(X86::COND_GE, MVT::i8),
19488 SDValue(Neg.getNode(), 1) };
19489 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19494 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19495 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19496 TargetLowering::DAGCombinerInfo &DCI,
19497 const X86Subtarget *Subtarget) {
19498 if (DCI.isBeforeLegalizeOps())
19501 if (Subtarget->hasCMov()) {
19502 SDValue RV = performIntegerAbsCombine(N, DAG);
19510 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19511 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19512 TargetLowering::DAGCombinerInfo &DCI,
19513 const X86Subtarget *Subtarget) {
19514 LoadSDNode *Ld = cast<LoadSDNode>(N);
19515 EVT RegVT = Ld->getValueType(0);
19516 EVT MemVT = Ld->getMemoryVT();
19518 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19519 unsigned RegSz = RegVT.getSizeInBits();
19521 // On Sandybridge unaligned 256bit loads are inefficient.
19522 ISD::LoadExtType Ext = Ld->getExtensionType();
19523 unsigned Alignment = Ld->getAlignment();
19524 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19525 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19526 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19527 unsigned NumElems = RegVT.getVectorNumElements();
19531 SDValue Ptr = Ld->getBasePtr();
19532 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19534 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19536 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19537 Ld->getPointerInfo(), Ld->isVolatile(),
19538 Ld->isNonTemporal(), Ld->isInvariant(),
19540 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19541 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19542 Ld->getPointerInfo(), Ld->isVolatile(),
19543 Ld->isNonTemporal(), Ld->isInvariant(),
19544 std::min(16U, Alignment));
19545 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19547 Load2.getValue(1));
19549 SDValue NewVec = DAG.getUNDEF(RegVT);
19550 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19551 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19552 return DCI.CombineTo(N, NewVec, TF, true);
19555 // If this is a vector EXT Load then attempt to optimize it using a
19556 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19557 // expansion is still better than scalar code.
19558 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19559 // emit a shuffle and a arithmetic shift.
19560 // TODO: It is possible to support ZExt by zeroing the undef values
19561 // during the shuffle phase or after the shuffle.
19562 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19563 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19564 assert(MemVT != RegVT && "Cannot extend to the same type");
19565 assert(MemVT.isVector() && "Must load a vector from memory");
19567 unsigned NumElems = RegVT.getVectorNumElements();
19568 unsigned MemSz = MemVT.getSizeInBits();
19569 assert(RegSz > MemSz && "Register size must be greater than the mem size");
19571 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19574 // All sizes must be a power of two.
19575 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19578 // Attempt to load the original value using scalar loads.
19579 // Find the largest scalar type that divides the total loaded size.
19580 MVT SclrLoadTy = MVT::i8;
19581 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19582 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19583 MVT Tp = (MVT::SimpleValueType)tp;
19584 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19589 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19590 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19592 SclrLoadTy = MVT::f64;
19594 // Calculate the number of scalar loads that we need to perform
19595 // in order to load our vector from memory.
19596 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19597 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19600 unsigned loadRegZize = RegSz;
19601 if (Ext == ISD::SEXTLOAD && RegSz == 256)
19604 // Represent our vector as a sequence of elements which are the
19605 // largest scalar that we can load.
19606 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19607 loadRegZize/SclrLoadTy.getSizeInBits());
19609 // Represent the data using the same element type that is stored in
19610 // memory. In practice, we ''widen'' MemVT.
19612 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19613 loadRegZize/MemVT.getScalarType().getSizeInBits());
19615 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19616 "Invalid vector type");
19618 // We can't shuffle using an illegal type.
19619 if (!TLI.isTypeLegal(WideVecVT))
19622 SmallVector<SDValue, 8> Chains;
19623 SDValue Ptr = Ld->getBasePtr();
19624 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19625 TLI.getPointerTy());
19626 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19628 for (unsigned i = 0; i < NumLoads; ++i) {
19629 // Perform a single load.
19630 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19631 Ptr, Ld->getPointerInfo(),
19632 Ld->isVolatile(), Ld->isNonTemporal(),
19633 Ld->isInvariant(), Ld->getAlignment());
19634 Chains.push_back(ScalarLoad.getValue(1));
19635 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19636 // another round of DAGCombining.
19638 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19640 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19641 ScalarLoad, DAG.getIntPtrConstant(i));
19643 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19646 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19648 // Bitcast the loaded value to a vector of the original element type, in
19649 // the size of the target vector type.
19650 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19651 unsigned SizeRatio = RegSz/MemSz;
19653 if (Ext == ISD::SEXTLOAD) {
19654 // If we have SSE4.1 we can directly emit a VSEXT node.
19655 if (Subtarget->hasSSE41()) {
19656 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19657 return DCI.CombineTo(N, Sext, TF, true);
19660 // Otherwise we'll shuffle the small elements in the high bits of the
19661 // larger type and perform an arithmetic shift. If the shift is not legal
19662 // it's better to scalarize.
19663 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19666 // Redistribute the loaded elements into the different locations.
19667 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19668 for (unsigned i = 0; i != NumElems; ++i)
19669 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19671 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19672 DAG.getUNDEF(WideVecVT),
19675 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19677 // Build the arithmetic shift.
19678 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19679 MemVT.getVectorElementType().getSizeInBits();
19680 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19681 DAG.getConstant(Amt, RegVT));
19683 return DCI.CombineTo(N, Shuff, TF, true);
19686 // Redistribute the loaded elements into the different locations.
19687 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19688 for (unsigned i = 0; i != NumElems; ++i)
19689 ShuffleVec[i*SizeRatio] = i;
19691 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19692 DAG.getUNDEF(WideVecVT),
19695 // Bitcast to the requested type.
19696 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19697 // Replace the original load with the new sequence
19698 // and return the new chain.
19699 return DCI.CombineTo(N, Shuff, TF, true);
19705 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19706 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19707 const X86Subtarget *Subtarget) {
19708 StoreSDNode *St = cast<StoreSDNode>(N);
19709 EVT VT = St->getValue().getValueType();
19710 EVT StVT = St->getMemoryVT();
19712 SDValue StoredVal = St->getOperand(1);
19713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19715 // If we are saving a concatenation of two XMM registers, perform two stores.
19716 // On Sandy Bridge, 256-bit memory operations are executed by two
19717 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19718 // memory operation.
19719 unsigned Alignment = St->getAlignment();
19720 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19721 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19722 StVT == VT && !IsAligned) {
19723 unsigned NumElems = VT.getVectorNumElements();
19727 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19728 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19730 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19731 SDValue Ptr0 = St->getBasePtr();
19732 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19734 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19735 St->getPointerInfo(), St->isVolatile(),
19736 St->isNonTemporal(), Alignment);
19737 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19738 St->getPointerInfo(), St->isVolatile(),
19739 St->isNonTemporal(),
19740 std::min(16U, Alignment));
19741 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19744 // Optimize trunc store (of multiple scalars) to shuffle and store.
19745 // First, pack all of the elements in one place. Next, store to memory
19746 // in fewer chunks.
19747 if (St->isTruncatingStore() && VT.isVector()) {
19748 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19749 unsigned NumElems = VT.getVectorNumElements();
19750 assert(StVT != VT && "Cannot truncate to the same type");
19751 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19752 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19754 // From, To sizes and ElemCount must be pow of two
19755 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19756 // We are going to use the original vector elt for storing.
19757 // Accumulated smaller vector elements must be a multiple of the store size.
19758 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19760 unsigned SizeRatio = FromSz / ToSz;
19762 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19764 // Create a type on which we perform the shuffle
19765 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19766 StVT.getScalarType(), NumElems*SizeRatio);
19768 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19770 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19771 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19772 for (unsigned i = 0; i != NumElems; ++i)
19773 ShuffleVec[i] = i * SizeRatio;
19775 // Can't shuffle using an illegal type.
19776 if (!TLI.isTypeLegal(WideVecVT))
19779 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19780 DAG.getUNDEF(WideVecVT),
19782 // At this point all of the data is stored at the bottom of the
19783 // register. We now need to save it to mem.
19785 // Find the largest store unit
19786 MVT StoreType = MVT::i8;
19787 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19788 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19789 MVT Tp = (MVT::SimpleValueType)tp;
19790 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19794 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19795 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19796 (64 <= NumElems * ToSz))
19797 StoreType = MVT::f64;
19799 // Bitcast the original vector into a vector of store-size units
19800 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19801 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19802 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19803 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19804 SmallVector<SDValue, 8> Chains;
19805 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19806 TLI.getPointerTy());
19807 SDValue Ptr = St->getBasePtr();
19809 // Perform one or more big stores into memory.
19810 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19811 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19812 StoreType, ShuffWide,
19813 DAG.getIntPtrConstant(i));
19814 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19815 St->getPointerInfo(), St->isVolatile(),
19816 St->isNonTemporal(), St->getAlignment());
19817 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19818 Chains.push_back(Ch);
19821 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19824 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19825 // the FP state in cases where an emms may be missing.
19826 // A preferable solution to the general problem is to figure out the right
19827 // places to insert EMMS. This qualifies as a quick hack.
19829 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19830 if (VT.getSizeInBits() != 64)
19833 const Function *F = DAG.getMachineFunction().getFunction();
19834 bool NoImplicitFloatOps = F->getAttributes().
19835 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19836 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19837 && Subtarget->hasSSE2();
19838 if ((VT.isVector() ||
19839 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19840 isa<LoadSDNode>(St->getValue()) &&
19841 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19842 St->getChain().hasOneUse() && !St->isVolatile()) {
19843 SDNode* LdVal = St->getValue().getNode();
19844 LoadSDNode *Ld = nullptr;
19845 int TokenFactorIndex = -1;
19846 SmallVector<SDValue, 8> Ops;
19847 SDNode* ChainVal = St->getChain().getNode();
19848 // Must be a store of a load. We currently handle two cases: the load
19849 // is a direct child, and it's under an intervening TokenFactor. It is
19850 // possible to dig deeper under nested TokenFactors.
19851 if (ChainVal == LdVal)
19852 Ld = cast<LoadSDNode>(St->getChain());
19853 else if (St->getValue().hasOneUse() &&
19854 ChainVal->getOpcode() == ISD::TokenFactor) {
19855 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19856 if (ChainVal->getOperand(i).getNode() == LdVal) {
19857 TokenFactorIndex = i;
19858 Ld = cast<LoadSDNode>(St->getValue());
19860 Ops.push_back(ChainVal->getOperand(i));
19864 if (!Ld || !ISD::isNormalLoad(Ld))
19867 // If this is not the MMX case, i.e. we are just turning i64 load/store
19868 // into f64 load/store, avoid the transformation if there are multiple
19869 // uses of the loaded value.
19870 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19875 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19876 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19878 if (Subtarget->is64Bit() || F64IsLegal) {
19879 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19880 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19881 Ld->getPointerInfo(), Ld->isVolatile(),
19882 Ld->isNonTemporal(), Ld->isInvariant(),
19883 Ld->getAlignment());
19884 SDValue NewChain = NewLd.getValue(1);
19885 if (TokenFactorIndex != -1) {
19886 Ops.push_back(NewChain);
19887 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19889 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19890 St->getPointerInfo(),
19891 St->isVolatile(), St->isNonTemporal(),
19892 St->getAlignment());
19895 // Otherwise, lower to two pairs of 32-bit loads / stores.
19896 SDValue LoAddr = Ld->getBasePtr();
19897 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19898 DAG.getConstant(4, MVT::i32));
19900 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19901 Ld->getPointerInfo(),
19902 Ld->isVolatile(), Ld->isNonTemporal(),
19903 Ld->isInvariant(), Ld->getAlignment());
19904 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19905 Ld->getPointerInfo().getWithOffset(4),
19906 Ld->isVolatile(), Ld->isNonTemporal(),
19908 MinAlign(Ld->getAlignment(), 4));
19910 SDValue NewChain = LoLd.getValue(1);
19911 if (TokenFactorIndex != -1) {
19912 Ops.push_back(LoLd);
19913 Ops.push_back(HiLd);
19914 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19917 LoAddr = St->getBasePtr();
19918 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19919 DAG.getConstant(4, MVT::i32));
19921 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19922 St->getPointerInfo(),
19923 St->isVolatile(), St->isNonTemporal(),
19924 St->getAlignment());
19925 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19926 St->getPointerInfo().getWithOffset(4),
19928 St->isNonTemporal(),
19929 MinAlign(St->getAlignment(), 4));
19930 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19935 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19936 /// and return the operands for the horizontal operation in LHS and RHS. A
19937 /// horizontal operation performs the binary operation on successive elements
19938 /// of its first operand, then on successive elements of its second operand,
19939 /// returning the resulting values in a vector. For example, if
19940 /// A = < float a0, float a1, float a2, float a3 >
19942 /// B = < float b0, float b1, float b2, float b3 >
19943 /// then the result of doing a horizontal operation on A and B is
19944 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19945 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19946 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19947 /// set to A, RHS to B, and the routine returns 'true'.
19948 /// Note that the binary operation should have the property that if one of the
19949 /// operands is UNDEF then the result is UNDEF.
19950 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19951 // Look for the following pattern: if
19952 // A = < float a0, float a1, float a2, float a3 >
19953 // B = < float b0, float b1, float b2, float b3 >
19955 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19956 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19957 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19958 // which is A horizontal-op B.
19960 // At least one of the operands should be a vector shuffle.
19961 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19962 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19965 MVT VT = LHS.getSimpleValueType();
19967 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19968 "Unsupported vector type for horizontal add/sub");
19970 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19971 // operate independently on 128-bit lanes.
19972 unsigned NumElts = VT.getVectorNumElements();
19973 unsigned NumLanes = VT.getSizeInBits()/128;
19974 unsigned NumLaneElts = NumElts / NumLanes;
19975 assert((NumLaneElts % 2 == 0) &&
19976 "Vector type should have an even number of elements in each lane");
19977 unsigned HalfLaneElts = NumLaneElts/2;
19979 // View LHS in the form
19980 // LHS = VECTOR_SHUFFLE A, B, LMask
19981 // If LHS is not a shuffle then pretend it is the shuffle
19982 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19983 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19986 SmallVector<int, 16> LMask(NumElts);
19987 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19988 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19989 A = LHS.getOperand(0);
19990 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19991 B = LHS.getOperand(1);
19992 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19993 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19995 if (LHS.getOpcode() != ISD::UNDEF)
19997 for (unsigned i = 0; i != NumElts; ++i)
20001 // Likewise, view RHS in the form
20002 // RHS = VECTOR_SHUFFLE C, D, RMask
20004 SmallVector<int, 16> RMask(NumElts);
20005 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20006 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20007 C = RHS.getOperand(0);
20008 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20009 D = RHS.getOperand(1);
20010 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20011 std::copy(Mask.begin(), Mask.end(), RMask.begin());
20013 if (RHS.getOpcode() != ISD::UNDEF)
20015 for (unsigned i = 0; i != NumElts; ++i)
20019 // Check that the shuffles are both shuffling the same vectors.
20020 if (!(A == C && B == D) && !(A == D && B == C))
20023 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20024 if (!A.getNode() && !B.getNode())
20027 // If A and B occur in reverse order in RHS, then "swap" them (which means
20028 // rewriting the mask).
20030 CommuteVectorShuffleMask(RMask, NumElts);
20032 // At this point LHS and RHS are equivalent to
20033 // LHS = VECTOR_SHUFFLE A, B, LMask
20034 // RHS = VECTOR_SHUFFLE A, B, RMask
20035 // Check that the masks correspond to performing a horizontal operation.
20036 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20037 for (unsigned i = 0; i != NumLaneElts; ++i) {
20038 int LIdx = LMask[i+l], RIdx = RMask[i+l];
20040 // Ignore any UNDEF components.
20041 if (LIdx < 0 || RIdx < 0 ||
20042 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20043 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20046 // Check that successive elements are being operated on. If not, this is
20047 // not a horizontal operation.
20048 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20049 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20050 if (!(LIdx == Index && RIdx == Index + 1) &&
20051 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20056 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20057 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20061 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20062 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20063 const X86Subtarget *Subtarget) {
20064 EVT VT = N->getValueType(0);
20065 SDValue LHS = N->getOperand(0);
20066 SDValue RHS = N->getOperand(1);
20068 // Try to synthesize horizontal adds from adds of shuffles.
20069 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20070 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20071 isHorizontalBinOp(LHS, RHS, true))
20072 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20076 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20077 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20078 const X86Subtarget *Subtarget) {
20079 EVT VT = N->getValueType(0);
20080 SDValue LHS = N->getOperand(0);
20081 SDValue RHS = N->getOperand(1);
20083 // Try to synthesize horizontal subs from subs of shuffles.
20084 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20085 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20086 isHorizontalBinOp(LHS, RHS, false))
20087 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20091 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20092 /// X86ISD::FXOR nodes.
20093 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20094 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20095 // F[X]OR(0.0, x) -> x
20096 // F[X]OR(x, 0.0) -> x
20097 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20098 if (C->getValueAPF().isPosZero())
20099 return N->getOperand(1);
20100 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20101 if (C->getValueAPF().isPosZero())
20102 return N->getOperand(0);
20106 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20107 /// X86ISD::FMAX nodes.
20108 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20109 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20111 // Only perform optimizations if UnsafeMath is used.
20112 if (!DAG.getTarget().Options.UnsafeFPMath)
20115 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20116 // into FMINC and FMAXC, which are Commutative operations.
20117 unsigned NewOp = 0;
20118 switch (N->getOpcode()) {
20119 default: llvm_unreachable("unknown opcode");
20120 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
20121 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
20124 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20125 N->getOperand(0), N->getOperand(1));
20128 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20129 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20130 // FAND(0.0, x) -> 0.0
20131 // FAND(x, 0.0) -> 0.0
20132 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20133 if (C->getValueAPF().isPosZero())
20134 return N->getOperand(0);
20135 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20136 if (C->getValueAPF().isPosZero())
20137 return N->getOperand(1);
20141 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20142 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20143 // FANDN(x, 0.0) -> 0.0
20144 // FANDN(0.0, x) -> x
20145 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20146 if (C->getValueAPF().isPosZero())
20147 return N->getOperand(1);
20148 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20149 if (C->getValueAPF().isPosZero())
20150 return N->getOperand(1);
20154 static SDValue PerformBTCombine(SDNode *N,
20156 TargetLowering::DAGCombinerInfo &DCI) {
20157 // BT ignores high bits in the bit index operand.
20158 SDValue Op1 = N->getOperand(1);
20159 if (Op1.hasOneUse()) {
20160 unsigned BitWidth = Op1.getValueSizeInBits();
20161 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20162 APInt KnownZero, KnownOne;
20163 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20164 !DCI.isBeforeLegalizeOps());
20165 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20166 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20167 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20168 DCI.CommitTargetLoweringOpt(TLO);
20173 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20174 SDValue Op = N->getOperand(0);
20175 if (Op.getOpcode() == ISD::BITCAST)
20176 Op = Op.getOperand(0);
20177 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20178 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20179 VT.getVectorElementType().getSizeInBits() ==
20180 OpVT.getVectorElementType().getSizeInBits()) {
20181 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20186 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20187 const X86Subtarget *Subtarget) {
20188 EVT VT = N->getValueType(0);
20189 if (!VT.isVector())
20192 SDValue N0 = N->getOperand(0);
20193 SDValue N1 = N->getOperand(1);
20194 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20197 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20198 // both SSE and AVX2 since there is no sign-extended shift right
20199 // operation on a vector with 64-bit elements.
20200 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20201 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20202 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20203 N0.getOpcode() == ISD::SIGN_EXTEND)) {
20204 SDValue N00 = N0.getOperand(0);
20206 // EXTLOAD has a better solution on AVX2,
20207 // it may be replaced with X86ISD::VSEXT node.
20208 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20209 if (!ISD::isNormalLoad(N00.getNode()))
20212 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20213 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20215 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20221 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20222 TargetLowering::DAGCombinerInfo &DCI,
20223 const X86Subtarget *Subtarget) {
20224 if (!DCI.isBeforeLegalizeOps())
20227 if (!Subtarget->hasFp256())
20230 EVT VT = N->getValueType(0);
20231 if (VT.isVector() && VT.getSizeInBits() == 256) {
20232 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20240 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20241 const X86Subtarget* Subtarget) {
20243 EVT VT = N->getValueType(0);
20245 // Let legalize expand this if it isn't a legal type yet.
20246 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20249 EVT ScalarVT = VT.getScalarType();
20250 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20251 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20254 SDValue A = N->getOperand(0);
20255 SDValue B = N->getOperand(1);
20256 SDValue C = N->getOperand(2);
20258 bool NegA = (A.getOpcode() == ISD::FNEG);
20259 bool NegB = (B.getOpcode() == ISD::FNEG);
20260 bool NegC = (C.getOpcode() == ISD::FNEG);
20262 // Negative multiplication when NegA xor NegB
20263 bool NegMul = (NegA != NegB);
20265 A = A.getOperand(0);
20267 B = B.getOperand(0);
20269 C = C.getOperand(0);
20273 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20275 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20277 return DAG.getNode(Opcode, dl, VT, A, B, C);
20280 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20281 TargetLowering::DAGCombinerInfo &DCI,
20282 const X86Subtarget *Subtarget) {
20283 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
20284 // (and (i32 x86isd::setcc_carry), 1)
20285 // This eliminates the zext. This transformation is necessary because
20286 // ISD::SETCC is always legalized to i8.
20288 SDValue N0 = N->getOperand(0);
20289 EVT VT = N->getValueType(0);
20291 if (N0.getOpcode() == ISD::AND &&
20293 N0.getOperand(0).hasOneUse()) {
20294 SDValue N00 = N0.getOperand(0);
20295 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20296 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20297 if (!C || C->getZExtValue() != 1)
20299 return DAG.getNode(ISD::AND, dl, VT,
20300 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20301 N00.getOperand(0), N00.getOperand(1)),
20302 DAG.getConstant(1, VT));
20306 if (N0.getOpcode() == ISD::TRUNCATE &&
20308 N0.getOperand(0).hasOneUse()) {
20309 SDValue N00 = N0.getOperand(0);
20310 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20311 return DAG.getNode(ISD::AND, dl, VT,
20312 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20313 N00.getOperand(0), N00.getOperand(1)),
20314 DAG.getConstant(1, VT));
20317 if (VT.is256BitVector()) {
20318 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20326 // Optimize x == -y --> x+y == 0
20327 // x != -y --> x+y != 0
20328 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20329 const X86Subtarget* Subtarget) {
20330 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20331 SDValue LHS = N->getOperand(0);
20332 SDValue RHS = N->getOperand(1);
20333 EVT VT = N->getValueType(0);
20336 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20337 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20338 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20339 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20340 LHS.getValueType(), RHS, LHS.getOperand(1));
20341 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20342 addV, DAG.getConstant(0, addV.getValueType()), CC);
20344 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20345 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20346 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20347 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20348 RHS.getValueType(), LHS, RHS.getOperand(1));
20349 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20350 addV, DAG.getConstant(0, addV.getValueType()), CC);
20353 if (VT.getScalarType() == MVT::i1) {
20354 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20355 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20356 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20357 if (!IsSEXT0 && !IsVZero0)
20359 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20360 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
20361 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20363 if (!IsSEXT1 && !IsVZero1)
20366 if (IsSEXT0 && IsVZero1) {
20367 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20368 if (CC == ISD::SETEQ)
20369 return DAG.getNOT(DL, LHS.getOperand(0), VT);
20370 return LHS.getOperand(0);
20372 if (IsSEXT1 && IsVZero0) {
20373 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20374 if (CC == ISD::SETEQ)
20375 return DAG.getNOT(DL, RHS.getOperand(0), VT);
20376 return RHS.getOperand(0);
20383 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20384 const X86Subtarget *Subtarget) {
20386 MVT VT = N->getOperand(1)->getSimpleValueType(0);
20387 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20388 "X86insertps is only defined for v4x32");
20390 SDValue Ld = N->getOperand(1);
20391 if (MayFoldLoad(Ld)) {
20392 // Extract the countS bits from the immediate so we can get the proper
20393 // address when narrowing the vector load to a specific element.
20394 // When the second source op is a memory address, interps doesn't use
20395 // countS and just gets an f32 from that address.
20396 unsigned DestIndex =
20397 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20398 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20402 // Create this as a scalar to vector to match the instruction pattern.
20403 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20404 // countS bits are ignored when loading from memory on insertps, which
20405 // means we don't need to explicitly set them to 0.
20406 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20407 LoadScalarToVector, N->getOperand(2));
20410 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20411 // as "sbb reg,reg", since it can be extended without zext and produces
20412 // an all-ones bit which is more useful than 0/1 in some cases.
20413 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20416 return DAG.getNode(ISD::AND, DL, VT,
20417 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20418 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20419 DAG.getConstant(1, VT));
20420 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20421 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20422 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20423 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20426 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20427 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20428 TargetLowering::DAGCombinerInfo &DCI,
20429 const X86Subtarget *Subtarget) {
20431 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20432 SDValue EFLAGS = N->getOperand(1);
20434 if (CC == X86::COND_A) {
20435 // Try to convert COND_A into COND_B in an attempt to facilitate
20436 // materializing "setb reg".
20438 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20439 // cannot take an immediate as its first operand.
20441 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20442 EFLAGS.getValueType().isInteger() &&
20443 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20444 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20445 EFLAGS.getNode()->getVTList(),
20446 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20447 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20448 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20452 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20453 // a zext and produces an all-ones bit which is more useful than 0/1 in some
20455 if (CC == X86::COND_B)
20456 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20460 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20461 if (Flags.getNode()) {
20462 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20463 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20469 // Optimize branch condition evaluation.
20471 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20472 TargetLowering::DAGCombinerInfo &DCI,
20473 const X86Subtarget *Subtarget) {
20475 SDValue Chain = N->getOperand(0);
20476 SDValue Dest = N->getOperand(1);
20477 SDValue EFLAGS = N->getOperand(3);
20478 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20482 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20483 if (Flags.getNode()) {
20484 SDValue Cond = DAG.getConstant(CC, MVT::i8);
20485 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20492 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20493 const X86TargetLowering *XTLI) {
20494 SDValue Op0 = N->getOperand(0);
20495 EVT InVT = Op0->getValueType(0);
20497 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20498 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20500 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20501 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20502 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20505 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20506 // a 32-bit target where SSE doesn't support i64->FP operations.
20507 if (Op0.getOpcode() == ISD::LOAD) {
20508 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20509 EVT VT = Ld->getValueType(0);
20510 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20511 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20512 !XTLI->getSubtarget()->is64Bit() &&
20514 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20515 Ld->getChain(), Op0, DAG);
20516 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20523 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20524 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20525 X86TargetLowering::DAGCombinerInfo &DCI) {
20526 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20527 // the result is either zero or one (depending on the input carry bit).
20528 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20529 if (X86::isZeroNode(N->getOperand(0)) &&
20530 X86::isZeroNode(N->getOperand(1)) &&
20531 // We don't have a good way to replace an EFLAGS use, so only do this when
20533 SDValue(N, 1).use_empty()) {
20535 EVT VT = N->getValueType(0);
20536 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20537 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20538 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20539 DAG.getConstant(X86::COND_B,MVT::i8),
20541 DAG.getConstant(1, VT));
20542 return DCI.CombineTo(N, Res1, CarryOut);
20548 // fold (add Y, (sete X, 0)) -> adc 0, Y
20549 // (add Y, (setne X, 0)) -> sbb -1, Y
20550 // (sub (sete X, 0), Y) -> sbb 0, Y
20551 // (sub (setne X, 0), Y) -> adc -1, Y
20552 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20555 // Look through ZExts.
20556 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20557 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20560 SDValue SetCC = Ext.getOperand(0);
20561 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20564 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20565 if (CC != X86::COND_E && CC != X86::COND_NE)
20568 SDValue Cmp = SetCC.getOperand(1);
20569 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20570 !X86::isZeroNode(Cmp.getOperand(1)) ||
20571 !Cmp.getOperand(0).getValueType().isInteger())
20574 SDValue CmpOp0 = Cmp.getOperand(0);
20575 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20576 DAG.getConstant(1, CmpOp0.getValueType()));
20578 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20579 if (CC == X86::COND_NE)
20580 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20581 DL, OtherVal.getValueType(), OtherVal,
20582 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20583 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20584 DL, OtherVal.getValueType(), OtherVal,
20585 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20588 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20589 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20590 const X86Subtarget *Subtarget) {
20591 EVT VT = N->getValueType(0);
20592 SDValue Op0 = N->getOperand(0);
20593 SDValue Op1 = N->getOperand(1);
20595 // Try to synthesize horizontal adds from adds of shuffles.
20596 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20597 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20598 isHorizontalBinOp(Op0, Op1, true))
20599 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20601 return OptimizeConditionalInDecrement(N, DAG);
20604 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20605 const X86Subtarget *Subtarget) {
20606 SDValue Op0 = N->getOperand(0);
20607 SDValue Op1 = N->getOperand(1);
20609 // X86 can't encode an immediate LHS of a sub. See if we can push the
20610 // negation into a preceding instruction.
20611 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20612 // If the RHS of the sub is a XOR with one use and a constant, invert the
20613 // immediate. Then add one to the LHS of the sub so we can turn
20614 // X-Y -> X+~Y+1, saving one register.
20615 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20616 isa<ConstantSDNode>(Op1.getOperand(1))) {
20617 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20618 EVT VT = Op0.getValueType();
20619 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20621 DAG.getConstant(~XorC, VT));
20622 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20623 DAG.getConstant(C->getAPIntValue()+1, VT));
20627 // Try to synthesize horizontal adds from adds of shuffles.
20628 EVT VT = N->getValueType(0);
20629 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20630 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20631 isHorizontalBinOp(Op0, Op1, true))
20632 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20634 return OptimizeConditionalInDecrement(N, DAG);
20637 /// performVZEXTCombine - Performs build vector combines
20638 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20639 TargetLowering::DAGCombinerInfo &DCI,
20640 const X86Subtarget *Subtarget) {
20641 // (vzext (bitcast (vzext (x)) -> (vzext x)
20642 SDValue In = N->getOperand(0);
20643 while (In.getOpcode() == ISD::BITCAST)
20644 In = In.getOperand(0);
20646 if (In.getOpcode() != X86ISD::VZEXT)
20649 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20653 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20654 DAGCombinerInfo &DCI) const {
20655 SelectionDAG &DAG = DCI.DAG;
20656 switch (N->getOpcode()) {
20658 case ISD::EXTRACT_VECTOR_ELT:
20659 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20661 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20662 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20663 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20664 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20665 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20666 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20669 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20670 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20671 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20672 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20673 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20674 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20675 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20676 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20677 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20679 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20681 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20682 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20683 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20684 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20685 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20686 case ISD::ANY_EXTEND:
20687 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20688 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20689 case ISD::SIGN_EXTEND_INREG:
20690 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20691 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20692 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20693 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20694 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20695 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20696 case X86ISD::SHUFP: // Handle all target specific shuffles
20697 case X86ISD::PALIGNR:
20698 case X86ISD::UNPCKH:
20699 case X86ISD::UNPCKL:
20700 case X86ISD::MOVHLPS:
20701 case X86ISD::MOVLHPS:
20702 case X86ISD::PSHUFD:
20703 case X86ISD::PSHUFHW:
20704 case X86ISD::PSHUFLW:
20705 case X86ISD::MOVSS:
20706 case X86ISD::MOVSD:
20707 case X86ISD::VPERMILP:
20708 case X86ISD::VPERM2X128:
20709 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20710 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20711 case ISD::INTRINSIC_WO_CHAIN:
20712 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20713 case X86ISD::INSERTPS:
20714 return PerformINSERTPSCombine(N, DAG, Subtarget);
20720 /// isTypeDesirableForOp - Return true if the target has native support for
20721 /// the specified value type and it is 'desirable' to use the type for the
20722 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20723 /// instruction encodings are longer and some i16 instructions are slow.
20724 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20725 if (!isTypeLegal(VT))
20727 if (VT != MVT::i16)
20734 case ISD::SIGN_EXTEND:
20735 case ISD::ZERO_EXTEND:
20736 case ISD::ANY_EXTEND:
20749 /// IsDesirableToPromoteOp - This method query the target whether it is
20750 /// beneficial for dag combiner to promote the specified node. If true, it
20751 /// should return the desired promotion type by reference.
20752 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20753 EVT VT = Op.getValueType();
20754 if (VT != MVT::i16)
20757 bool Promote = false;
20758 bool Commute = false;
20759 switch (Op.getOpcode()) {
20762 LoadSDNode *LD = cast<LoadSDNode>(Op);
20763 // If the non-extending load has a single use and it's not live out, then it
20764 // might be folded.
20765 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20766 Op.hasOneUse()*/) {
20767 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20768 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20769 // The only case where we'd want to promote LOAD (rather then it being
20770 // promoted as an operand is when it's only use is liveout.
20771 if (UI->getOpcode() != ISD::CopyToReg)
20778 case ISD::SIGN_EXTEND:
20779 case ISD::ZERO_EXTEND:
20780 case ISD::ANY_EXTEND:
20785 SDValue N0 = Op.getOperand(0);
20786 // Look out for (store (shl (load), x)).
20787 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20800 SDValue N0 = Op.getOperand(0);
20801 SDValue N1 = Op.getOperand(1);
20802 if (!Commute && MayFoldLoad(N1))
20804 // Avoid disabling potential load folding opportunities.
20805 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20807 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20817 //===----------------------------------------------------------------------===//
20818 // X86 Inline Assembly Support
20819 //===----------------------------------------------------------------------===//
20822 // Helper to match a string separated by whitespace.
20823 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20824 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20826 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20827 StringRef piece(*args[i]);
20828 if (!s.startswith(piece)) // Check if the piece matches.
20831 s = s.substr(piece.size());
20832 StringRef::size_type pos = s.find_first_not_of(" \t");
20833 if (pos == 0) // We matched a prefix.
20841 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20844 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20846 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20847 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20848 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20849 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20851 if (AsmPieces.size() == 3)
20853 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20860 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20861 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20863 std::string AsmStr = IA->getAsmString();
20865 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20866 if (!Ty || Ty->getBitWidth() % 16 != 0)
20869 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20870 SmallVector<StringRef, 4> AsmPieces;
20871 SplitString(AsmStr, AsmPieces, ";\n");
20873 switch (AsmPieces.size()) {
20874 default: return false;
20876 // FIXME: this should verify that we are targeting a 486 or better. If not,
20877 // we will turn this bswap into something that will be lowered to logical
20878 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20879 // lower so don't worry about this.
20881 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20882 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20883 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20884 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20885 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20886 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20887 // No need to check constraints, nothing other than the equivalent of
20888 // "=r,0" would be valid here.
20889 return IntrinsicLowering::LowerToByteSwap(CI);
20892 // rorw $$8, ${0:w} --> llvm.bswap.i16
20893 if (CI->getType()->isIntegerTy(16) &&
20894 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20895 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20896 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20898 const std::string &ConstraintsStr = IA->getConstraintString();
20899 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20900 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20901 if (clobbersFlagRegisters(AsmPieces))
20902 return IntrinsicLowering::LowerToByteSwap(CI);
20906 if (CI->getType()->isIntegerTy(32) &&
20907 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20908 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20909 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20910 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20912 const std::string &ConstraintsStr = IA->getConstraintString();
20913 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20914 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20915 if (clobbersFlagRegisters(AsmPieces))
20916 return IntrinsicLowering::LowerToByteSwap(CI);
20919 if (CI->getType()->isIntegerTy(64)) {
20920 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20921 if (Constraints.size() >= 2 &&
20922 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20923 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20924 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20925 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20926 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20927 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20928 return IntrinsicLowering::LowerToByteSwap(CI);
20936 /// getConstraintType - Given a constraint letter, return the type of
20937 /// constraint it is for this target.
20938 X86TargetLowering::ConstraintType
20939 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20940 if (Constraint.size() == 1) {
20941 switch (Constraint[0]) {
20952 return C_RegisterClass;
20976 return TargetLowering::getConstraintType(Constraint);
20979 /// Examine constraint type and operand type and determine a weight value.
20980 /// This object must already have been set up with the operand type
20981 /// and the current alternative constraint selected.
20982 TargetLowering::ConstraintWeight
20983 X86TargetLowering::getSingleConstraintMatchWeight(
20984 AsmOperandInfo &info, const char *constraint) const {
20985 ConstraintWeight weight = CW_Invalid;
20986 Value *CallOperandVal = info.CallOperandVal;
20987 // If we don't have a value, we can't do a match,
20988 // but allow it at the lowest weight.
20989 if (!CallOperandVal)
20991 Type *type = CallOperandVal->getType();
20992 // Look at the constraint type.
20993 switch (*constraint) {
20995 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21006 if (CallOperandVal->getType()->isIntegerTy())
21007 weight = CW_SpecificReg;
21012 if (type->isFloatingPointTy())
21013 weight = CW_SpecificReg;
21016 if (type->isX86_MMXTy() && Subtarget->hasMMX())
21017 weight = CW_SpecificReg;
21021 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21022 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21023 weight = CW_Register;
21026 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21027 if (C->getZExtValue() <= 31)
21028 weight = CW_Constant;
21032 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21033 if (C->getZExtValue() <= 63)
21034 weight = CW_Constant;
21038 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21039 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21040 weight = CW_Constant;
21044 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21045 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21046 weight = CW_Constant;
21050 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21051 if (C->getZExtValue() <= 3)
21052 weight = CW_Constant;
21056 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21057 if (C->getZExtValue() <= 0xff)
21058 weight = CW_Constant;
21063 if (dyn_cast<ConstantFP>(CallOperandVal)) {
21064 weight = CW_Constant;
21068 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21069 if ((C->getSExtValue() >= -0x80000000LL) &&
21070 (C->getSExtValue() <= 0x7fffffffLL))
21071 weight = CW_Constant;
21075 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21076 if (C->getZExtValue() <= 0xffffffff)
21077 weight = CW_Constant;
21084 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21085 /// with another that has more specific requirements based on the type of the
21086 /// corresponding operand.
21087 const char *X86TargetLowering::
21088 LowerXConstraint(EVT ConstraintVT) const {
21089 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21090 // 'f' like normal targets.
21091 if (ConstraintVT.isFloatingPoint()) {
21092 if (Subtarget->hasSSE2())
21094 if (Subtarget->hasSSE1())
21098 return TargetLowering::LowerXConstraint(ConstraintVT);
21101 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21102 /// vector. If it is invalid, don't add anything to Ops.
21103 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21104 std::string &Constraint,
21105 std::vector<SDValue>&Ops,
21106 SelectionDAG &DAG) const {
21109 // Only support length 1 constraints for now.
21110 if (Constraint.length() > 1) return;
21112 char ConstraintLetter = Constraint[0];
21113 switch (ConstraintLetter) {
21116 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21117 if (C->getZExtValue() <= 31) {
21118 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21125 if (C->getZExtValue() <= 63) {
21126 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21133 if (isInt<8>(C->getSExtValue())) {
21134 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21141 if (C->getZExtValue() <= 255) {
21142 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21148 // 32-bit signed value
21149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21150 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21151 C->getSExtValue())) {
21152 // Widen to 64 bits here to get it sign extended.
21153 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21156 // FIXME gcc accepts some relocatable values here too, but only in certain
21157 // memory models; it's complicated.
21162 // 32-bit unsigned value
21163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21164 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21165 C->getZExtValue())) {
21166 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21170 // FIXME gcc accepts some relocatable values here too, but only in certain
21171 // memory models; it's complicated.
21175 // Literal immediates are always ok.
21176 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21177 // Widen to 64 bits here to get it sign extended.
21178 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21182 // In any sort of PIC mode addresses need to be computed at runtime by
21183 // adding in a register or some sort of table lookup. These can't
21184 // be used as immediates.
21185 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21188 // If we are in non-pic codegen mode, we allow the address of a global (with
21189 // an optional displacement) to be used with 'i'.
21190 GlobalAddressSDNode *GA = nullptr;
21191 int64_t Offset = 0;
21193 // Match either (GA), (GA+C), (GA+C1+C2), etc.
21195 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21196 Offset += GA->getOffset();
21198 } else if (Op.getOpcode() == ISD::ADD) {
21199 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21200 Offset += C->getZExtValue();
21201 Op = Op.getOperand(0);
21204 } else if (Op.getOpcode() == ISD::SUB) {
21205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21206 Offset += -C->getZExtValue();
21207 Op = Op.getOperand(0);
21212 // Otherwise, this isn't something we can handle, reject it.
21216 const GlobalValue *GV = GA->getGlobal();
21217 // If we require an extra load to get this address, as in PIC mode, we
21218 // can't accept it.
21219 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21220 getTargetMachine())))
21223 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21224 GA->getValueType(0), Offset);
21229 if (Result.getNode()) {
21230 Ops.push_back(Result);
21233 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21236 std::pair<unsigned, const TargetRegisterClass*>
21237 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21239 // First, see if this is a constraint that directly corresponds to an LLVM
21241 if (Constraint.size() == 1) {
21242 // GCC Constraint Letters
21243 switch (Constraint[0]) {
21245 // TODO: Slight differences here in allocation order and leaving
21246 // RIP in the class. Do they matter any more here than they do
21247 // in the normal allocation?
21248 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21249 if (Subtarget->is64Bit()) {
21250 if (VT == MVT::i32 || VT == MVT::f32)
21251 return std::make_pair(0U, &X86::GR32RegClass);
21252 if (VT == MVT::i16)
21253 return std::make_pair(0U, &X86::GR16RegClass);
21254 if (VT == MVT::i8 || VT == MVT::i1)
21255 return std::make_pair(0U, &X86::GR8RegClass);
21256 if (VT == MVT::i64 || VT == MVT::f64)
21257 return std::make_pair(0U, &X86::GR64RegClass);
21260 // 32-bit fallthrough
21261 case 'Q': // Q_REGS
21262 if (VT == MVT::i32 || VT == MVT::f32)
21263 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21264 if (VT == MVT::i16)
21265 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21266 if (VT == MVT::i8 || VT == MVT::i1)
21267 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21268 if (VT == MVT::i64)
21269 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21271 case 'r': // GENERAL_REGS
21272 case 'l': // INDEX_REGS
21273 if (VT == MVT::i8 || VT == MVT::i1)
21274 return std::make_pair(0U, &X86::GR8RegClass);
21275 if (VT == MVT::i16)
21276 return std::make_pair(0U, &X86::GR16RegClass);
21277 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21278 return std::make_pair(0U, &X86::GR32RegClass);
21279 return std::make_pair(0U, &X86::GR64RegClass);
21280 case 'R': // LEGACY_REGS
21281 if (VT == MVT::i8 || VT == MVT::i1)
21282 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21283 if (VT == MVT::i16)
21284 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21285 if (VT == MVT::i32 || !Subtarget->is64Bit())
21286 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21287 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21288 case 'f': // FP Stack registers.
21289 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21290 // value to the correct fpstack register class.
21291 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21292 return std::make_pair(0U, &X86::RFP32RegClass);
21293 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21294 return std::make_pair(0U, &X86::RFP64RegClass);
21295 return std::make_pair(0U, &X86::RFP80RegClass);
21296 case 'y': // MMX_REGS if MMX allowed.
21297 if (!Subtarget->hasMMX()) break;
21298 return std::make_pair(0U, &X86::VR64RegClass);
21299 case 'Y': // SSE_REGS if SSE2 allowed
21300 if (!Subtarget->hasSSE2()) break;
21302 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21303 if (!Subtarget->hasSSE1()) break;
21305 switch (VT.SimpleTy) {
21307 // Scalar SSE types.
21310 return std::make_pair(0U, &X86::FR32RegClass);
21313 return std::make_pair(0U, &X86::FR64RegClass);
21321 return std::make_pair(0U, &X86::VR128RegClass);
21329 return std::make_pair(0U, &X86::VR256RegClass);
21334 return std::make_pair(0U, &X86::VR512RegClass);
21340 // Use the default implementation in TargetLowering to convert the register
21341 // constraint into a member of a register class.
21342 std::pair<unsigned, const TargetRegisterClass*> Res;
21343 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21345 // Not found as a standard register?
21347 // Map st(0) -> st(7) -> ST0
21348 if (Constraint.size() == 7 && Constraint[0] == '{' &&
21349 tolower(Constraint[1]) == 's' &&
21350 tolower(Constraint[2]) == 't' &&
21351 Constraint[3] == '(' &&
21352 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21353 Constraint[5] == ')' &&
21354 Constraint[6] == '}') {
21356 Res.first = X86::ST0+Constraint[4]-'0';
21357 Res.second = &X86::RFP80RegClass;
21361 // GCC allows "st(0)" to be called just plain "st".
21362 if (StringRef("{st}").equals_lower(Constraint)) {
21363 Res.first = X86::ST0;
21364 Res.second = &X86::RFP80RegClass;
21369 if (StringRef("{flags}").equals_lower(Constraint)) {
21370 Res.first = X86::EFLAGS;
21371 Res.second = &X86::CCRRegClass;
21375 // 'A' means EAX + EDX.
21376 if (Constraint == "A") {
21377 Res.first = X86::EAX;
21378 Res.second = &X86::GR32_ADRegClass;
21384 // Otherwise, check to see if this is a register class of the wrong value
21385 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21386 // turn into {ax},{dx}.
21387 if (Res.second->hasType(VT))
21388 return Res; // Correct type already, nothing to do.
21390 // All of the single-register GCC register classes map their values onto
21391 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
21392 // really want an 8-bit or 32-bit register, map to the appropriate register
21393 // class and return the appropriate register.
21394 if (Res.second == &X86::GR16RegClass) {
21395 if (VT == MVT::i8 || VT == MVT::i1) {
21396 unsigned DestReg = 0;
21397 switch (Res.first) {
21399 case X86::AX: DestReg = X86::AL; break;
21400 case X86::DX: DestReg = X86::DL; break;
21401 case X86::CX: DestReg = X86::CL; break;
21402 case X86::BX: DestReg = X86::BL; break;
21405 Res.first = DestReg;
21406 Res.second = &X86::GR8RegClass;
21408 } else if (VT == MVT::i32 || VT == MVT::f32) {
21409 unsigned DestReg = 0;
21410 switch (Res.first) {
21412 case X86::AX: DestReg = X86::EAX; break;
21413 case X86::DX: DestReg = X86::EDX; break;
21414 case X86::CX: DestReg = X86::ECX; break;
21415 case X86::BX: DestReg = X86::EBX; break;
21416 case X86::SI: DestReg = X86::ESI; break;
21417 case X86::DI: DestReg = X86::EDI; break;
21418 case X86::BP: DestReg = X86::EBP; break;
21419 case X86::SP: DestReg = X86::ESP; break;
21422 Res.first = DestReg;
21423 Res.second = &X86::GR32RegClass;
21425 } else if (VT == MVT::i64 || VT == MVT::f64) {
21426 unsigned DestReg = 0;
21427 switch (Res.first) {
21429 case X86::AX: DestReg = X86::RAX; break;
21430 case X86::DX: DestReg = X86::RDX; break;
21431 case X86::CX: DestReg = X86::RCX; break;
21432 case X86::BX: DestReg = X86::RBX; break;
21433 case X86::SI: DestReg = X86::RSI; break;
21434 case X86::DI: DestReg = X86::RDI; break;
21435 case X86::BP: DestReg = X86::RBP; break;
21436 case X86::SP: DestReg = X86::RSP; break;
21439 Res.first = DestReg;
21440 Res.second = &X86::GR64RegClass;
21443 } else if (Res.second == &X86::FR32RegClass ||
21444 Res.second == &X86::FR64RegClass ||
21445 Res.second == &X86::VR128RegClass ||
21446 Res.second == &X86::VR256RegClass ||
21447 Res.second == &X86::FR32XRegClass ||
21448 Res.second == &X86::FR64XRegClass ||
21449 Res.second == &X86::VR128XRegClass ||
21450 Res.second == &X86::VR256XRegClass ||
21451 Res.second == &X86::VR512RegClass) {
21452 // Handle references to XMM physical registers that got mapped into the
21453 // wrong class. This can happen with constraints like {xmm0} where the
21454 // target independent register mapper will just pick the first match it can
21455 // find, ignoring the required type.
21457 if (VT == MVT::f32 || VT == MVT::i32)
21458 Res.second = &X86::FR32RegClass;
21459 else if (VT == MVT::f64 || VT == MVT::i64)
21460 Res.second = &X86::FR64RegClass;
21461 else if (X86::VR128RegClass.hasType(VT))
21462 Res.second = &X86::VR128RegClass;
21463 else if (X86::VR256RegClass.hasType(VT))
21464 Res.second = &X86::VR256RegClass;
21465 else if (X86::VR512RegClass.hasType(VT))
21466 Res.second = &X86::VR512RegClass;
21472 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21474 // Scaling factors are not free at all.
21475 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21476 // will take 2 allocations in the out of order engine instead of 1
21477 // for plain addressing mode, i.e. inst (reg1).
21479 // vaddps (%rsi,%drx), %ymm0, %ymm1
21480 // Requires two allocations (one for the load, one for the computation)
21482 // vaddps (%rsi), %ymm0, %ymm1
21483 // Requires just 1 allocation, i.e., freeing allocations for other operations
21484 // and having less micro operations to execute.
21486 // For some X86 architectures, this is even worse because for instance for
21487 // stores, the complex addressing mode forces the instruction to use the
21488 // "load" ports instead of the dedicated "store" port.
21489 // E.g., on Haswell:
21490 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21491 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
21492 if (isLegalAddressingMode(AM, Ty))
21493 // Scale represents reg2 * scale, thus account for 1
21494 // as soon as we use a second register.
21495 return AM.Scale != 0;