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 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
19 #include "X86CallingConv.h"
20 #include "X86InstrBuilder.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.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 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62 SelectionDAG &DAG, SDLoc dl,
63 unsigned vectorWidth) {
64 assert((vectorWidth == 128 || vectorWidth == 256) &&
65 "Unsupported vector width");
66 EVT VT = Vec.getValueType();
67 EVT ElVT = VT.getVectorElementType();
68 unsigned Factor = VT.getSizeInBits()/vectorWidth;
69 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70 VT.getVectorNumElements()/Factor);
72 // Extract from UNDEF is UNDEF.
73 if (Vec.getOpcode() == ISD::UNDEF)
74 return DAG.getUNDEF(ResultVT);
76 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
77 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79 // This is the index of the first element of the vectorWidth-bit chunk
81 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84 // If the input is a buildvector just emit a smaller one.
85 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103 SelectionDAG &DAG, SDLoc dl) {
104 assert((Vec.getValueType().is256BitVector() ||
105 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111 SelectionDAG &DAG, SDLoc dl) {
112 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117 unsigned IdxVal, SelectionDAG &DAG,
118 SDLoc dl, unsigned vectorWidth) {
119 assert((vectorWidth == 128 || vectorWidth == 256) &&
120 "Unsupported vector width");
121 // Inserting UNDEF is Result
122 if (Vec.getOpcode() == ISD::UNDEF)
124 EVT VT = Vec.getValueType();
125 EVT ElVT = VT.getVectorElementType();
126 EVT ResultVT = Result.getValueType();
128 // Insert the relevant vectorWidth bits.
129 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131 // This is the index of the first element of the vectorWidth-bit chunk
133 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
136 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
140 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference. Idx is an index in the 128 bits
144 /// we want. It need not be aligned to a 128-bit bounday. That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147 unsigned IdxVal, SelectionDAG &DAG,
149 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154 unsigned IdxVal, SelectionDAG &DAG,
156 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165 unsigned NumElems, SelectionDAG &DAG,
167 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172 unsigned NumElems, SelectionDAG &DAG,
174 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180 bool is64Bit = Subtarget->is64Bit();
182 if (Subtarget->isTargetMacho()) {
184 return new X86_64MachoTargetObjectFile();
185 return new TargetLoweringObjectFileMachO();
188 if (Subtarget->isTargetLinux())
189 return new X86LinuxTargetObjectFile();
190 if (Subtarget->isTargetELF())
191 return new TargetLoweringObjectFileELF();
192 if (Subtarget->isTargetWindows())
193 return new X86WindowsTargetObjectFile();
194 if (Subtarget->isTargetCOFF())
195 return new TargetLoweringObjectFileCOFF();
196 llvm_unreachable("unknown subtarget type");
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200 : TargetLowering(TM, createTLOF(TM)) {
201 Subtarget = &TM.getSubtarget<X86Subtarget>();
202 X86ScalarSSEf64 = Subtarget->hasSSE2();
203 X86ScalarSSEf32 = Subtarget->hasSSE1();
204 TD = getDataLayout();
206 resetOperationActions();
209 void X86TargetLowering::resetOperationActions() {
210 const TargetMachine &TM = getTargetMachine();
211 static bool FirstTimeThrough = true;
213 // If none of the target options have changed, then we don't need to reset the
214 // operation actions.
215 if (!FirstTimeThrough && TO == TM.Options) return;
217 if (!FirstTimeThrough) {
218 // Reinitialize the actions.
220 FirstTimeThrough = false;
225 // Set up the TargetLowering object.
226 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228 // X86 is weird, it always uses i8 for shift amounts and setcc results.
229 setBooleanContents(ZeroOrOneBooleanContent);
230 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233 // For 64-bit since we have so many registers use the ILP scheduler, for
234 // 32-bit code use the register pressure specific scheduling.
235 // For Atom, always use ILP scheduling.
236 if (Subtarget->isAtom())
237 setSchedulingPreference(Sched::ILP);
238 else if (Subtarget->is64Bit())
239 setSchedulingPreference(Sched::ILP);
241 setSchedulingPreference(Sched::RegPressure);
242 const X86RegisterInfo *RegInfo =
243 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246 // Bypass expensive divides on Atom when compiling with O2
247 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248 addBypassSlowDiv(32, 8);
249 if (Subtarget->is64Bit())
250 addBypassSlowDiv(64, 16);
253 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
254 // Setup Windows compiler runtime calls.
255 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257 setLibcallName(RTLIB::SREM_I64, "_allrem");
258 setLibcallName(RTLIB::UREM_I64, "_aullrem");
259 setLibcallName(RTLIB::MUL_I64, "_allmul");
260 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266 // The _ftol2 runtime function has an unusual calling conv, which
267 // is modeled by a special pseudo-instruction.
268 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
269 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
270 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
271 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
274 if (Subtarget->isTargetDarwin()) {
275 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276 setUseUnderscoreSetJmp(false);
277 setUseUnderscoreLongJmp(false);
278 } else if (Subtarget->isTargetMingw()) {
279 // MS runtime is weird: it exports _setjmp, but longjmp!
280 setUseUnderscoreSetJmp(true);
281 setUseUnderscoreLongJmp(false);
283 setUseUnderscoreSetJmp(true);
284 setUseUnderscoreLongJmp(true);
287 // Set up the register classes.
288 addRegisterClass(MVT::i8, &X86::GR8RegClass);
289 addRegisterClass(MVT::i16, &X86::GR16RegClass);
290 addRegisterClass(MVT::i32, &X86::GR32RegClass);
291 if (Subtarget->is64Bit())
292 addRegisterClass(MVT::i64, &X86::GR64RegClass);
294 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296 // We don't accept any truncstore of integer registers.
297 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
304 // SETOEQ and SETUNE require checking two conditions.
305 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
315 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
318 if (Subtarget->is64Bit()) {
319 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
320 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
321 } else if (!TM.Options.UseSoftFloat) {
322 // We have an algorithm for SSE2->double, and we turn this into a
323 // 64-bit FILD followed by conditional FADD for other targets.
324 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
325 // We have an algorithm for SSE2, and we turn this into a 64-bit
326 // FILD for other targets.
327 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
330 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
333 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
335 if (!TM.Options.UseSoftFloat) {
336 // SSE has no i16 to fp conversion, only i32
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
346 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
350 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
351 // are Legal, f80 is custom lowered.
352 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
353 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
355 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
358 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
360 if (X86ScalarSSEf32) {
361 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
362 // f32 and f64 cases are Legal, f80 case is not
363 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
365 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
369 // Handle FP_TO_UINT by promoting the destination to a larger signed
371 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
372 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
375 if (Subtarget->is64Bit()) {
376 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
377 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
378 } else if (!TM.Options.UseSoftFloat) {
379 // Since AVX is a superset of SSE3, only check for SSE here.
380 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381 // Expand FP_TO_UINT into a select.
382 // FIXME: We would like to use a Custom expander here eventually to do
383 // the optimal thing for SSE vs. the default expansion in the legalizer.
384 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
386 // With SSE3 we can use fisttpll to convert to a signed i64; without
387 // SSE, we're stuck with a fistpll.
388 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
391 if (isTargetFTOL()) {
392 // Use the _ftol2 runtime function, which has a pseudo-instruction
393 // to handle its weird calling convention.
394 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
397 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398 if (!X86ScalarSSEf64) {
399 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
400 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
401 if (Subtarget->is64Bit()) {
402 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
403 // Without SSE, i64->f64 goes through memory.
404 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
408 // Scalar integer divide and remainder are lowered to use operations that
409 // produce two results, to match the available instructions. This exposes
410 // the two-result form to trivial CSE, which is able to combine x/y and x%y
411 // into a single instruction.
413 // Scalar integer multiply-high is also lowered to use two-result
414 // operations, to match the available instructions. However, plain multiply
415 // (low) operations are left as Legal, as there are single-result
416 // instructions for this in x86. Using the two-result multiply instructions
417 // when both high and low results are needed must be arranged by dagcombine.
418 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420 setOperationAction(ISD::MULHS, VT, Expand);
421 setOperationAction(ISD::MULHU, VT, Expand);
422 setOperationAction(ISD::SDIV, VT, Expand);
423 setOperationAction(ISD::UDIV, VT, Expand);
424 setOperationAction(ISD::SREM, VT, Expand);
425 setOperationAction(ISD::UREM, VT, Expand);
427 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428 setOperationAction(ISD::ADDC, VT, Custom);
429 setOperationAction(ISD::ADDE, VT, Custom);
430 setOperationAction(ISD::SUBC, VT, Custom);
431 setOperationAction(ISD::SUBE, VT, Custom);
434 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
435 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
436 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
437 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
439 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
443 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
444 if (Subtarget->is64Bit())
445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
449 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
450 setOperationAction(ISD::FREM , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f64 , Expand);
452 setOperationAction(ISD::FREM , MVT::f80 , Expand);
453 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
455 // Promote the i8 variants and force them on up to i32 which has a shorter
457 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
458 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
459 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
461 if (Subtarget->hasBMI()) {
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
468 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
469 if (Subtarget->is64Bit())
470 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
473 if (Subtarget->hasLZCNT()) {
474 // When promoting the i8 variants, force them to i32 for a shorter
476 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
477 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
482 if (Subtarget->is64Bit())
483 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
486 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
491 if (Subtarget->is64Bit()) {
492 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497 if (Subtarget->hasPOPCNT()) {
498 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
500 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
501 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
507 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
509 if (!Subtarget->hasMOVBE())
510 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
512 // These should be promoted to a larger select which is supported.
513 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
514 // X86 wants to expand cmov itself.
515 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
516 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
518 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
521 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
524 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
527 if (Subtarget->is64Bit()) {
528 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
529 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
531 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
532 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534 // support continuation, user-level threading, and etc.. As a result, no
535 // other SjLj exception interfaces are implemented and please don't build
536 // your own exception handling based on them.
537 // LLVM/Clang supports zero-cost DWARF exception handling.
538 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
542 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
543 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
544 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
546 if (Subtarget->is64Bit())
547 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
549 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
550 if (Subtarget->is64Bit()) {
551 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
552 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
553 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
554 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
555 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
557 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
559 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
561 if (Subtarget->is64Bit()) {
562 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
567 if (Subtarget->hasSSE1())
568 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
570 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
572 // Expand certain atomics
573 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
580 if (!Subtarget->is64Bit()) {
581 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
595 if (Subtarget->hasCmpxchg16b()) {
596 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
599 // FIXME - use subtarget debug flags
600 if (!Subtarget->isTargetDarwin() &&
601 !Subtarget->isTargetELF() &&
602 !Subtarget->isTargetCygMing()) {
603 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
606 if (Subtarget->is64Bit()) {
607 setExceptionPointerRegister(X86::RAX);
608 setExceptionSelectorRegister(X86::RDX);
610 setExceptionPointerRegister(X86::EAX);
611 setExceptionSelectorRegister(X86::EDX);
613 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619 setOperationAction(ISD::TRAP, MVT::Other, Legal);
620 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623 setOperationAction(ISD::VASTART , MVT::Other, Custom);
624 setOperationAction(ISD::VAEND , MVT::Other, Expand);
625 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626 // TargetInfo::X86_64ABIBuiltinVaList
627 setOperationAction(ISD::VAARG , MVT::Other, Custom);
628 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
630 // TargetInfo::CharPtrBuiltinVaList
631 setOperationAction(ISD::VAARG , MVT::Other, Expand);
632 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
635 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
636 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
638 if (Subtarget->isOSWindows() && !Subtarget->isTargetMacho())
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
641 else if (TM.Options.EnableSegmentedStacks)
642 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
643 MVT::i64 : MVT::i32, Custom);
645 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
646 MVT::i64 : MVT::i32, Expand);
648 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
649 // f32 and f64 use SSE.
650 // Set up the FP register classes.
651 addRegisterClass(MVT::f32, &X86::FR32RegClass);
652 addRegisterClass(MVT::f64, &X86::FR64RegClass);
654 // Use ANDPD to simulate FABS.
655 setOperationAction(ISD::FABS , MVT::f64, Custom);
656 setOperationAction(ISD::FABS , MVT::f32, Custom);
658 // Use XORP to simulate FNEG.
659 setOperationAction(ISD::FNEG , MVT::f64, Custom);
660 setOperationAction(ISD::FNEG , MVT::f32, Custom);
662 // Use ANDPD and ORPD to simulate FCOPYSIGN.
663 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
664 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
666 // Lower this to FGETSIGNx86 plus an AND.
667 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
668 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
670 // We don't support sin/cos/fmod
671 setOperationAction(ISD::FSIN , MVT::f64, Expand);
672 setOperationAction(ISD::FCOS , MVT::f64, Expand);
673 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674 setOperationAction(ISD::FSIN , MVT::f32, Expand);
675 setOperationAction(ISD::FCOS , MVT::f32, Expand);
676 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
678 // Expand FP immediates into loads from the stack, except for the special
680 addLegalFPImmediate(APFloat(+0.0)); // xorpd
681 addLegalFPImmediate(APFloat(+0.0f)); // xorps
682 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
683 // Use SSE for f32, x87 for f64.
684 // Set up the FP register classes.
685 addRegisterClass(MVT::f32, &X86::FR32RegClass);
686 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
688 // Use ANDPS to simulate FABS.
689 setOperationAction(ISD::FABS , MVT::f32, Custom);
691 // Use XORP to simulate FNEG.
692 setOperationAction(ISD::FNEG , MVT::f32, Custom);
694 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
696 // Use ANDPS and ORPS to simulate FCOPYSIGN.
697 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
698 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
700 // We don't support sin/cos/fmod
701 setOperationAction(ISD::FSIN , MVT::f32, Expand);
702 setOperationAction(ISD::FCOS , MVT::f32, Expand);
703 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
705 // Special cases we handle for FP constants.
706 addLegalFPImmediate(APFloat(+0.0f)); // xorps
707 addLegalFPImmediate(APFloat(+0.0)); // FLD0
708 addLegalFPImmediate(APFloat(+1.0)); // FLD1
709 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
710 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
712 if (!TM.Options.UnsafeFPMath) {
713 setOperationAction(ISD::FSIN , MVT::f64, Expand);
714 setOperationAction(ISD::FCOS , MVT::f64, Expand);
715 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
717 } else if (!TM.Options.UseSoftFloat) {
718 // f32 and f64 in x87.
719 // Set up the FP register classes.
720 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
721 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
723 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
724 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
725 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
726 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
728 if (!TM.Options.UnsafeFPMath) {
729 setOperationAction(ISD::FSIN , MVT::f64, Expand);
730 setOperationAction(ISD::FSIN , MVT::f32, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FCOS , MVT::f32, Expand);
733 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
736 addLegalFPImmediate(APFloat(+0.0)); // FLD0
737 addLegalFPImmediate(APFloat(+1.0)); // FLD1
738 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
739 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
740 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
741 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
742 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
743 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
746 // We don't support FMA.
747 setOperationAction(ISD::FMA, MVT::f64, Expand);
748 setOperationAction(ISD::FMA, MVT::f32, Expand);
750 // Long double always uses X87.
751 if (!TM.Options.UseSoftFloat) {
752 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
753 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
754 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
756 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
757 addLegalFPImmediate(TmpFlt); // FLD0
759 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
762 APFloat TmpFlt2(+1.0);
763 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
765 addLegalFPImmediate(TmpFlt2); // FLD1
766 TmpFlt2.changeSign();
767 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
770 if (!TM.Options.UnsafeFPMath) {
771 setOperationAction(ISD::FSIN , MVT::f80, Expand);
772 setOperationAction(ISD::FCOS , MVT::f80, Expand);
773 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
776 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
777 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
778 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
779 setOperationAction(ISD::FRINT, MVT::f80, Expand);
780 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
781 setOperationAction(ISD::FMA, MVT::f80, Expand);
784 // Always use a library call for pow.
785 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
786 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
787 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
789 setOperationAction(ISD::FLOG, MVT::f80, Expand);
790 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
791 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
792 setOperationAction(ISD::FEXP, MVT::f80, Expand);
793 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
795 // First set operation action for all vector types to either promote
796 // (for widening) or expand (for scalarization). Then we will selectively
797 // turn on ones that can be effectively codegen'd.
798 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
799 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
800 MVT VT = (MVT::SimpleValueType)i;
801 setOperationAction(ISD::ADD , VT, Expand);
802 setOperationAction(ISD::SUB , VT, Expand);
803 setOperationAction(ISD::FADD, VT, Expand);
804 setOperationAction(ISD::FNEG, VT, Expand);
805 setOperationAction(ISD::FSUB, VT, Expand);
806 setOperationAction(ISD::MUL , VT, Expand);
807 setOperationAction(ISD::FMUL, VT, Expand);
808 setOperationAction(ISD::SDIV, VT, Expand);
809 setOperationAction(ISD::UDIV, VT, Expand);
810 setOperationAction(ISD::FDIV, VT, Expand);
811 setOperationAction(ISD::SREM, VT, Expand);
812 setOperationAction(ISD::UREM, VT, Expand);
813 setOperationAction(ISD::LOAD, VT, Expand);
814 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
815 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
818 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
819 setOperationAction(ISD::FABS, VT, Expand);
820 setOperationAction(ISD::FSIN, VT, Expand);
821 setOperationAction(ISD::FSINCOS, VT, Expand);
822 setOperationAction(ISD::FCOS, VT, Expand);
823 setOperationAction(ISD::FSINCOS, VT, Expand);
824 setOperationAction(ISD::FREM, VT, Expand);
825 setOperationAction(ISD::FMA, VT, Expand);
826 setOperationAction(ISD::FPOWI, VT, Expand);
827 setOperationAction(ISD::FSQRT, VT, Expand);
828 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
829 setOperationAction(ISD::FFLOOR, VT, Expand);
830 setOperationAction(ISD::FCEIL, VT, Expand);
831 setOperationAction(ISD::FTRUNC, VT, Expand);
832 setOperationAction(ISD::FRINT, VT, Expand);
833 setOperationAction(ISD::FNEARBYINT, VT, Expand);
834 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
835 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::SDIVREM, VT, Expand);
837 setOperationAction(ISD::UDIVREM, VT, Expand);
838 setOperationAction(ISD::FPOW, VT, Expand);
839 setOperationAction(ISD::CTPOP, VT, Expand);
840 setOperationAction(ISD::CTTZ, VT, Expand);
841 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
842 setOperationAction(ISD::CTLZ, VT, Expand);
843 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
844 setOperationAction(ISD::SHL, VT, Expand);
845 setOperationAction(ISD::SRA, VT, Expand);
846 setOperationAction(ISD::SRL, VT, Expand);
847 setOperationAction(ISD::ROTL, VT, Expand);
848 setOperationAction(ISD::ROTR, VT, Expand);
849 setOperationAction(ISD::BSWAP, VT, Expand);
850 setOperationAction(ISD::SETCC, VT, Expand);
851 setOperationAction(ISD::FLOG, VT, Expand);
852 setOperationAction(ISD::FLOG2, VT, Expand);
853 setOperationAction(ISD::FLOG10, VT, Expand);
854 setOperationAction(ISD::FEXP, VT, Expand);
855 setOperationAction(ISD::FEXP2, VT, Expand);
856 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
857 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
858 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
859 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
860 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
861 setOperationAction(ISD::TRUNCATE, VT, Expand);
862 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
863 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
864 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
865 setOperationAction(ISD::VSELECT, VT, Expand);
866 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
867 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
868 setTruncStoreAction(VT,
869 (MVT::SimpleValueType)InnerVT, Expand);
870 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
871 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
872 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
875 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
876 // with -msoft-float, disable use of MMX as well.
877 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
878 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
879 // No operations on x86mmx supported, everything uses intrinsics.
882 // MMX-sized vectors (other than x86mmx) are expected to be expanded
883 // into smaller operations.
884 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
885 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
886 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
887 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
888 setOperationAction(ISD::AND, MVT::v8i8, Expand);
889 setOperationAction(ISD::AND, MVT::v4i16, Expand);
890 setOperationAction(ISD::AND, MVT::v2i32, Expand);
891 setOperationAction(ISD::AND, MVT::v1i64, Expand);
892 setOperationAction(ISD::OR, MVT::v8i8, Expand);
893 setOperationAction(ISD::OR, MVT::v4i16, Expand);
894 setOperationAction(ISD::OR, MVT::v2i32, Expand);
895 setOperationAction(ISD::OR, MVT::v1i64, Expand);
896 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
901 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
902 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
903 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
905 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
906 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
907 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
908 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
909 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
910 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
911 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
912 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
914 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
915 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
917 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
918 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
919 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
920 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
921 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
922 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
923 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
924 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
925 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
926 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
927 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
928 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
931 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
932 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
934 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
935 // registers cannot be used even for integer operations.
936 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
937 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
938 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
939 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
941 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
942 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
943 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
944 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
945 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
946 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
947 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
948 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
949 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
950 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
951 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
952 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
953 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
954 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
955 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
956 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
957 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
958 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
961 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
962 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
963 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
966 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
971 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
972 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
973 MVT VT = (MVT::SimpleValueType)i;
974 // Do not attempt to custom lower non-power-of-2 vectors
975 if (!isPowerOf2_32(VT.getVectorNumElements()))
977 // Do not attempt to custom lower non-128-bit vectors
978 if (!VT.is128BitVector())
980 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
981 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
982 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
986 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
992 if (Subtarget->is64Bit()) {
993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
997 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
998 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
999 MVT VT = (MVT::SimpleValueType)i;
1001 // Do not attempt to promote non-128-bit vectors
1002 if (!VT.is128BitVector())
1005 setOperationAction(ISD::AND, VT, Promote);
1006 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1007 setOperationAction(ISD::OR, VT, Promote);
1008 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1009 setOperationAction(ISD::XOR, VT, Promote);
1010 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1011 setOperationAction(ISD::LOAD, VT, Promote);
1012 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1013 setOperationAction(ISD::SELECT, VT, Promote);
1014 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1017 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1019 // Custom lower v2i64 and v2f64 selects.
1020 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1021 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1022 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1023 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1025 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1026 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1030 // As there is no 64-bit GPR available, we need build a special custom
1031 // sequence to convert from v2i32 to v2f32.
1032 if (!Subtarget->is64Bit())
1033 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1036 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1038 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1041 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1042 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1043 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1044 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1045 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1046 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1047 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1048 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1049 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1050 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1051 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1053 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1059 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1060 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1064 // FIXME: Do we need to handle scalar-to-vector here?
1065 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1073 // i8 and i16 vectors are custom , because the source register and source
1074 // source memory operand types are not the same width. f32 vectors are
1075 // custom since the immediate controlling the insert encodes additional
1077 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1078 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1079 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1080 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1082 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1084 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1087 // FIXME: these should be Legal but thats only for the case where
1088 // the index is constant. For now custom expand to deal with that.
1089 if (Subtarget->is64Bit()) {
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1095 if (Subtarget->hasSSE2()) {
1096 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1099 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1100 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1102 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1103 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1105 // In the customized shift lowering, the legal cases in AVX2 will be
1107 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1108 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1110 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1111 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1113 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1115 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1116 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1119 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1120 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1123 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1127 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1128 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1129 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1131 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1142 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1144 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1155 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1157 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1159 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1160 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1161 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1162 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1164 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1167 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1169 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1183 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1186 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1187 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1189 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1191 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1192 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1201 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1202 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1203 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1204 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1205 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1207 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1208 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1209 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1210 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1211 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1212 setOperationAction(ISD::FMA, MVT::f32, Legal);
1213 setOperationAction(ISD::FMA, MVT::f64, Legal);
1216 if (Subtarget->hasInt256()) {
1217 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1218 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1219 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1220 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1222 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1223 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1224 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1225 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1227 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1228 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1229 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1230 // Don't lower v32i8 because there is no 128-bit byte mul
1232 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1234 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1236 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1237 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1238 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1239 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1241 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1242 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1243 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1244 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1246 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1247 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1248 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1249 // Don't lower v32i8 because there is no 128-bit byte mul
1252 // In the customized shift lowering, the legal cases in AVX2 will be
1254 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1255 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1257 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1258 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1260 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1262 // Custom lower several nodes for 256-bit types.
1263 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1264 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1265 MVT VT = (MVT::SimpleValueType)i;
1267 // Extract subvector is special because the value type
1268 // (result) is 128-bit but the source is 256-bit wide.
1269 if (VT.is128BitVector())
1270 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1272 // Do not attempt to custom lower other non-256-bit vectors
1273 if (!VT.is256BitVector())
1276 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1277 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1278 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1279 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1280 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1281 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1282 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1285 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1286 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1287 MVT VT = (MVT::SimpleValueType)i;
1289 // Do not attempt to promote non-256-bit vectors
1290 if (!VT.is256BitVector())
1293 setOperationAction(ISD::AND, VT, Promote);
1294 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1295 setOperationAction(ISD::OR, VT, Promote);
1296 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1297 setOperationAction(ISD::XOR, VT, Promote);
1298 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1299 setOperationAction(ISD::LOAD, VT, Promote);
1300 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1301 setOperationAction(ISD::SELECT, VT, Promote);
1302 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1306 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1307 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1308 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1309 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1310 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1312 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1313 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1314 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1316 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1317 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1318 setOperationAction(ISD::XOR, MVT::i1, Legal);
1319 setOperationAction(ISD::OR, MVT::i1, Legal);
1320 setOperationAction(ISD::AND, MVT::i1, Legal);
1321 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1322 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1323 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1324 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1326 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1328 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1329 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1330 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1331 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1335 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1336 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1338 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1341 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1342 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1343 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1345 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1346 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1347 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1348 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1349 if (Subtarget->is64Bit()) {
1350 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1351 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1352 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1353 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1355 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1356 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1357 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1358 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1359 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1360 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1361 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1362 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1364 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1365 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1366 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1370 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1371 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1372 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1373 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1374 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1378 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1379 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1380 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1385 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1386 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1388 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1392 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1393 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1394 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1395 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1396 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1398 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1399 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1401 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1402 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1404 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1406 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1407 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1409 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1410 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1412 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1413 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1415 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1416 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1417 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1418 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1419 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1420 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1422 // Custom lower several nodes.
1423 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1424 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1425 MVT VT = (MVT::SimpleValueType)i;
1427 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1428 // Extract subvector is special because the value type
1429 // (result) is 256/128-bit but the source is 512-bit wide.
1430 if (VT.is128BitVector() || VT.is256BitVector())
1431 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1433 if (VT.getVectorElementType() == MVT::i1)
1434 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1436 // Do not attempt to custom lower other non-512-bit vectors
1437 if (!VT.is512BitVector())
1440 if ( EltSize >= 32) {
1441 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1442 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1443 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1444 setOperationAction(ISD::VSELECT, VT, Legal);
1445 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1446 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1447 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1450 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1451 MVT VT = (MVT::SimpleValueType)i;
1453 // Do not attempt to promote non-256-bit vectors
1454 if (!VT.is512BitVector())
1457 setOperationAction(ISD::SELECT, VT, Promote);
1458 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1462 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1463 // of this type with custom code.
1464 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1465 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1466 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1470 // We want to custom lower some of our intrinsics.
1471 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1472 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1473 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1475 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1476 // handle type legalization for these operations here.
1478 // FIXME: We really should do custom legalization for addition and
1479 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1480 // than generic legalization for 64-bit multiplication-with-overflow, though.
1481 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1482 // Add/Sub/Mul with overflow operations are custom lowered.
1484 setOperationAction(ISD::SADDO, VT, Custom);
1485 setOperationAction(ISD::UADDO, VT, Custom);
1486 setOperationAction(ISD::SSUBO, VT, Custom);
1487 setOperationAction(ISD::USUBO, VT, Custom);
1488 setOperationAction(ISD::SMULO, VT, Custom);
1489 setOperationAction(ISD::UMULO, VT, Custom);
1492 // There are no 8-bit 3-address imul/mul instructions
1493 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1494 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1496 if (!Subtarget->is64Bit()) {
1497 // These libcalls are not available in 32-bit.
1498 setLibcallName(RTLIB::SHL_I128, 0);
1499 setLibcallName(RTLIB::SRL_I128, 0);
1500 setLibcallName(RTLIB::SRA_I128, 0);
1503 // Combine sin / cos into one node or libcall if possible.
1504 if (Subtarget->hasSinCos()) {
1505 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1506 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1507 if (Subtarget->isTargetDarwin()) {
1508 // For MacOSX, we don't want to the normal expansion of a libcall to
1509 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1511 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1512 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1516 // We have target-specific dag combine patterns for the following nodes:
1517 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1518 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1519 setTargetDAGCombine(ISD::VSELECT);
1520 setTargetDAGCombine(ISD::SELECT);
1521 setTargetDAGCombine(ISD::SHL);
1522 setTargetDAGCombine(ISD::SRA);
1523 setTargetDAGCombine(ISD::SRL);
1524 setTargetDAGCombine(ISD::OR);
1525 setTargetDAGCombine(ISD::AND);
1526 setTargetDAGCombine(ISD::ADD);
1527 setTargetDAGCombine(ISD::FADD);
1528 setTargetDAGCombine(ISD::FSUB);
1529 setTargetDAGCombine(ISD::FMA);
1530 setTargetDAGCombine(ISD::SUB);
1531 setTargetDAGCombine(ISD::LOAD);
1532 setTargetDAGCombine(ISD::STORE);
1533 setTargetDAGCombine(ISD::ZERO_EXTEND);
1534 setTargetDAGCombine(ISD::ANY_EXTEND);
1535 setTargetDAGCombine(ISD::SIGN_EXTEND);
1536 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1537 setTargetDAGCombine(ISD::TRUNCATE);
1538 setTargetDAGCombine(ISD::SINT_TO_FP);
1539 setTargetDAGCombine(ISD::SETCC);
1540 if (Subtarget->is64Bit())
1541 setTargetDAGCombine(ISD::MUL);
1542 setTargetDAGCombine(ISD::XOR);
1544 computeRegisterProperties();
1546 // On Darwin, -Os means optimize for size without hurting performance,
1547 // do not reduce the limit.
1548 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1549 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1550 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1551 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1552 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1553 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1554 setPrefLoopAlignment(4); // 2^4 bytes.
1556 // Predictable cmov don't hurt on atom because it's in-order.
1557 PredictableSelectIsExpensive = !Subtarget->isAtom();
1559 setPrefFunctionAlignment(4); // 2^4 bytes.
1562 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1564 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1566 if (Subtarget->hasAVX512())
1567 switch(VT.getVectorNumElements()) {
1568 case 8: return MVT::v8i1;
1569 case 16: return MVT::v16i1;
1572 return VT.changeVectorElementTypeToInteger();
1575 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1576 /// the desired ByVal argument alignment.
1577 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1580 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1581 if (VTy->getBitWidth() == 128)
1583 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1584 unsigned EltAlign = 0;
1585 getMaxByValAlign(ATy->getElementType(), EltAlign);
1586 if (EltAlign > MaxAlign)
1587 MaxAlign = EltAlign;
1588 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1589 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1590 unsigned EltAlign = 0;
1591 getMaxByValAlign(STy->getElementType(i), EltAlign);
1592 if (EltAlign > MaxAlign)
1593 MaxAlign = EltAlign;
1600 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1601 /// function arguments in the caller parameter area. For X86, aggregates
1602 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1603 /// are at 4-byte boundaries.
1604 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1605 if (Subtarget->is64Bit()) {
1606 // Max of 8 and alignment of type.
1607 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1614 if (Subtarget->hasSSE1())
1615 getMaxByValAlign(Ty, Align);
1619 /// getOptimalMemOpType - Returns the target specific optimal type for load
1620 /// and store operations as a result of memset, memcpy, and memmove
1621 /// lowering. If DstAlign is zero that means it's safe to destination
1622 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1623 /// means there isn't a need to check it against alignment requirement,
1624 /// probably because the source does not need to be loaded. If 'IsMemset' is
1625 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1626 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1627 /// source is constant so it does not need to be loaded.
1628 /// It returns EVT::Other if the type should be determined using generic
1629 /// target-independent logic.
1631 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1632 unsigned DstAlign, unsigned SrcAlign,
1633 bool IsMemset, bool ZeroMemset,
1635 MachineFunction &MF) const {
1636 const Function *F = MF.getFunction();
1637 if ((!IsMemset || ZeroMemset) &&
1638 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1639 Attribute::NoImplicitFloat)) {
1641 (Subtarget->isUnalignedMemAccessFast() ||
1642 ((DstAlign == 0 || DstAlign >= 16) &&
1643 (SrcAlign == 0 || SrcAlign >= 16)))) {
1645 if (Subtarget->hasInt256())
1647 if (Subtarget->hasFp256())
1650 if (Subtarget->hasSSE2())
1652 if (Subtarget->hasSSE1())
1654 } else if (!MemcpyStrSrc && Size >= 8 &&
1655 !Subtarget->is64Bit() &&
1656 Subtarget->hasSSE2()) {
1657 // Do not use f64 to lower memcpy if source is string constant. It's
1658 // better to use i32 to avoid the loads.
1662 if (Subtarget->is64Bit() && Size >= 8)
1667 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1669 return X86ScalarSSEf32;
1670 else if (VT == MVT::f64)
1671 return X86ScalarSSEf64;
1676 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1680 *Fast = Subtarget->isUnalignedMemAccessFast();
1684 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1685 /// current function. The returned value is a member of the
1686 /// MachineJumpTableInfo::JTEntryKind enum.
1687 unsigned X86TargetLowering::getJumpTableEncoding() const {
1688 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1690 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1691 Subtarget->isPICStyleGOT())
1692 return MachineJumpTableInfo::EK_Custom32;
1694 // Otherwise, use the normal jump table encoding heuristics.
1695 return TargetLowering::getJumpTableEncoding();
1699 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1700 const MachineBasicBlock *MBB,
1701 unsigned uid,MCContext &Ctx) const{
1702 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1703 Subtarget->isPICStyleGOT());
1704 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1706 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1707 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1710 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1712 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1713 SelectionDAG &DAG) const {
1714 if (!Subtarget->is64Bit())
1715 // This doesn't have SDLoc associated with it, but is not really the
1716 // same as a Register.
1717 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1721 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1722 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1724 const MCExpr *X86TargetLowering::
1725 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1726 MCContext &Ctx) const {
1727 // X86-64 uses RIP relative addressing based on the jump table label.
1728 if (Subtarget->isPICStyleRIPRel())
1729 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1731 // Otherwise, the reference is relative to the PIC base.
1732 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1735 // FIXME: Why this routine is here? Move to RegInfo!
1736 std::pair<const TargetRegisterClass*, uint8_t>
1737 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1738 const TargetRegisterClass *RRC = 0;
1740 switch (VT.SimpleTy) {
1742 return TargetLowering::findRepresentativeClass(VT);
1743 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1744 RRC = Subtarget->is64Bit() ?
1745 (const TargetRegisterClass*)&X86::GR64RegClass :
1746 (const TargetRegisterClass*)&X86::GR32RegClass;
1749 RRC = &X86::VR64RegClass;
1751 case MVT::f32: case MVT::f64:
1752 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1753 case MVT::v4f32: case MVT::v2f64:
1754 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1756 RRC = &X86::VR128RegClass;
1759 return std::make_pair(RRC, Cost);
1762 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1763 unsigned &Offset) const {
1764 if (!Subtarget->isTargetLinux())
1767 if (Subtarget->is64Bit()) {
1768 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1770 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1782 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1783 unsigned DestAS) const {
1784 assert(SrcAS != DestAS && "Expected different address spaces!");
1786 return SrcAS < 256 && DestAS < 256;
1789 //===----------------------------------------------------------------------===//
1790 // Return Value Calling Convention Implementation
1791 //===----------------------------------------------------------------------===//
1793 #include "X86GenCallingConv.inc"
1796 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1797 MachineFunction &MF, bool isVarArg,
1798 const SmallVectorImpl<ISD::OutputArg> &Outs,
1799 LLVMContext &Context) const {
1800 SmallVector<CCValAssign, 16> RVLocs;
1801 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1803 return CCInfo.CheckReturn(Outs, RetCC_X86);
1806 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1807 static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1812 X86TargetLowering::LowerReturn(SDValue Chain,
1813 CallingConv::ID CallConv, bool isVarArg,
1814 const SmallVectorImpl<ISD::OutputArg> &Outs,
1815 const SmallVectorImpl<SDValue> &OutVals,
1816 SDLoc dl, SelectionDAG &DAG) const {
1817 MachineFunction &MF = DAG.getMachineFunction();
1818 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1820 SmallVector<CCValAssign, 16> RVLocs;
1821 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1822 RVLocs, *DAG.getContext());
1823 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1826 SmallVector<SDValue, 6> RetOps;
1827 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1828 // Operand #1 = Bytes To Pop
1829 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1832 // Copy the result values into the output registers.
1833 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1834 CCValAssign &VA = RVLocs[i];
1835 assert(VA.isRegLoc() && "Can only return in registers!");
1836 SDValue ValToCopy = OutVals[i];
1837 EVT ValVT = ValToCopy.getValueType();
1839 // Promote values to the appropriate types
1840 if (VA.getLocInfo() == CCValAssign::SExt)
1841 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1842 else if (VA.getLocInfo() == CCValAssign::ZExt)
1843 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1844 else if (VA.getLocInfo() == CCValAssign::AExt)
1845 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1846 else if (VA.getLocInfo() == CCValAssign::BCvt)
1847 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1849 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1850 "Unexpected FP-extend for return value.");
1852 // If this is x86-64, and we disabled SSE, we can't return FP values,
1853 // or SSE or MMX vectors.
1854 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1855 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1856 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1857 report_fatal_error("SSE register return with SSE disabled");
1859 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1860 // llvm-gcc has never done it right and no one has noticed, so this
1861 // should be OK for now.
1862 if (ValVT == MVT::f64 &&
1863 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1864 report_fatal_error("SSE2 register return with SSE2 disabled");
1866 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1867 // the RET instruction and handled by the FP Stackifier.
1868 if (VA.getLocReg() == X86::ST0 ||
1869 VA.getLocReg() == X86::ST1) {
1870 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1871 // change the value to the FP stack register class.
1872 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1873 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1874 RetOps.push_back(ValToCopy);
1875 // Don't emit a copytoreg.
1879 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1880 // which is returned in RAX / RDX.
1881 if (Subtarget->is64Bit()) {
1882 if (ValVT == MVT::x86mmx) {
1883 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1884 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1885 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1887 // If we don't have SSE2 available, convert to v4f32 so the generated
1888 // register is legal.
1889 if (!Subtarget->hasSSE2())
1890 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1895 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1896 Flag = Chain.getValue(1);
1897 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1900 // The x86-64 ABIs require that for returning structs by value we copy
1901 // the sret argument into %rax/%eax (depending on ABI) for the return.
1902 // Win32 requires us to put the sret argument to %eax as well.
1903 // We saved the argument into a virtual register in the entry block,
1904 // so now we copy the value out and into %rax/%eax.
1905 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1906 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1907 MachineFunction &MF = DAG.getMachineFunction();
1908 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1909 unsigned Reg = FuncInfo->getSRetReturnReg();
1911 "SRetReturnReg should have been set in LowerFormalArguments().");
1912 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1915 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1916 X86::RAX : X86::EAX;
1917 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1918 Flag = Chain.getValue(1);
1920 // RAX/EAX now acts like a return value.
1921 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1924 RetOps[0] = Chain; // Update chain.
1926 // Add the flag if we have it.
1928 RetOps.push_back(Flag);
1930 return DAG.getNode(X86ISD::RET_FLAG, dl,
1931 MVT::Other, &RetOps[0], RetOps.size());
1934 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1935 if (N->getNumValues() != 1)
1937 if (!N->hasNUsesOfValue(1, 0))
1940 SDValue TCChain = Chain;
1941 SDNode *Copy = *N->use_begin();
1942 if (Copy->getOpcode() == ISD::CopyToReg) {
1943 // If the copy has a glue operand, we conservatively assume it isn't safe to
1944 // perform a tail call.
1945 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1947 TCChain = Copy->getOperand(0);
1948 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1951 bool HasRet = false;
1952 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1954 if (UI->getOpcode() != X86ISD::RET_FLAG)
1967 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1968 ISD::NodeType ExtendKind) const {
1970 // TODO: Is this also valid on 32-bit?
1971 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1972 ReturnMVT = MVT::i8;
1974 ReturnMVT = MVT::i32;
1976 MVT MinVT = getRegisterType(ReturnMVT);
1977 return VT.bitsLT(MinVT) ? MinVT : VT;
1980 /// LowerCallResult - Lower the result values of a call into the
1981 /// appropriate copies out of appropriate physical registers.
1984 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1985 CallingConv::ID CallConv, bool isVarArg,
1986 const SmallVectorImpl<ISD::InputArg> &Ins,
1987 SDLoc dl, SelectionDAG &DAG,
1988 SmallVectorImpl<SDValue> &InVals) const {
1990 // Assign locations to each value returned by this call.
1991 SmallVector<CCValAssign, 16> RVLocs;
1992 bool Is64Bit = Subtarget->is64Bit();
1993 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1994 getTargetMachine(), RVLocs, *DAG.getContext());
1995 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1997 // Copy all of the result registers out of their specified physreg.
1998 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1999 CCValAssign &VA = RVLocs[i];
2000 EVT CopyVT = VA.getValVT();
2002 // If this is x86-64, and we disabled SSE, we can't return FP values
2003 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2004 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2005 report_fatal_error("SSE register return with SSE disabled");
2010 // If this is a call to a function that returns an fp value on the floating
2011 // point stack, we must guarantee the value is popped from the stack, so
2012 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2013 // if the return value is not used. We use the FpPOP_RETVAL instruction
2015 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2016 // If we prefer to use the value in xmm registers, copy it out as f80 and
2017 // use a truncate to move it from fp stack reg to xmm reg.
2018 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2019 SDValue Ops[] = { Chain, InFlag };
2020 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2021 MVT::Other, MVT::Glue, Ops), 1);
2022 Val = Chain.getValue(0);
2024 // Round the f80 to the right size, which also moves it to the appropriate
2026 if (CopyVT != VA.getValVT())
2027 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2028 // This truncation won't change the value.
2029 DAG.getIntPtrConstant(1));
2031 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2032 CopyVT, InFlag).getValue(1);
2033 Val = Chain.getValue(0);
2035 InFlag = Chain.getValue(2);
2036 InVals.push_back(Val);
2042 //===----------------------------------------------------------------------===//
2043 // C & StdCall & Fast Calling Convention implementation
2044 //===----------------------------------------------------------------------===//
2045 // StdCall calling convention seems to be standard for many Windows' API
2046 // routines and around. It differs from C calling convention just a little:
2047 // callee should clean up the stack, not caller. Symbols should be also
2048 // decorated in some fancy way :) It doesn't support any vector arguments.
2049 // For info on fast calling convention see Fast Calling Convention (tail call)
2050 // implementation LowerX86_32FastCCCallTo.
2052 /// CallIsStructReturn - Determines whether a call uses struct return
2054 enum StructReturnType {
2059 static StructReturnType
2060 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2062 return NotStructReturn;
2064 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2065 if (!Flags.isSRet())
2066 return NotStructReturn;
2067 if (Flags.isInReg())
2068 return RegStructReturn;
2069 return StackStructReturn;
2072 /// ArgsAreStructReturn - Determines whether a function uses struct
2073 /// return semantics.
2074 static StructReturnType
2075 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2077 return NotStructReturn;
2079 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2080 if (!Flags.isSRet())
2081 return NotStructReturn;
2082 if (Flags.isInReg())
2083 return RegStructReturn;
2084 return StackStructReturn;
2087 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2088 /// by "Src" to address "Dst" with size and alignment information specified by
2089 /// the specific parameter attribute. The copy will be passed as a byval
2090 /// function parameter.
2092 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2093 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2095 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2097 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2098 /*isVolatile*/false, /*AlwaysInline=*/true,
2099 MachinePointerInfo(), MachinePointerInfo());
2102 /// IsTailCallConvention - Return true if the calling convention is one that
2103 /// supports tail call optimization.
2104 static bool IsTailCallConvention(CallingConv::ID CC) {
2105 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2106 CC == CallingConv::HiPE);
2109 /// \brief Return true if the calling convention is a C calling convention.
2110 static bool IsCCallConvention(CallingConv::ID CC) {
2111 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2112 CC == CallingConv::X86_64_SysV);
2115 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2116 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2120 CallingConv::ID CalleeCC = CS.getCallingConv();
2121 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2127 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2128 /// a tailcall target by changing its ABI.
2129 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2130 bool GuaranteedTailCallOpt) {
2131 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2135 X86TargetLowering::LowerMemArgument(SDValue Chain,
2136 CallingConv::ID CallConv,
2137 const SmallVectorImpl<ISD::InputArg> &Ins,
2138 SDLoc dl, SelectionDAG &DAG,
2139 const CCValAssign &VA,
2140 MachineFrameInfo *MFI,
2142 // Create the nodes corresponding to a load from this parameter slot.
2143 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2144 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2145 getTargetMachine().Options.GuaranteedTailCallOpt);
2146 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2149 // If value is passed by pointer we have address passed instead of the value
2151 if (VA.getLocInfo() == CCValAssign::Indirect)
2152 ValVT = VA.getLocVT();
2154 ValVT = VA.getValVT();
2156 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2157 // changed with more analysis.
2158 // In case of tail call optimization mark all arguments mutable. Since they
2159 // could be overwritten by lowering of arguments in case of a tail call.
2160 if (Flags.isByVal()) {
2161 unsigned Bytes = Flags.getByValSize();
2162 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2163 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2164 return DAG.getFrameIndex(FI, getPointerTy());
2166 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2167 VA.getLocMemOffset(), isImmutable);
2168 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2169 return DAG.getLoad(ValVT, dl, Chain, FIN,
2170 MachinePointerInfo::getFixedStack(FI),
2171 false, false, false, 0);
2176 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2177 CallingConv::ID CallConv,
2179 const SmallVectorImpl<ISD::InputArg> &Ins,
2182 SmallVectorImpl<SDValue> &InVals)
2184 MachineFunction &MF = DAG.getMachineFunction();
2185 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2187 const Function* Fn = MF.getFunction();
2188 if (Fn->hasExternalLinkage() &&
2189 Subtarget->isTargetCygMing() &&
2190 Fn->getName() == "main")
2191 FuncInfo->setForceFramePointer(true);
2193 MachineFrameInfo *MFI = MF.getFrameInfo();
2194 bool Is64Bit = Subtarget->is64Bit();
2195 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2197 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2198 "Var args not supported with calling convention fastcc, ghc or hipe");
2200 // Assign locations to all of the incoming arguments.
2201 SmallVector<CCValAssign, 16> ArgLocs;
2202 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2203 ArgLocs, *DAG.getContext());
2205 // Allocate shadow area for Win64
2207 CCInfo.AllocateStack(32, 8);
2209 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2211 unsigned LastVal = ~0U;
2213 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2214 CCValAssign &VA = ArgLocs[i];
2215 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2217 assert(VA.getValNo() != LastVal &&
2218 "Don't support value assigned to multiple locs yet");
2220 LastVal = VA.getValNo();
2222 if (VA.isRegLoc()) {
2223 EVT RegVT = VA.getLocVT();
2224 const TargetRegisterClass *RC;
2225 if (RegVT == MVT::i32)
2226 RC = &X86::GR32RegClass;
2227 else if (Is64Bit && RegVT == MVT::i64)
2228 RC = &X86::GR64RegClass;
2229 else if (RegVT == MVT::f32)
2230 RC = &X86::FR32RegClass;
2231 else if (RegVT == MVT::f64)
2232 RC = &X86::FR64RegClass;
2233 else if (RegVT.is512BitVector())
2234 RC = &X86::VR512RegClass;
2235 else if (RegVT.is256BitVector())
2236 RC = &X86::VR256RegClass;
2237 else if (RegVT.is128BitVector())
2238 RC = &X86::VR128RegClass;
2239 else if (RegVT == MVT::x86mmx)
2240 RC = &X86::VR64RegClass;
2241 else if (RegVT == MVT::i1)
2242 RC = &X86::VK1RegClass;
2243 else if (RegVT == MVT::v8i1)
2244 RC = &X86::VK8RegClass;
2245 else if (RegVT == MVT::v16i1)
2246 RC = &X86::VK16RegClass;
2248 llvm_unreachable("Unknown argument type!");
2250 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2251 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2253 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2254 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2256 if (VA.getLocInfo() == CCValAssign::SExt)
2257 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2258 DAG.getValueType(VA.getValVT()));
2259 else if (VA.getLocInfo() == CCValAssign::ZExt)
2260 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2261 DAG.getValueType(VA.getValVT()));
2262 else if (VA.getLocInfo() == CCValAssign::BCvt)
2263 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2265 if (VA.isExtInLoc()) {
2266 // Handle MMX values passed in XMM regs.
2267 if (RegVT.isVector())
2268 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2270 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2273 assert(VA.isMemLoc());
2274 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2277 // If value is passed via pointer - do a load.
2278 if (VA.getLocInfo() == CCValAssign::Indirect)
2279 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2280 MachinePointerInfo(), false, false, false, 0);
2282 InVals.push_back(ArgValue);
2285 // The x86-64 ABIs require that for returning structs by value we copy
2286 // the sret argument into %rax/%eax (depending on ABI) for the return.
2287 // Win32 requires us to put the sret argument to %eax as well.
2288 // Save the argument into a virtual register so that we can access it
2289 // from the return points.
2290 if (MF.getFunction()->hasStructRetAttr() &&
2291 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2292 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2293 unsigned Reg = FuncInfo->getSRetReturnReg();
2295 MVT PtrTy = getPointerTy();
2296 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2297 FuncInfo->setSRetReturnReg(Reg);
2299 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2300 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2303 unsigned StackSize = CCInfo.getNextStackOffset();
2304 // Align stack specially for tail calls.
2305 if (FuncIsMadeTailCallSafe(CallConv,
2306 MF.getTarget().Options.GuaranteedTailCallOpt))
2307 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2309 // If the function takes variable number of arguments, make a frame index for
2310 // the start of the first vararg value... for expansion of llvm.va_start.
2312 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2313 CallConv != CallingConv::X86_ThisCall)) {
2314 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2317 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2319 // FIXME: We should really autogenerate these arrays
2320 static const uint16_t GPR64ArgRegsWin64[] = {
2321 X86::RCX, X86::RDX, X86::R8, X86::R9
2323 static const uint16_t GPR64ArgRegs64Bit[] = {
2324 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2326 static const uint16_t XMMArgRegs64Bit[] = {
2327 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2328 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2330 const uint16_t *GPR64ArgRegs;
2331 unsigned NumXMMRegs = 0;
2334 // The XMM registers which might contain var arg parameters are shadowed
2335 // in their paired GPR. So we only need to save the GPR to their home
2337 TotalNumIntRegs = 4;
2338 GPR64ArgRegs = GPR64ArgRegsWin64;
2340 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2341 GPR64ArgRegs = GPR64ArgRegs64Bit;
2343 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2346 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2349 bool NoImplicitFloatOps = Fn->getAttributes().
2350 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2351 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2352 "SSE register cannot be used when SSE is disabled!");
2353 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2354 NoImplicitFloatOps) &&
2355 "SSE register cannot be used when SSE is disabled!");
2356 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2357 !Subtarget->hasSSE1())
2358 // Kernel mode asks for SSE to be disabled, so don't push them
2360 TotalNumXMMRegs = 0;
2363 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2364 // Get to the caller-allocated home save location. Add 8 to account
2365 // for the return address.
2366 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2367 FuncInfo->setRegSaveFrameIndex(
2368 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2369 // Fixup to set vararg frame on shadow area (4 x i64).
2371 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2373 // For X86-64, if there are vararg parameters that are passed via
2374 // registers, then we must store them to their spots on the stack so
2375 // they may be loaded by deferencing the result of va_next.
2376 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2377 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2378 FuncInfo->setRegSaveFrameIndex(
2379 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2383 // Store the integer parameter registers.
2384 SmallVector<SDValue, 8> MemOps;
2385 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2387 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2388 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2389 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2390 DAG.getIntPtrConstant(Offset));
2391 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2392 &X86::GR64RegClass);
2393 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2395 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2396 MachinePointerInfo::getFixedStack(
2397 FuncInfo->getRegSaveFrameIndex(), Offset),
2399 MemOps.push_back(Store);
2403 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2404 // Now store the XMM (fp + vector) parameter registers.
2405 SmallVector<SDValue, 11> SaveXMMOps;
2406 SaveXMMOps.push_back(Chain);
2408 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2409 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2410 SaveXMMOps.push_back(ALVal);
2412 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2413 FuncInfo->getRegSaveFrameIndex()));
2414 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2415 FuncInfo->getVarArgsFPOffset()));
2417 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2418 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2419 &X86::VR128RegClass);
2420 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2421 SaveXMMOps.push_back(Val);
2423 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2425 &SaveXMMOps[0], SaveXMMOps.size()));
2428 if (!MemOps.empty())
2429 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2430 &MemOps[0], MemOps.size());
2434 // Some CCs need callee pop.
2435 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2436 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2437 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2439 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2440 // If this is an sret function, the return should pop the hidden pointer.
2441 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2442 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2443 argsAreStructReturn(Ins) == StackStructReturn)
2444 FuncInfo->setBytesToPopOnReturn(4);
2448 // RegSaveFrameIndex is X86-64 only.
2449 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2450 if (CallConv == CallingConv::X86_FastCall ||
2451 CallConv == CallingConv::X86_ThisCall)
2452 // fastcc functions can't have varargs.
2453 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2456 FuncInfo->setArgumentStackSize(StackSize);
2462 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2463 SDValue StackPtr, SDValue Arg,
2464 SDLoc dl, SelectionDAG &DAG,
2465 const CCValAssign &VA,
2466 ISD::ArgFlagsTy Flags) const {
2467 unsigned LocMemOffset = VA.getLocMemOffset();
2468 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2469 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2470 if (Flags.isByVal())
2471 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2473 return DAG.getStore(Chain, dl, Arg, PtrOff,
2474 MachinePointerInfo::getStack(LocMemOffset),
2478 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2479 /// optimization is performed and it is required.
2481 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2482 SDValue &OutRetAddr, SDValue Chain,
2483 bool IsTailCall, bool Is64Bit,
2484 int FPDiff, SDLoc dl) const {
2485 // Adjust the Return address stack slot.
2486 EVT VT = getPointerTy();
2487 OutRetAddr = getReturnAddressFrameIndex(DAG);
2489 // Load the "old" Return address.
2490 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2491 false, false, false, 0);
2492 return SDValue(OutRetAddr.getNode(), 1);
2495 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2496 /// optimization is performed and it is required (FPDiff!=0).
2498 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2499 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2500 unsigned SlotSize, int FPDiff, SDLoc dl) {
2501 // Store the return address to the appropriate stack slot.
2502 if (!FPDiff) return Chain;
2503 // Calculate the new stack slot for the return address.
2504 int NewReturnAddrFI =
2505 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2507 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2508 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2509 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2515 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2516 SmallVectorImpl<SDValue> &InVals) const {
2517 SelectionDAG &DAG = CLI.DAG;
2519 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2520 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2521 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2522 SDValue Chain = CLI.Chain;
2523 SDValue Callee = CLI.Callee;
2524 CallingConv::ID CallConv = CLI.CallConv;
2525 bool &isTailCall = CLI.IsTailCall;
2526 bool isVarArg = CLI.IsVarArg;
2528 MachineFunction &MF = DAG.getMachineFunction();
2529 bool Is64Bit = Subtarget->is64Bit();
2530 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2531 StructReturnType SR = callIsStructReturn(Outs);
2532 bool IsSibcall = false;
2534 if (MF.getTarget().Options.DisableTailCalls)
2538 // Check if it's really possible to do a tail call.
2539 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2540 isVarArg, SR != NotStructReturn,
2541 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2542 Outs, OutVals, Ins, DAG);
2544 // Sibcalls are automatically detected tailcalls which do not require
2546 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2553 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2554 "Var args not supported with calling convention fastcc, ghc or hipe");
2556 // Analyze operands of the call, assigning locations to each operand.
2557 SmallVector<CCValAssign, 16> ArgLocs;
2558 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2559 ArgLocs, *DAG.getContext());
2561 // Allocate shadow area for Win64
2563 CCInfo.AllocateStack(32, 8);
2565 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2567 // Get a count of how many bytes are to be pushed on the stack.
2568 unsigned NumBytes = CCInfo.getNextStackOffset();
2570 // This is a sibcall. The memory operands are available in caller's
2571 // own caller's stack.
2573 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2574 IsTailCallConvention(CallConv))
2575 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2578 if (isTailCall && !IsSibcall) {
2579 // Lower arguments at fp - stackoffset + fpdiff.
2580 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2581 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2583 FPDiff = NumBytesCallerPushed - NumBytes;
2585 // Set the delta of movement of the returnaddr stackslot.
2586 // But only set if delta is greater than previous delta.
2587 if (FPDiff < X86Info->getTCReturnAddrDelta())
2588 X86Info->setTCReturnAddrDelta(FPDiff);
2591 unsigned NumBytesToPush = NumBytes;
2592 unsigned NumBytesToPop = NumBytes;
2594 // If we have an inalloca argument, all stack space has already been allocated
2595 // for us and be right at the top of the stack. We don't support multiple
2596 // arguments passed in memory when using inalloca.
2597 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2599 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2600 "an inalloca argument must be the only memory argument");
2604 Chain = DAG.getCALLSEQ_START(
2605 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2607 SDValue RetAddrFrIdx;
2608 // Load return address for tail calls.
2609 if (isTailCall && FPDiff)
2610 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2611 Is64Bit, FPDiff, dl);
2613 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2614 SmallVector<SDValue, 8> MemOpChains;
2617 // Walk the register/memloc assignments, inserting copies/loads. In the case
2618 // of tail call optimization arguments are handle later.
2619 const X86RegisterInfo *RegInfo =
2620 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2621 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2622 // Skip inalloca arguments, they have already been written.
2623 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2624 if (Flags.isInAlloca())
2627 CCValAssign &VA = ArgLocs[i];
2628 EVT RegVT = VA.getLocVT();
2629 SDValue Arg = OutVals[i];
2630 bool isByVal = Flags.isByVal();
2632 // Promote the value if needed.
2633 switch (VA.getLocInfo()) {
2634 default: llvm_unreachable("Unknown loc info!");
2635 case CCValAssign::Full: break;
2636 case CCValAssign::SExt:
2637 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2639 case CCValAssign::ZExt:
2640 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2642 case CCValAssign::AExt:
2643 if (RegVT.is128BitVector()) {
2644 // Special case: passing MMX values in XMM registers.
2645 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2646 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2647 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2649 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2651 case CCValAssign::BCvt:
2652 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2654 case CCValAssign::Indirect: {
2655 // Store the argument.
2656 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2657 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2658 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2659 MachinePointerInfo::getFixedStack(FI),
2666 if (VA.isRegLoc()) {
2667 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2668 if (isVarArg && IsWin64) {
2669 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2670 // shadow reg if callee is a varargs function.
2671 unsigned ShadowReg = 0;
2672 switch (VA.getLocReg()) {
2673 case X86::XMM0: ShadowReg = X86::RCX; break;
2674 case X86::XMM1: ShadowReg = X86::RDX; break;
2675 case X86::XMM2: ShadowReg = X86::R8; break;
2676 case X86::XMM3: ShadowReg = X86::R9; break;
2679 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2681 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2682 assert(VA.isMemLoc());
2683 if (StackPtr.getNode() == 0)
2684 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2686 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2687 dl, DAG, VA, Flags));
2691 if (!MemOpChains.empty())
2692 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2693 &MemOpChains[0], MemOpChains.size());
2695 if (Subtarget->isPICStyleGOT()) {
2696 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2699 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2700 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2702 // If we are tail calling and generating PIC/GOT style code load the
2703 // address of the callee into ECX. The value in ecx is used as target of
2704 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2705 // for tail calls on PIC/GOT architectures. Normally we would just put the
2706 // address of GOT into ebx and then call target@PLT. But for tail calls
2707 // ebx would be restored (since ebx is callee saved) before jumping to the
2710 // Note: The actual moving to ECX is done further down.
2711 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2712 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2713 !G->getGlobal()->hasProtectedVisibility())
2714 Callee = LowerGlobalAddress(Callee, DAG);
2715 else if (isa<ExternalSymbolSDNode>(Callee))
2716 Callee = LowerExternalSymbol(Callee, DAG);
2720 if (Is64Bit && isVarArg && !IsWin64) {
2721 // From AMD64 ABI document:
2722 // For calls that may call functions that use varargs or stdargs
2723 // (prototype-less calls or calls to functions containing ellipsis (...) in
2724 // the declaration) %al is used as hidden argument to specify the number
2725 // of SSE registers used. The contents of %al do not need to match exactly
2726 // the number of registers, but must be an ubound on the number of SSE
2727 // registers used and is in the range 0 - 8 inclusive.
2729 // Count the number of XMM registers allocated.
2730 static const uint16_t XMMArgRegs[] = {
2731 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2732 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2734 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2735 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2736 && "SSE registers cannot be used when SSE is disabled");
2738 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2739 DAG.getConstant(NumXMMRegs, MVT::i8)));
2742 // For tail calls lower the arguments to the 'real' stack slot.
2744 // Force all the incoming stack arguments to be loaded from the stack
2745 // before any new outgoing arguments are stored to the stack, because the
2746 // outgoing stack slots may alias the incoming argument stack slots, and
2747 // the alias isn't otherwise explicit. This is slightly more conservative
2748 // than necessary, because it means that each store effectively depends
2749 // on every argument instead of just those arguments it would clobber.
2750 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2752 SmallVector<SDValue, 8> MemOpChains2;
2755 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2756 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2757 CCValAssign &VA = ArgLocs[i];
2760 assert(VA.isMemLoc());
2761 SDValue Arg = OutVals[i];
2762 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2763 // Create frame index.
2764 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2765 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2766 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2767 FIN = DAG.getFrameIndex(FI, getPointerTy());
2769 if (Flags.isByVal()) {
2770 // Copy relative to framepointer.
2771 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2772 if (StackPtr.getNode() == 0)
2773 StackPtr = DAG.getCopyFromReg(Chain, dl,
2774 RegInfo->getStackRegister(),
2776 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2778 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2782 // Store relative to framepointer.
2783 MemOpChains2.push_back(
2784 DAG.getStore(ArgChain, dl, Arg, FIN,
2785 MachinePointerInfo::getFixedStack(FI),
2791 if (!MemOpChains2.empty())
2792 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2793 &MemOpChains2[0], MemOpChains2.size());
2795 // Store the return address to the appropriate stack slot.
2796 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2797 getPointerTy(), RegInfo->getSlotSize(),
2801 // Build a sequence of copy-to-reg nodes chained together with token chain
2802 // and flag operands which copy the outgoing args into registers.
2804 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2805 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2806 RegsToPass[i].second, InFlag);
2807 InFlag = Chain.getValue(1);
2810 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2811 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2812 // In the 64-bit large code model, we have to make all calls
2813 // through a register, since the call instruction's 32-bit
2814 // pc-relative offset may not be large enough to hold the whole
2816 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2817 // If the callee is a GlobalAddress node (quite common, every direct call
2818 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2821 // We should use extra load for direct calls to dllimported functions in
2823 const GlobalValue *GV = G->getGlobal();
2824 if (!GV->hasDLLImportStorageClass()) {
2825 unsigned char OpFlags = 0;
2826 bool ExtraLoad = false;
2827 unsigned WrapperKind = ISD::DELETED_NODE;
2829 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2830 // external symbols most go through the PLT in PIC mode. If the symbol
2831 // has hidden or protected visibility, or if it is static or local, then
2832 // we don't need to use the PLT - we can directly call it.
2833 if (Subtarget->isTargetELF() &&
2834 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2835 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2836 OpFlags = X86II::MO_PLT;
2837 } else if (Subtarget->isPICStyleStubAny() &&
2838 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2839 (!Subtarget->getTargetTriple().isMacOSX() ||
2840 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2841 // PC-relative references to external symbols should go through $stub,
2842 // unless we're building with the leopard linker or later, which
2843 // automatically synthesizes these stubs.
2844 OpFlags = X86II::MO_DARWIN_STUB;
2845 } else if (Subtarget->isPICStyleRIPRel() &&
2846 isa<Function>(GV) &&
2847 cast<Function>(GV)->getAttributes().
2848 hasAttribute(AttributeSet::FunctionIndex,
2849 Attribute::NonLazyBind)) {
2850 // If the function is marked as non-lazy, generate an indirect call
2851 // which loads from the GOT directly. This avoids runtime overhead
2852 // at the cost of eager binding (and one extra byte of encoding).
2853 OpFlags = X86II::MO_GOTPCREL;
2854 WrapperKind = X86ISD::WrapperRIP;
2858 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2859 G->getOffset(), OpFlags);
2861 // Add a wrapper if needed.
2862 if (WrapperKind != ISD::DELETED_NODE)
2863 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2864 // Add extra indirection if needed.
2866 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2867 MachinePointerInfo::getGOT(),
2868 false, false, false, 0);
2870 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2871 unsigned char OpFlags = 0;
2873 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2874 // external symbols should go through the PLT.
2875 if (Subtarget->isTargetELF() &&
2876 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2877 OpFlags = X86II::MO_PLT;
2878 } else if (Subtarget->isPICStyleStubAny() &&
2879 (!Subtarget->getTargetTriple().isMacOSX() ||
2880 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2881 // PC-relative references to external symbols should go through $stub,
2882 // unless we're building with the leopard linker or later, which
2883 // automatically synthesizes these stubs.
2884 OpFlags = X86II::MO_DARWIN_STUB;
2887 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2891 // Returns a chain & a flag for retval copy to use.
2892 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2893 SmallVector<SDValue, 8> Ops;
2895 if (!IsSibcall && isTailCall) {
2896 Chain = DAG.getCALLSEQ_END(Chain,
2897 DAG.getIntPtrConstant(NumBytesToPop, true),
2898 DAG.getIntPtrConstant(0, true), InFlag, dl);
2899 InFlag = Chain.getValue(1);
2902 Ops.push_back(Chain);
2903 Ops.push_back(Callee);
2906 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2908 // Add argument registers to the end of the list so that they are known live
2910 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2911 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2912 RegsToPass[i].second.getValueType()));
2914 // Add a register mask operand representing the call-preserved registers.
2915 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2916 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2917 assert(Mask && "Missing call preserved mask for calling convention");
2918 Ops.push_back(DAG.getRegisterMask(Mask));
2920 if (InFlag.getNode())
2921 Ops.push_back(InFlag);
2925 //// If this is the first return lowered for this function, add the regs
2926 //// to the liveout set for the function.
2927 // This isn't right, although it's probably harmless on x86; liveouts
2928 // should be computed from returns not tail calls. Consider a void
2929 // function making a tail call to a function returning int.
2930 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2933 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2934 InFlag = Chain.getValue(1);
2936 // Create the CALLSEQ_END node.
2937 unsigned NumBytesForCalleeToPop;
2938 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2939 getTargetMachine().Options.GuaranteedTailCallOpt))
2940 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2941 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2942 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2943 SR == StackStructReturn)
2944 // If this is a call to a struct-return function, the callee
2945 // pops the hidden struct pointer, so we have to push it back.
2946 // This is common for Darwin/X86, Linux & Mingw32 targets.
2947 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2948 NumBytesForCalleeToPop = 4;
2950 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2952 // Returns a flag for retval copy to use.
2954 Chain = DAG.getCALLSEQ_END(Chain,
2955 DAG.getIntPtrConstant(NumBytesToPop, true),
2956 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2959 InFlag = Chain.getValue(1);
2962 // Handle result values, copying them out of physregs into vregs that we
2964 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2965 Ins, dl, DAG, InVals);
2968 //===----------------------------------------------------------------------===//
2969 // Fast Calling Convention (tail call) implementation
2970 //===----------------------------------------------------------------------===//
2972 // Like std call, callee cleans arguments, convention except that ECX is
2973 // reserved for storing the tail called function address. Only 2 registers are
2974 // free for argument passing (inreg). Tail call optimization is performed
2976 // * tailcallopt is enabled
2977 // * caller/callee are fastcc
2978 // On X86_64 architecture with GOT-style position independent code only local
2979 // (within module) calls are supported at the moment.
2980 // To keep the stack aligned according to platform abi the function
2981 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2982 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2983 // If a tail called function callee has more arguments than the caller the
2984 // caller needs to make sure that there is room to move the RETADDR to. This is
2985 // achieved by reserving an area the size of the argument delta right after the
2986 // original REtADDR, but before the saved framepointer or the spilled registers
2987 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2999 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3000 /// for a 16 byte align requirement.
3002 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3003 SelectionDAG& DAG) const {
3004 MachineFunction &MF = DAG.getMachineFunction();
3005 const TargetMachine &TM = MF.getTarget();
3006 const X86RegisterInfo *RegInfo =
3007 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3008 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3009 unsigned StackAlignment = TFI.getStackAlignment();
3010 uint64_t AlignMask = StackAlignment - 1;
3011 int64_t Offset = StackSize;
3012 unsigned SlotSize = RegInfo->getSlotSize();
3013 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3014 // Number smaller than 12 so just add the difference.
3015 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3017 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3018 Offset = ((~AlignMask) & Offset) + StackAlignment +
3019 (StackAlignment-SlotSize);
3024 /// MatchingStackOffset - Return true if the given stack call argument is
3025 /// already available in the same position (relatively) of the caller's
3026 /// incoming argument stack.
3028 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3029 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3030 const X86InstrInfo *TII) {
3031 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3033 if (Arg.getOpcode() == ISD::CopyFromReg) {
3034 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3035 if (!TargetRegisterInfo::isVirtualRegister(VR))
3037 MachineInstr *Def = MRI->getVRegDef(VR);
3040 if (!Flags.isByVal()) {
3041 if (!TII->isLoadFromStackSlot(Def, FI))
3044 unsigned Opcode = Def->getOpcode();
3045 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3046 Def->getOperand(1).isFI()) {
3047 FI = Def->getOperand(1).getIndex();
3048 Bytes = Flags.getByValSize();
3052 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3053 if (Flags.isByVal())
3054 // ByVal argument is passed in as a pointer but it's now being
3055 // dereferenced. e.g.
3056 // define @foo(%struct.X* %A) {
3057 // tail call @bar(%struct.X* byval %A)
3060 SDValue Ptr = Ld->getBasePtr();
3061 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3064 FI = FINode->getIndex();
3065 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3066 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3067 FI = FINode->getIndex();
3068 Bytes = Flags.getByValSize();
3072 assert(FI != INT_MAX);
3073 if (!MFI->isFixedObjectIndex(FI))
3075 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3078 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3079 /// for tail call optimization. Targets which want to do tail call
3080 /// optimization should implement this function.
3082 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3083 CallingConv::ID CalleeCC,
3085 bool isCalleeStructRet,
3086 bool isCallerStructRet,
3088 const SmallVectorImpl<ISD::OutputArg> &Outs,
3089 const SmallVectorImpl<SDValue> &OutVals,
3090 const SmallVectorImpl<ISD::InputArg> &Ins,
3091 SelectionDAG &DAG) const {
3092 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3095 // If -tailcallopt is specified, make fastcc functions tail-callable.
3096 const MachineFunction &MF = DAG.getMachineFunction();
3097 const Function *CallerF = MF.getFunction();
3099 // If the function return type is x86_fp80 and the callee return type is not,
3100 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3101 // perform a tailcall optimization here.
3102 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3105 CallingConv::ID CallerCC = CallerF->getCallingConv();
3106 bool CCMatch = CallerCC == CalleeCC;
3107 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3108 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3110 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3111 if (IsTailCallConvention(CalleeCC) && CCMatch)
3116 // Look for obvious safe cases to perform tail call optimization that do not
3117 // require ABI changes. This is what gcc calls sibcall.
3119 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3120 // emit a special epilogue.
3121 const X86RegisterInfo *RegInfo =
3122 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3123 if (RegInfo->needsStackRealignment(MF))
3126 // Also avoid sibcall optimization if either caller or callee uses struct
3127 // return semantics.
3128 if (isCalleeStructRet || isCallerStructRet)
3131 // An stdcall/thiscall caller is expected to clean up its arguments; the
3132 // callee isn't going to do that.
3133 // FIXME: this is more restrictive than needed. We could produce a tailcall
3134 // when the stack adjustment matches. For example, with a thiscall that takes
3135 // only one argument.
3136 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3137 CallerCC == CallingConv::X86_ThisCall))
3140 // Do not sibcall optimize vararg calls unless all arguments are passed via
3142 if (isVarArg && !Outs.empty()) {
3144 // Optimizing for varargs on Win64 is unlikely to be safe without
3145 // additional testing.
3146 if (IsCalleeWin64 || IsCallerWin64)
3149 SmallVector<CCValAssign, 16> ArgLocs;
3150 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151 getTargetMachine(), ArgLocs, *DAG.getContext());
3153 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3154 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3155 if (!ArgLocs[i].isRegLoc())
3159 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3160 // stack. Therefore, if it's not used by the call it is not safe to optimize
3161 // this into a sibcall.
3162 bool Unused = false;
3163 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3170 SmallVector<CCValAssign, 16> RVLocs;
3171 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3172 getTargetMachine(), RVLocs, *DAG.getContext());
3173 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3174 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3175 CCValAssign &VA = RVLocs[i];
3176 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3181 // If the calling conventions do not match, then we'd better make sure the
3182 // results are returned in the same way as what the caller expects.
3184 SmallVector<CCValAssign, 16> RVLocs1;
3185 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3186 getTargetMachine(), RVLocs1, *DAG.getContext());
3187 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3189 SmallVector<CCValAssign, 16> RVLocs2;
3190 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3191 getTargetMachine(), RVLocs2, *DAG.getContext());
3192 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3194 if (RVLocs1.size() != RVLocs2.size())
3196 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3197 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3199 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3201 if (RVLocs1[i].isRegLoc()) {
3202 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3205 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3211 // If the callee takes no arguments then go on to check the results of the
3213 if (!Outs.empty()) {
3214 // Check if stack adjustment is needed. For now, do not do this if any
3215 // argument is passed on the stack.
3216 SmallVector<CCValAssign, 16> ArgLocs;
3217 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3218 getTargetMachine(), ArgLocs, *DAG.getContext());
3220 // Allocate shadow area for Win64
3222 CCInfo.AllocateStack(32, 8);
3224 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3225 if (CCInfo.getNextStackOffset()) {
3226 MachineFunction &MF = DAG.getMachineFunction();
3227 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3230 // Check if the arguments are already laid out in the right way as
3231 // the caller's fixed stack objects.
3232 MachineFrameInfo *MFI = MF.getFrameInfo();
3233 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3234 const X86InstrInfo *TII =
3235 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3236 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3237 CCValAssign &VA = ArgLocs[i];
3238 SDValue Arg = OutVals[i];
3239 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3240 if (VA.getLocInfo() == CCValAssign::Indirect)
3242 if (!VA.isRegLoc()) {
3243 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3250 // If the tailcall address may be in a register, then make sure it's
3251 // possible to register allocate for it. In 32-bit, the call address can
3252 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3253 // callee-saved registers are restored. These happen to be the same
3254 // registers used to pass 'inreg' arguments so watch out for those.
3255 if (!Subtarget->is64Bit() &&
3256 ((!isa<GlobalAddressSDNode>(Callee) &&
3257 !isa<ExternalSymbolSDNode>(Callee)) ||
3258 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3259 unsigned NumInRegs = 0;
3260 // In PIC we need an extra register to formulate the address computation
3262 unsigned MaxInRegs =
3263 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3265 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3266 CCValAssign &VA = ArgLocs[i];
3269 unsigned Reg = VA.getLocReg();
3272 case X86::EAX: case X86::EDX: case X86::ECX:
3273 if (++NumInRegs == MaxInRegs)
3285 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3286 const TargetLibraryInfo *libInfo) const {
3287 return X86::createFastISel(funcInfo, libInfo);
3290 //===----------------------------------------------------------------------===//
3291 // Other Lowering Hooks
3292 //===----------------------------------------------------------------------===//
3294 static bool MayFoldLoad(SDValue Op) {
3295 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3298 static bool MayFoldIntoStore(SDValue Op) {
3299 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3302 static bool isTargetShuffle(unsigned Opcode) {
3304 default: return false;
3305 case X86ISD::PSHUFD:
3306 case X86ISD::PSHUFHW:
3307 case X86ISD::PSHUFLW:
3309 case X86ISD::PALIGNR:
3310 case X86ISD::MOVLHPS:
3311 case X86ISD::MOVLHPD:
3312 case X86ISD::MOVHLPS:
3313 case X86ISD::MOVLPS:
3314 case X86ISD::MOVLPD:
3315 case X86ISD::MOVSHDUP:
3316 case X86ISD::MOVSLDUP:
3317 case X86ISD::MOVDDUP:
3320 case X86ISD::UNPCKL:
3321 case X86ISD::UNPCKH:
3322 case X86ISD::VPERMILP:
3323 case X86ISD::VPERM2X128:
3324 case X86ISD::VPERMI:
3329 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3330 SDValue V1, SelectionDAG &DAG) {
3332 default: llvm_unreachable("Unknown x86 shuffle node");
3333 case X86ISD::MOVSHDUP:
3334 case X86ISD::MOVSLDUP:
3335 case X86ISD::MOVDDUP:
3336 return DAG.getNode(Opc, dl, VT, V1);
3340 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3341 SDValue V1, unsigned TargetMask,
3342 SelectionDAG &DAG) {
3344 default: llvm_unreachable("Unknown x86 shuffle node");
3345 case X86ISD::PSHUFD:
3346 case X86ISD::PSHUFHW:
3347 case X86ISD::PSHUFLW:
3348 case X86ISD::VPERMILP:
3349 case X86ISD::VPERMI:
3350 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3354 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3355 SDValue V1, SDValue V2, unsigned TargetMask,
3356 SelectionDAG &DAG) {
3358 default: llvm_unreachable("Unknown x86 shuffle node");
3359 case X86ISD::PALIGNR:
3361 case X86ISD::VPERM2X128:
3362 return DAG.getNode(Opc, dl, VT, V1, V2,
3363 DAG.getConstant(TargetMask, MVT::i8));
3367 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3368 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3370 default: llvm_unreachable("Unknown x86 shuffle node");
3371 case X86ISD::MOVLHPS:
3372 case X86ISD::MOVLHPD:
3373 case X86ISD::MOVHLPS:
3374 case X86ISD::MOVLPS:
3375 case X86ISD::MOVLPD:
3378 case X86ISD::UNPCKL:
3379 case X86ISD::UNPCKH:
3380 return DAG.getNode(Opc, dl, VT, V1, V2);
3384 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3385 MachineFunction &MF = DAG.getMachineFunction();
3386 const X86RegisterInfo *RegInfo =
3387 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3388 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3389 int ReturnAddrIndex = FuncInfo->getRAIndex();
3391 if (ReturnAddrIndex == 0) {
3392 // Set up a frame object for the return address.
3393 unsigned SlotSize = RegInfo->getSlotSize();
3394 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3397 FuncInfo->setRAIndex(ReturnAddrIndex);
3400 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3403 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3404 bool hasSymbolicDisplacement) {
3405 // Offset should fit into 32 bit immediate field.
3406 if (!isInt<32>(Offset))
3409 // If we don't have a symbolic displacement - we don't have any extra
3411 if (!hasSymbolicDisplacement)
3414 // FIXME: Some tweaks might be needed for medium code model.
3415 if (M != CodeModel::Small && M != CodeModel::Kernel)
3418 // For small code model we assume that latest object is 16MB before end of 31
3419 // bits boundary. We may also accept pretty large negative constants knowing
3420 // that all objects are in the positive half of address space.
3421 if (M == CodeModel::Small && Offset < 16*1024*1024)
3424 // For kernel code model we know that all object resist in the negative half
3425 // of 32bits address space. We may not accept negative offsets, since they may
3426 // be just off and we may accept pretty large positive ones.
3427 if (M == CodeModel::Kernel && Offset > 0)
3433 /// isCalleePop - Determines whether the callee is required to pop its
3434 /// own arguments. Callee pop is necessary to support tail calls.
3435 bool X86::isCalleePop(CallingConv::ID CallingConv,
3436 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3440 switch (CallingConv) {
3443 case CallingConv::X86_StdCall:
3445 case CallingConv::X86_FastCall:
3447 case CallingConv::X86_ThisCall:
3449 case CallingConv::Fast:
3451 case CallingConv::GHC:
3453 case CallingConv::HiPE:
3458 /// \brief Return true if the condition is an unsigned comparison operation.
3459 static bool isX86CCUnsigned(unsigned X86CC) {
3461 default: llvm_unreachable("Invalid integer condition!");
3462 case X86::COND_E: return true;
3463 case X86::COND_G: return false;
3464 case X86::COND_GE: return false;
3465 case X86::COND_L: return false;
3466 case X86::COND_LE: return false;
3467 case X86::COND_NE: return true;
3468 case X86::COND_B: return true;
3469 case X86::COND_A: return true;
3470 case X86::COND_BE: return true;
3471 case X86::COND_AE: return true;
3473 llvm_unreachable("covered switch fell through?!");
3476 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3477 /// specific condition code, returning the condition code and the LHS/RHS of the
3478 /// comparison to make.
3479 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3480 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3482 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3483 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3484 // X > -1 -> X == 0, jump !sign.
3485 RHS = DAG.getConstant(0, RHS.getValueType());
3486 return X86::COND_NS;
3488 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3489 // X < 0 -> X == 0, jump on sign.
3492 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3494 RHS = DAG.getConstant(0, RHS.getValueType());
3495 return X86::COND_LE;
3499 switch (SetCCOpcode) {
3500 default: llvm_unreachable("Invalid integer condition!");
3501 case ISD::SETEQ: return X86::COND_E;
3502 case ISD::SETGT: return X86::COND_G;
3503 case ISD::SETGE: return X86::COND_GE;
3504 case ISD::SETLT: return X86::COND_L;
3505 case ISD::SETLE: return X86::COND_LE;
3506 case ISD::SETNE: return X86::COND_NE;
3507 case ISD::SETULT: return X86::COND_B;
3508 case ISD::SETUGT: return X86::COND_A;
3509 case ISD::SETULE: return X86::COND_BE;
3510 case ISD::SETUGE: return X86::COND_AE;
3514 // First determine if it is required or is profitable to flip the operands.
3516 // If LHS is a foldable load, but RHS is not, flip the condition.
3517 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3518 !ISD::isNON_EXTLoad(RHS.getNode())) {
3519 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3520 std::swap(LHS, RHS);
3523 switch (SetCCOpcode) {
3529 std::swap(LHS, RHS);
3533 // On a floating point condition, the flags are set as follows:
3535 // 0 | 0 | 0 | X > Y
3536 // 0 | 0 | 1 | X < Y
3537 // 1 | 0 | 0 | X == Y
3538 // 1 | 1 | 1 | unordered
3539 switch (SetCCOpcode) {
3540 default: llvm_unreachable("Condcode should be pre-legalized away");
3542 case ISD::SETEQ: return X86::COND_E;
3543 case ISD::SETOLT: // flipped
3545 case ISD::SETGT: return X86::COND_A;
3546 case ISD::SETOLE: // flipped
3548 case ISD::SETGE: return X86::COND_AE;
3549 case ISD::SETUGT: // flipped
3551 case ISD::SETLT: return X86::COND_B;
3552 case ISD::SETUGE: // flipped
3554 case ISD::SETLE: return X86::COND_BE;
3556 case ISD::SETNE: return X86::COND_NE;
3557 case ISD::SETUO: return X86::COND_P;
3558 case ISD::SETO: return X86::COND_NP;
3560 case ISD::SETUNE: return X86::COND_INVALID;
3564 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3565 /// code. Current x86 isa includes the following FP cmov instructions:
3566 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3567 static bool hasFPCMov(unsigned X86CC) {
3583 /// isFPImmLegal - Returns true if the target can instruction select the
3584 /// specified FP immediate natively. If false, the legalizer will
3585 /// materialize the FP immediate as a load from a constant pool.
3586 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3587 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3588 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3594 /// \brief Returns true if it is beneficial to convert a load of a constant
3595 /// to just the constant itself.
3596 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3598 assert(Ty->isIntegerTy());
3600 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3601 if (BitSize == 0 || BitSize > 64)
3606 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3607 /// the specified range (L, H].
3608 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3609 return (Val < 0) || (Val >= Low && Val < Hi);
3612 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3613 /// specified value.
3614 static bool isUndefOrEqual(int Val, int CmpVal) {
3615 return (Val < 0 || Val == CmpVal);
3618 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3619 /// from position Pos and ending in Pos+Size, falls within the specified
3620 /// sequential range (L, L+Pos]. or is undef.
3621 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3622 unsigned Pos, unsigned Size, int Low) {
3623 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3624 if (!isUndefOrEqual(Mask[i], Low))
3629 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3630 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3631 /// the second operand.
3632 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3633 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3634 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3635 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3636 return (Mask[0] < 2 && Mask[1] < 2);
3640 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3641 /// is suitable for input to PSHUFHW.
3642 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3643 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3646 // Lower quadword copied in order or undef.
3647 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3650 // Upper quadword shuffled.
3651 for (unsigned i = 4; i != 8; ++i)
3652 if (!isUndefOrInRange(Mask[i], 4, 8))
3655 if (VT == MVT::v16i16) {
3656 // Lower quadword copied in order or undef.
3657 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3660 // Upper quadword shuffled.
3661 for (unsigned i = 12; i != 16; ++i)
3662 if (!isUndefOrInRange(Mask[i], 12, 16))
3669 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3670 /// is suitable for input to PSHUFLW.
3671 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3672 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3675 // Upper quadword copied in order.
3676 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3679 // Lower quadword shuffled.
3680 for (unsigned i = 0; i != 4; ++i)
3681 if (!isUndefOrInRange(Mask[i], 0, 4))
3684 if (VT == MVT::v16i16) {
3685 // Upper quadword copied in order.
3686 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3689 // Lower quadword shuffled.
3690 for (unsigned i = 8; i != 12; ++i)
3691 if (!isUndefOrInRange(Mask[i], 8, 12))
3698 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3699 /// is suitable for input to PALIGNR.
3700 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3701 const X86Subtarget *Subtarget) {
3702 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3703 (VT.is256BitVector() && !Subtarget->hasInt256()))
3706 unsigned NumElts = VT.getVectorNumElements();
3707 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3708 unsigned NumLaneElts = NumElts/NumLanes;
3710 // Do not handle 64-bit element shuffles with palignr.
3711 if (NumLaneElts == 2)
3714 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3716 for (i = 0; i != NumLaneElts; ++i) {
3721 // Lane is all undef, go to next lane
3722 if (i == NumLaneElts)
3725 int Start = Mask[i+l];
3727 // Make sure its in this lane in one of the sources
3728 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3729 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3732 // If not lane 0, then we must match lane 0
3733 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3736 // Correct second source to be contiguous with first source
3737 if (Start >= (int)NumElts)
3738 Start -= NumElts - NumLaneElts;
3740 // Make sure we're shifting in the right direction.
3741 if (Start <= (int)(i+l))
3746 // Check the rest of the elements to see if they are consecutive.
3747 for (++i; i != NumLaneElts; ++i) {
3748 int Idx = Mask[i+l];
3750 // Make sure its in this lane
3751 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3752 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3755 // If not lane 0, then we must match lane 0
3756 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3759 if (Idx >= (int)NumElts)
3760 Idx -= NumElts - NumLaneElts;
3762 if (!isUndefOrEqual(Idx, Start+i))
3771 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3772 /// the two vector operands have swapped position.
3773 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3774 unsigned NumElems) {
3775 for (unsigned i = 0; i != NumElems; ++i) {
3779 else if (idx < (int)NumElems)
3780 Mask[i] = idx + NumElems;
3782 Mask[i] = idx - NumElems;
3786 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3787 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3788 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3789 /// reverse of what x86 shuffles want.
3790 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3792 unsigned NumElems = VT.getVectorNumElements();
3793 unsigned NumLanes = VT.getSizeInBits()/128;
3794 unsigned NumLaneElems = NumElems/NumLanes;
3796 if (NumLaneElems != 2 && NumLaneElems != 4)
3799 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3800 bool symetricMaskRequired =
3801 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3803 // VSHUFPSY divides the resulting vector into 4 chunks.
3804 // The sources are also splitted into 4 chunks, and each destination
3805 // chunk must come from a different source chunk.
3807 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3808 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3810 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3811 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3813 // VSHUFPDY divides the resulting vector into 4 chunks.
3814 // The sources are also splitted into 4 chunks, and each destination
3815 // chunk must come from a different source chunk.
3817 // SRC1 => X3 X2 X1 X0
3818 // SRC2 => Y3 Y2 Y1 Y0
3820 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3822 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3823 unsigned HalfLaneElems = NumLaneElems/2;
3824 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3825 for (unsigned i = 0; i != NumLaneElems; ++i) {
3826 int Idx = Mask[i+l];
3827 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3828 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3830 // For VSHUFPSY, the mask of the second half must be the same as the
3831 // first but with the appropriate offsets. This works in the same way as
3832 // VPERMILPS works with masks.
3833 if (!symetricMaskRequired || Idx < 0)
3835 if (MaskVal[i] < 0) {
3836 MaskVal[i] = Idx - l;
3839 if ((signed)(Idx - l) != MaskVal[i])
3847 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3848 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3849 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3850 if (!VT.is128BitVector())
3853 unsigned NumElems = VT.getVectorNumElements();
3858 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3859 return isUndefOrEqual(Mask[0], 6) &&
3860 isUndefOrEqual(Mask[1], 7) &&
3861 isUndefOrEqual(Mask[2], 2) &&
3862 isUndefOrEqual(Mask[3], 3);
3865 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3866 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3868 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3869 if (!VT.is128BitVector())
3872 unsigned NumElems = VT.getVectorNumElements();
3877 return isUndefOrEqual(Mask[0], 2) &&
3878 isUndefOrEqual(Mask[1], 3) &&
3879 isUndefOrEqual(Mask[2], 2) &&
3880 isUndefOrEqual(Mask[3], 3);
3883 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3884 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3885 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3886 if (!VT.is128BitVector())
3889 unsigned NumElems = VT.getVectorNumElements();
3891 if (NumElems != 2 && NumElems != 4)
3894 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3895 if (!isUndefOrEqual(Mask[i], i + NumElems))
3898 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3899 if (!isUndefOrEqual(Mask[i], i))
3905 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3906 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3907 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3908 if (!VT.is128BitVector())
3911 unsigned NumElems = VT.getVectorNumElements();
3913 if (NumElems != 2 && NumElems != 4)
3916 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3917 if (!isUndefOrEqual(Mask[i], i))
3920 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3921 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3928 // Some special combinations that can be optimized.
3931 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3932 SelectionDAG &DAG) {
3933 MVT VT = SVOp->getSimpleValueType(0);
3936 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3939 ArrayRef<int> Mask = SVOp->getMask();
3941 // These are the special masks that may be optimized.
3942 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3943 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3944 bool MatchEvenMask = true;
3945 bool MatchOddMask = true;
3946 for (int i=0; i<8; ++i) {
3947 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3948 MatchEvenMask = false;
3949 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3950 MatchOddMask = false;
3953 if (!MatchEvenMask && !MatchOddMask)
3956 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3958 SDValue Op0 = SVOp->getOperand(0);
3959 SDValue Op1 = SVOp->getOperand(1);
3961 if (MatchEvenMask) {
3962 // Shift the second operand right to 32 bits.
3963 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3964 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3966 // Shift the first operand left to 32 bits.
3967 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3968 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3970 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3971 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3974 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3975 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3976 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3977 bool HasInt256, bool V2IsSplat = false) {
3979 assert(VT.getSizeInBits() >= 128 &&
3980 "Unsupported vector type for unpckl");
3982 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3984 unsigned NumOf256BitLanes;
3985 unsigned NumElts = VT.getVectorNumElements();
3986 if (VT.is256BitVector()) {
3987 if (NumElts != 4 && NumElts != 8 &&
3988 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3991 NumOf256BitLanes = 1;
3992 } else if (VT.is512BitVector()) {
3993 assert(VT.getScalarType().getSizeInBits() >= 32 &&
3994 "Unsupported vector type for unpckh");
3996 NumOf256BitLanes = 2;
3999 NumOf256BitLanes = 1;
4002 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4003 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4005 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4006 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4007 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4008 int BitI = Mask[l256*NumEltsInStride+l+i];
4009 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4010 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4012 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4014 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4022 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4023 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4024 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4025 bool HasInt256, bool V2IsSplat = false) {
4026 assert(VT.getSizeInBits() >= 128 &&
4027 "Unsupported vector type for unpckh");
4029 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4031 unsigned NumOf256BitLanes;
4032 unsigned NumElts = VT.getVectorNumElements();
4033 if (VT.is256BitVector()) {
4034 if (NumElts != 4 && NumElts != 8 &&
4035 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4038 NumOf256BitLanes = 1;
4039 } else if (VT.is512BitVector()) {
4040 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4041 "Unsupported vector type for unpckh");
4043 NumOf256BitLanes = 2;
4046 NumOf256BitLanes = 1;
4049 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4050 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4052 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4053 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4054 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4055 int BitI = Mask[l256*NumEltsInStride+l+i];
4056 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4057 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4059 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4061 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4069 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4070 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4072 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4073 unsigned NumElts = VT.getVectorNumElements();
4074 bool Is256BitVec = VT.is256BitVector();
4076 if (VT.is512BitVector())
4078 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4079 "Unsupported vector type for unpckh");
4081 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4082 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4085 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4086 // FIXME: Need a better way to get rid of this, there's no latency difference
4087 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4088 // the former later. We should also remove the "_undef" special mask.
4089 if (NumElts == 4 && Is256BitVec)
4092 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4093 // independently on 128-bit lanes.
4094 unsigned NumLanes = VT.getSizeInBits()/128;
4095 unsigned NumLaneElts = NumElts/NumLanes;
4097 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4098 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4099 int BitI = Mask[l+i];
4100 int BitI1 = Mask[l+i+1];
4102 if (!isUndefOrEqual(BitI, j))
4104 if (!isUndefOrEqual(BitI1, j))
4112 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4113 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4115 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4116 unsigned NumElts = VT.getVectorNumElements();
4118 if (VT.is512BitVector())
4121 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4122 "Unsupported vector type for unpckh");
4124 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4125 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4128 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4129 // independently on 128-bit lanes.
4130 unsigned NumLanes = VT.getSizeInBits()/128;
4131 unsigned NumLaneElts = NumElts/NumLanes;
4133 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4134 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4135 int BitI = Mask[l+i];
4136 int BitI1 = Mask[l+i+1];
4137 if (!isUndefOrEqual(BitI, j))
4139 if (!isUndefOrEqual(BitI1, j))
4146 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4147 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4148 /// MOVSD, and MOVD, i.e. setting the lowest element.
4149 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4150 if (VT.getVectorElementType().getSizeInBits() < 32)
4152 if (!VT.is128BitVector())
4155 unsigned NumElts = VT.getVectorNumElements();
4157 if (!isUndefOrEqual(Mask[0], NumElts))
4160 for (unsigned i = 1; i != NumElts; ++i)
4161 if (!isUndefOrEqual(Mask[i], i))
4167 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4168 /// as permutations between 128-bit chunks or halves. As an example: this
4170 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4171 /// The first half comes from the second half of V1 and the second half from the
4172 /// the second half of V2.
4173 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4174 if (!HasFp256 || !VT.is256BitVector())
4177 // The shuffle result is divided into half A and half B. In total the two
4178 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4179 // B must come from C, D, E or F.
4180 unsigned HalfSize = VT.getVectorNumElements()/2;
4181 bool MatchA = false, MatchB = false;
4183 // Check if A comes from one of C, D, E, F.
4184 for (unsigned Half = 0; Half != 4; ++Half) {
4185 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4191 // Check if B comes from one of C, D, E, F.
4192 for (unsigned Half = 0; Half != 4; ++Half) {
4193 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4199 return MatchA && MatchB;
4202 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4203 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4204 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4205 MVT VT = SVOp->getSimpleValueType(0);
4207 unsigned HalfSize = VT.getVectorNumElements()/2;
4209 unsigned FstHalf = 0, SndHalf = 0;
4210 for (unsigned i = 0; i < HalfSize; ++i) {
4211 if (SVOp->getMaskElt(i) > 0) {
4212 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4216 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4217 if (SVOp->getMaskElt(i) > 0) {
4218 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4223 return (FstHalf | (SndHalf << 4));
4226 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4227 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4228 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4232 unsigned NumElts = VT.getVectorNumElements();
4234 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4235 for (unsigned i = 0; i != NumElts; ++i) {
4238 Imm8 |= Mask[i] << (i*2);
4243 unsigned LaneSize = 4;
4244 SmallVector<int, 4> MaskVal(LaneSize, -1);
4246 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4247 for (unsigned i = 0; i != LaneSize; ++i) {
4248 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4252 if (MaskVal[i] < 0) {
4253 MaskVal[i] = Mask[i+l] - l;
4254 Imm8 |= MaskVal[i] << (i*2);
4257 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4264 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4265 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4266 /// Note that VPERMIL mask matching is different depending whether theunderlying
4267 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4268 /// to the same elements of the low, but to the higher half of the source.
4269 /// In VPERMILPD the two lanes could be shuffled independently of each other
4270 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4271 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4272 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4273 if (VT.getSizeInBits() < 256 || EltSize < 32)
4275 bool symetricMaskRequired = (EltSize == 32);
4276 unsigned NumElts = VT.getVectorNumElements();
4278 unsigned NumLanes = VT.getSizeInBits()/128;
4279 unsigned LaneSize = NumElts/NumLanes;
4280 // 2 or 4 elements in one lane
4282 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4283 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4284 for (unsigned i = 0; i != LaneSize; ++i) {
4285 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4287 if (symetricMaskRequired) {
4288 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4289 ExpectedMaskVal[i] = Mask[i+l] - l;
4292 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4300 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4301 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4302 /// element of vector 2 and the other elements to come from vector 1 in order.
4303 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4304 bool V2IsSplat = false, bool V2IsUndef = false) {
4305 if (!VT.is128BitVector())
4308 unsigned NumOps = VT.getVectorNumElements();
4309 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4312 if (!isUndefOrEqual(Mask[0], 0))
4315 for (unsigned i = 1; i != NumOps; ++i)
4316 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4317 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4318 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4324 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4325 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4326 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4327 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4328 const X86Subtarget *Subtarget) {
4329 if (!Subtarget->hasSSE3())
4332 unsigned NumElems = VT.getVectorNumElements();
4334 if ((VT.is128BitVector() && NumElems != 4) ||
4335 (VT.is256BitVector() && NumElems != 8) ||
4336 (VT.is512BitVector() && NumElems != 16))
4339 // "i+1" is the value the indexed mask element must have
4340 for (unsigned i = 0; i != NumElems; i += 2)
4341 if (!isUndefOrEqual(Mask[i], i+1) ||
4342 !isUndefOrEqual(Mask[i+1], i+1))
4348 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4349 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4350 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4351 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4352 const X86Subtarget *Subtarget) {
4353 if (!Subtarget->hasSSE3())
4356 unsigned NumElems = VT.getVectorNumElements();
4358 if ((VT.is128BitVector() && NumElems != 4) ||
4359 (VT.is256BitVector() && NumElems != 8) ||
4360 (VT.is512BitVector() && NumElems != 16))
4363 // "i" is the value the indexed mask element must have
4364 for (unsigned i = 0; i != NumElems; i += 2)
4365 if (!isUndefOrEqual(Mask[i], i) ||
4366 !isUndefOrEqual(Mask[i+1], i))
4372 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4373 /// specifies a shuffle of elements that is suitable for input to 256-bit
4374 /// version of MOVDDUP.
4375 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4376 if (!HasFp256 || !VT.is256BitVector())
4379 unsigned NumElts = VT.getVectorNumElements();
4383 for (unsigned i = 0; i != NumElts/2; ++i)
4384 if (!isUndefOrEqual(Mask[i], 0))
4386 for (unsigned i = NumElts/2; i != NumElts; ++i)
4387 if (!isUndefOrEqual(Mask[i], NumElts/2))
4392 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4393 /// specifies a shuffle of elements that is suitable for input to 128-bit
4394 /// version of MOVDDUP.
4395 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4396 if (!VT.is128BitVector())
4399 unsigned e = VT.getVectorNumElements() / 2;
4400 for (unsigned i = 0; i != e; ++i)
4401 if (!isUndefOrEqual(Mask[i], i))
4403 for (unsigned i = 0; i != e; ++i)
4404 if (!isUndefOrEqual(Mask[e+i], i))
4409 /// isVEXTRACTIndex - Return true if the specified
4410 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4411 /// suitable for instruction that extract 128 or 256 bit vectors
4412 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4413 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4414 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4417 // The index should be aligned on a vecWidth-bit boundary.
4419 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4421 MVT VT = N->getSimpleValueType(0);
4422 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4423 bool Result = (Index * ElSize) % vecWidth == 0;
4428 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4429 /// operand specifies a subvector insert that is suitable for input to
4430 /// insertion of 128 or 256-bit subvectors
4431 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4432 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4433 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4435 // The index should be aligned on a vecWidth-bit boundary.
4437 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4439 MVT VT = N->getSimpleValueType(0);
4440 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4441 bool Result = (Index * ElSize) % vecWidth == 0;
4446 bool X86::isVINSERT128Index(SDNode *N) {
4447 return isVINSERTIndex(N, 128);
4450 bool X86::isVINSERT256Index(SDNode *N) {
4451 return isVINSERTIndex(N, 256);
4454 bool X86::isVEXTRACT128Index(SDNode *N) {
4455 return isVEXTRACTIndex(N, 128);
4458 bool X86::isVEXTRACT256Index(SDNode *N) {
4459 return isVEXTRACTIndex(N, 256);
4462 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4463 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4464 /// Handles 128-bit and 256-bit.
4465 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4466 MVT VT = N->getSimpleValueType(0);
4468 assert((VT.getSizeInBits() >= 128) &&
4469 "Unsupported vector type for PSHUF/SHUFP");
4471 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4472 // independently on 128-bit lanes.
4473 unsigned NumElts = VT.getVectorNumElements();
4474 unsigned NumLanes = VT.getSizeInBits()/128;
4475 unsigned NumLaneElts = NumElts/NumLanes;
4477 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4478 "Only supports 2, 4 or 8 elements per lane");
4480 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4482 for (unsigned i = 0; i != NumElts; ++i) {
4483 int Elt = N->getMaskElt(i);
4484 if (Elt < 0) continue;
4485 Elt &= NumLaneElts - 1;
4486 unsigned ShAmt = (i << Shift) % 8;
4487 Mask |= Elt << ShAmt;
4493 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4494 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4495 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4496 MVT VT = N->getSimpleValueType(0);
4498 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4499 "Unsupported vector type for PSHUFHW");
4501 unsigned NumElts = VT.getVectorNumElements();
4504 for (unsigned l = 0; l != NumElts; l += 8) {
4505 // 8 nodes per lane, but we only care about the last 4.
4506 for (unsigned i = 0; i < 4; ++i) {
4507 int Elt = N->getMaskElt(l+i+4);
4508 if (Elt < 0) continue;
4509 Elt &= 0x3; // only 2-bits.
4510 Mask |= Elt << (i * 2);
4517 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4518 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4519 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4520 MVT VT = N->getSimpleValueType(0);
4522 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4523 "Unsupported vector type for PSHUFHW");
4525 unsigned NumElts = VT.getVectorNumElements();
4528 for (unsigned l = 0; l != NumElts; l += 8) {
4529 // 8 nodes per lane, but we only care about the first 4.
4530 for (unsigned i = 0; i < 4; ++i) {
4531 int Elt = N->getMaskElt(l+i);
4532 if (Elt < 0) continue;
4533 Elt &= 0x3; // only 2-bits
4534 Mask |= Elt << (i * 2);
4541 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4542 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4543 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4544 MVT VT = SVOp->getSimpleValueType(0);
4545 unsigned EltSize = VT.is512BitVector() ? 1 :
4546 VT.getVectorElementType().getSizeInBits() >> 3;
4548 unsigned NumElts = VT.getVectorNumElements();
4549 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4550 unsigned NumLaneElts = NumElts/NumLanes;
4554 for (i = 0; i != NumElts; ++i) {
4555 Val = SVOp->getMaskElt(i);
4559 if (Val >= (int)NumElts)
4560 Val -= NumElts - NumLaneElts;
4562 assert(Val - i > 0 && "PALIGNR imm should be positive");
4563 return (Val - i) * EltSize;
4566 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4567 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4568 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4569 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4572 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4574 MVT VecVT = N->getOperand(0).getSimpleValueType();
4575 MVT ElVT = VecVT.getVectorElementType();
4577 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4578 return Index / NumElemsPerChunk;
4581 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4582 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4583 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4584 llvm_unreachable("Illegal insert subvector for VINSERT");
4587 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4589 MVT VecVT = N->getSimpleValueType(0);
4590 MVT ElVT = VecVT.getVectorElementType();
4592 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4593 return Index / NumElemsPerChunk;
4596 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4597 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4598 /// and VINSERTI128 instructions.
4599 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4600 return getExtractVEXTRACTImmediate(N, 128);
4603 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4604 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4605 /// and VINSERTI64x4 instructions.
4606 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4607 return getExtractVEXTRACTImmediate(N, 256);
4610 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4611 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4612 /// and VINSERTI128 instructions.
4613 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4614 return getInsertVINSERTImmediate(N, 128);
4617 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4618 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4619 /// and VINSERTI64x4 instructions.
4620 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4621 return getInsertVINSERTImmediate(N, 256);
4624 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4626 bool X86::isZeroNode(SDValue Elt) {
4627 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4628 return CN->isNullValue();
4629 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4630 return CFP->getValueAPF().isPosZero();
4634 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4635 /// their permute mask.
4636 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4637 SelectionDAG &DAG) {
4638 MVT VT = SVOp->getSimpleValueType(0);
4639 unsigned NumElems = VT.getVectorNumElements();
4640 SmallVector<int, 8> MaskVec;
4642 for (unsigned i = 0; i != NumElems; ++i) {
4643 int Idx = SVOp->getMaskElt(i);
4645 if (Idx < (int)NumElems)
4650 MaskVec.push_back(Idx);
4652 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4653 SVOp->getOperand(0), &MaskVec[0]);
4656 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4657 /// match movhlps. The lower half elements should come from upper half of
4658 /// V1 (and in order), and the upper half elements should come from the upper
4659 /// half of V2 (and in order).
4660 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4661 if (!VT.is128BitVector())
4663 if (VT.getVectorNumElements() != 4)
4665 for (unsigned i = 0, e = 2; i != e; ++i)
4666 if (!isUndefOrEqual(Mask[i], i+2))
4668 for (unsigned i = 2; i != 4; ++i)
4669 if (!isUndefOrEqual(Mask[i], i+4))
4674 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4675 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4677 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4678 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4680 N = N->getOperand(0).getNode();
4681 if (!ISD::isNON_EXTLoad(N))
4684 *LD = cast<LoadSDNode>(N);
4688 // Test whether the given value is a vector value which will be legalized
4690 static bool WillBeConstantPoolLoad(SDNode *N) {
4691 if (N->getOpcode() != ISD::BUILD_VECTOR)
4694 // Check for any non-constant elements.
4695 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4696 switch (N->getOperand(i).getNode()->getOpcode()) {
4698 case ISD::ConstantFP:
4705 // Vectors of all-zeros and all-ones are materialized with special
4706 // instructions rather than being loaded.
4707 return !ISD::isBuildVectorAllZeros(N) &&
4708 !ISD::isBuildVectorAllOnes(N);
4711 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4712 /// match movlp{s|d}. The lower half elements should come from lower half of
4713 /// V1 (and in order), and the upper half elements should come from the upper
4714 /// half of V2 (and in order). And since V1 will become the source of the
4715 /// MOVLP, it must be either a vector load or a scalar load to vector.
4716 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4717 ArrayRef<int> Mask, MVT VT) {
4718 if (!VT.is128BitVector())
4721 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4723 // Is V2 is a vector load, don't do this transformation. We will try to use
4724 // load folding shufps op.
4725 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4728 unsigned NumElems = VT.getVectorNumElements();
4730 if (NumElems != 2 && NumElems != 4)
4732 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4733 if (!isUndefOrEqual(Mask[i], i))
4735 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4736 if (!isUndefOrEqual(Mask[i], i+NumElems))
4741 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4743 static bool isSplatVector(SDNode *N) {
4744 if (N->getOpcode() != ISD::BUILD_VECTOR)
4747 SDValue SplatValue = N->getOperand(0);
4748 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4749 if (N->getOperand(i) != SplatValue)
4754 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4755 /// to an zero vector.
4756 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4757 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4758 SDValue V1 = N->getOperand(0);
4759 SDValue V2 = N->getOperand(1);
4760 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4761 for (unsigned i = 0; i != NumElems; ++i) {
4762 int Idx = N->getMaskElt(i);
4763 if (Idx >= (int)NumElems) {
4764 unsigned Opc = V2.getOpcode();
4765 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4767 if (Opc != ISD::BUILD_VECTOR ||
4768 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4770 } else if (Idx >= 0) {
4771 unsigned Opc = V1.getOpcode();
4772 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4774 if (Opc != ISD::BUILD_VECTOR ||
4775 !X86::isZeroNode(V1.getOperand(Idx)))
4782 /// getZeroVector - Returns a vector of specified type with all zero elements.
4784 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4785 SelectionDAG &DAG, SDLoc dl) {
4786 assert(VT.isVector() && "Expected a vector type");
4788 // Always build SSE zero vectors as <4 x i32> bitcasted
4789 // to their dest type. This ensures they get CSE'd.
4791 if (VT.is128BitVector()) { // SSE
4792 if (Subtarget->hasSSE2()) { // SSE2
4793 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4794 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4796 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4797 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4799 } else if (VT.is256BitVector()) { // AVX
4800 if (Subtarget->hasInt256()) { // AVX2
4801 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4802 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4803 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4804 array_lengthof(Ops));
4806 // 256-bit logic and arithmetic instructions in AVX are all
4807 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4808 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4809 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4810 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4811 array_lengthof(Ops));
4813 } else if (VT.is512BitVector()) { // AVX-512
4814 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4815 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4816 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4817 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4818 } else if (VT.getScalarType() == MVT::i1) {
4819 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4820 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4821 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4822 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4823 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4824 Ops, VT.getVectorNumElements());
4826 llvm_unreachable("Unexpected vector type");
4828 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4831 /// getOnesVector - Returns a vector of specified type with all bits set.
4832 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4833 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4834 /// Then bitcast to their original type, ensuring they get CSE'd.
4835 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4837 assert(VT.isVector() && "Expected a vector type");
4839 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4841 if (VT.is256BitVector()) {
4842 if (HasInt256) { // AVX2
4843 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4844 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4845 array_lengthof(Ops));
4847 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4848 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4850 } else if (VT.is128BitVector()) {
4851 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4853 llvm_unreachable("Unexpected vector type");
4855 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4858 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4859 /// that point to V2 points to its first element.
4860 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4861 for (unsigned i = 0; i != NumElems; ++i) {
4862 if (Mask[i] > (int)NumElems) {
4868 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4869 /// operation of specified width.
4870 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4872 unsigned NumElems = VT.getVectorNumElements();
4873 SmallVector<int, 8> Mask;
4874 Mask.push_back(NumElems);
4875 for (unsigned i = 1; i != NumElems; ++i)
4877 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4880 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4881 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4883 unsigned NumElems = VT.getVectorNumElements();
4884 SmallVector<int, 8> Mask;
4885 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4887 Mask.push_back(i + NumElems);
4889 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4892 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4893 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4895 unsigned NumElems = VT.getVectorNumElements();
4896 SmallVector<int, 8> Mask;
4897 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4898 Mask.push_back(i + Half);
4899 Mask.push_back(i + NumElems + Half);
4901 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4904 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4905 // a generic shuffle instruction because the target has no such instructions.
4906 // Generate shuffles which repeat i16 and i8 several times until they can be
4907 // represented by v4f32 and then be manipulated by target suported shuffles.
4908 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4909 MVT VT = V.getSimpleValueType();
4910 int NumElems = VT.getVectorNumElements();
4913 while (NumElems > 4) {
4914 if (EltNo < NumElems/2) {
4915 V = getUnpackl(DAG, dl, VT, V, V);
4917 V = getUnpackh(DAG, dl, VT, V, V);
4918 EltNo -= NumElems/2;
4925 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4926 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4927 MVT VT = V.getSimpleValueType();
4930 if (VT.is128BitVector()) {
4931 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4932 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4933 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4935 } else if (VT.is256BitVector()) {
4936 // To use VPERMILPS to splat scalars, the second half of indicies must
4937 // refer to the higher part, which is a duplication of the lower one,
4938 // because VPERMILPS can only handle in-lane permutations.
4939 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4940 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4942 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4943 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4946 llvm_unreachable("Vector size not supported");
4948 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4951 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4952 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4953 MVT SrcVT = SV->getSimpleValueType(0);
4954 SDValue V1 = SV->getOperand(0);
4957 int EltNo = SV->getSplatIndex();
4958 int NumElems = SrcVT.getVectorNumElements();
4959 bool Is256BitVec = SrcVT.is256BitVector();
4961 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4962 "Unknown how to promote splat for type");
4964 // Extract the 128-bit part containing the splat element and update
4965 // the splat element index when it refers to the higher register.
4967 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4968 if (EltNo >= NumElems/2)
4969 EltNo -= NumElems/2;
4972 // All i16 and i8 vector types can't be used directly by a generic shuffle
4973 // instruction because the target has no such instruction. Generate shuffles
4974 // which repeat i16 and i8 several times until they fit in i32, and then can
4975 // be manipulated by target suported shuffles.
4976 MVT EltVT = SrcVT.getVectorElementType();
4977 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4978 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4980 // Recreate the 256-bit vector and place the same 128-bit vector
4981 // into the low and high part. This is necessary because we want
4982 // to use VPERM* to shuffle the vectors
4984 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4987 return getLegalSplat(DAG, V1, EltNo);
4990 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4991 /// vector of zero or undef vector. This produces a shuffle where the low
4992 /// element of V2 is swizzled into the zero/undef vector, landing at element
4993 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4994 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4996 const X86Subtarget *Subtarget,
4997 SelectionDAG &DAG) {
4998 MVT VT = V2.getSimpleValueType();
5000 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5001 unsigned NumElems = VT.getVectorNumElements();
5002 SmallVector<int, 16> MaskVec;
5003 for (unsigned i = 0; i != NumElems; ++i)
5004 // If this is the insertion idx, put the low elt of V2 here.
5005 MaskVec.push_back(i == Idx ? NumElems : i);
5006 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5009 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5010 /// target specific opcode. Returns true if the Mask could be calculated.
5011 /// Sets IsUnary to true if only uses one source.
5012 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5013 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5014 unsigned NumElems = VT.getVectorNumElements();
5018 switch(N->getOpcode()) {
5020 ImmN = N->getOperand(N->getNumOperands()-1);
5021 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5023 case X86ISD::UNPCKH:
5024 DecodeUNPCKHMask(VT, Mask);
5026 case X86ISD::UNPCKL:
5027 DecodeUNPCKLMask(VT, Mask);
5029 case X86ISD::MOVHLPS:
5030 DecodeMOVHLPSMask(NumElems, Mask);
5032 case X86ISD::MOVLHPS:
5033 DecodeMOVLHPSMask(NumElems, Mask);
5035 case X86ISD::PALIGNR:
5036 ImmN = N->getOperand(N->getNumOperands()-1);
5037 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5039 case X86ISD::PSHUFD:
5040 case X86ISD::VPERMILP:
5041 ImmN = N->getOperand(N->getNumOperands()-1);
5042 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5045 case X86ISD::PSHUFHW:
5046 ImmN = N->getOperand(N->getNumOperands()-1);
5047 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5050 case X86ISD::PSHUFLW:
5051 ImmN = N->getOperand(N->getNumOperands()-1);
5052 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5055 case X86ISD::VPERMI:
5056 ImmN = N->getOperand(N->getNumOperands()-1);
5057 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5061 case X86ISD::MOVSD: {
5062 // The index 0 always comes from the first element of the second source,
5063 // this is why MOVSS and MOVSD are used in the first place. The other
5064 // elements come from the other positions of the first source vector
5065 Mask.push_back(NumElems);
5066 for (unsigned i = 1; i != NumElems; ++i) {
5071 case X86ISD::VPERM2X128:
5072 ImmN = N->getOperand(N->getNumOperands()-1);
5073 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5074 if (Mask.empty()) return false;
5076 case X86ISD::MOVDDUP:
5077 case X86ISD::MOVLHPD:
5078 case X86ISD::MOVLPD:
5079 case X86ISD::MOVLPS:
5080 case X86ISD::MOVSHDUP:
5081 case X86ISD::MOVSLDUP:
5082 // Not yet implemented
5084 default: llvm_unreachable("unknown target shuffle node");
5090 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5091 /// element of the result of the vector shuffle.
5092 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5095 return SDValue(); // Limit search depth.
5097 SDValue V = SDValue(N, 0);
5098 EVT VT = V.getValueType();
5099 unsigned Opcode = V.getOpcode();
5101 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5102 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5103 int Elt = SV->getMaskElt(Index);
5106 return DAG.getUNDEF(VT.getVectorElementType());
5108 unsigned NumElems = VT.getVectorNumElements();
5109 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5110 : SV->getOperand(1);
5111 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5114 // Recurse into target specific vector shuffles to find scalars.
5115 if (isTargetShuffle(Opcode)) {
5116 MVT ShufVT = V.getSimpleValueType();
5117 unsigned NumElems = ShufVT.getVectorNumElements();
5118 SmallVector<int, 16> ShuffleMask;
5121 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5124 int Elt = ShuffleMask[Index];
5126 return DAG.getUNDEF(ShufVT.getVectorElementType());
5128 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5130 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5134 // Actual nodes that may contain scalar elements
5135 if (Opcode == ISD::BITCAST) {
5136 V = V.getOperand(0);
5137 EVT SrcVT = V.getValueType();
5138 unsigned NumElems = VT.getVectorNumElements();
5140 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5144 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5145 return (Index == 0) ? V.getOperand(0)
5146 : DAG.getUNDEF(VT.getVectorElementType());
5148 if (V.getOpcode() == ISD::BUILD_VECTOR)
5149 return V.getOperand(Index);
5154 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5155 /// shuffle operation which come from a consecutively from a zero. The
5156 /// search can start in two different directions, from left or right.
5157 /// We count undefs as zeros until PreferredNum is reached.
5158 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5159 unsigned NumElems, bool ZerosFromLeft,
5161 unsigned PreferredNum = -1U) {
5162 unsigned NumZeros = 0;
5163 for (unsigned i = 0; i != NumElems; ++i) {
5164 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5165 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5169 if (X86::isZeroNode(Elt))
5171 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5172 NumZeros = std::min(NumZeros + 1, PreferredNum);
5180 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5181 /// correspond consecutively to elements from one of the vector operands,
5182 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5184 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5185 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5186 unsigned NumElems, unsigned &OpNum) {
5187 bool SeenV1 = false;
5188 bool SeenV2 = false;
5190 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5191 int Idx = SVOp->getMaskElt(i);
5192 // Ignore undef indicies
5196 if (Idx < (int)NumElems)
5201 // Only accept consecutive elements from the same vector
5202 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5206 OpNum = SeenV1 ? 0 : 1;
5210 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5211 /// logical left shift of a vector.
5212 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5213 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5215 SVOp->getSimpleValueType(0).getVectorNumElements();
5216 unsigned NumZeros = getNumOfConsecutiveZeros(
5217 SVOp, NumElems, false /* check zeros from right */, DAG,
5218 SVOp->getMaskElt(0));
5224 // Considering the elements in the mask that are not consecutive zeros,
5225 // check if they consecutively come from only one of the source vectors.
5227 // V1 = {X, A, B, C} 0
5229 // vector_shuffle V1, V2 <1, 2, 3, X>
5231 if (!isShuffleMaskConsecutive(SVOp,
5232 0, // Mask Start Index
5233 NumElems-NumZeros, // Mask End Index(exclusive)
5234 NumZeros, // Where to start looking in the src vector
5235 NumElems, // Number of elements in vector
5236 OpSrc)) // Which source operand ?
5241 ShVal = SVOp->getOperand(OpSrc);
5245 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5246 /// logical left shift of a vector.
5247 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5248 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5250 SVOp->getSimpleValueType(0).getVectorNumElements();
5251 unsigned NumZeros = getNumOfConsecutiveZeros(
5252 SVOp, NumElems, true /* check zeros from left */, DAG,
5253 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5259 // Considering the elements in the mask that are not consecutive zeros,
5260 // check if they consecutively come from only one of the source vectors.
5262 // 0 { A, B, X, X } = V2
5264 // vector_shuffle V1, V2 <X, X, 4, 5>
5266 if (!isShuffleMaskConsecutive(SVOp,
5267 NumZeros, // Mask Start Index
5268 NumElems, // Mask End Index(exclusive)
5269 0, // Where to start looking in the src vector
5270 NumElems, // Number of elements in vector
5271 OpSrc)) // Which source operand ?
5276 ShVal = SVOp->getOperand(OpSrc);
5280 /// isVectorShift - Returns true if the shuffle can be implemented as a
5281 /// logical left or right shift of a vector.
5282 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5283 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5284 // Although the logic below support any bitwidth size, there are no
5285 // shift instructions which handle more than 128-bit vectors.
5286 if (!SVOp->getSimpleValueType(0).is128BitVector())
5289 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5290 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5296 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5298 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5299 unsigned NumNonZero, unsigned NumZero,
5301 const X86Subtarget* Subtarget,
5302 const TargetLowering &TLI) {
5309 for (unsigned i = 0; i < 16; ++i) {
5310 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5311 if (ThisIsNonZero && First) {
5313 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5315 V = DAG.getUNDEF(MVT::v8i16);
5320 SDValue ThisElt(0, 0), LastElt(0, 0);
5321 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5322 if (LastIsNonZero) {
5323 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5324 MVT::i16, Op.getOperand(i-1));
5326 if (ThisIsNonZero) {
5327 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5328 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5329 ThisElt, DAG.getConstant(8, MVT::i8));
5331 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5335 if (ThisElt.getNode())
5336 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5337 DAG.getIntPtrConstant(i/2));
5341 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5344 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5346 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5347 unsigned NumNonZero, unsigned NumZero,
5349 const X86Subtarget* Subtarget,
5350 const TargetLowering &TLI) {
5357 for (unsigned i = 0; i < 8; ++i) {
5358 bool isNonZero = (NonZeros & (1 << i)) != 0;
5362 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5364 V = DAG.getUNDEF(MVT::v8i16);
5367 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5368 MVT::v8i16, V, Op.getOperand(i),
5369 DAG.getIntPtrConstant(i));
5376 /// getVShift - Return a vector logical shift node.
5378 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5379 unsigned NumBits, SelectionDAG &DAG,
5380 const TargetLowering &TLI, SDLoc dl) {
5381 assert(VT.is128BitVector() && "Unknown type for VShift");
5382 EVT ShVT = MVT::v2i64;
5383 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5384 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5385 return DAG.getNode(ISD::BITCAST, dl, VT,
5386 DAG.getNode(Opc, dl, ShVT, SrcOp,
5387 DAG.getConstant(NumBits,
5388 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5392 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5394 // Check if the scalar load can be widened into a vector load. And if
5395 // the address is "base + cst" see if the cst can be "absorbed" into
5396 // the shuffle mask.
5397 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5398 SDValue Ptr = LD->getBasePtr();
5399 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5401 EVT PVT = LD->getValueType(0);
5402 if (PVT != MVT::i32 && PVT != MVT::f32)
5407 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5408 FI = FINode->getIndex();
5410 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5411 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5412 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5413 Offset = Ptr.getConstantOperandVal(1);
5414 Ptr = Ptr.getOperand(0);
5419 // FIXME: 256-bit vector instructions don't require a strict alignment,
5420 // improve this code to support it better.
5421 unsigned RequiredAlign = VT.getSizeInBits()/8;
5422 SDValue Chain = LD->getChain();
5423 // Make sure the stack object alignment is at least 16 or 32.
5424 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5425 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5426 if (MFI->isFixedObjectIndex(FI)) {
5427 // Can't change the alignment. FIXME: It's possible to compute
5428 // the exact stack offset and reference FI + adjust offset instead.
5429 // If someone *really* cares about this. That's the way to implement it.
5432 MFI->setObjectAlignment(FI, RequiredAlign);
5436 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5437 // Ptr + (Offset & ~15).
5440 if ((Offset % RequiredAlign) & 3)
5442 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5444 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5445 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5447 int EltNo = (Offset - StartOffset) >> 2;
5448 unsigned NumElems = VT.getVectorNumElements();
5450 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5451 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5452 LD->getPointerInfo().getWithOffset(StartOffset),
5453 false, false, false, 0);
5455 SmallVector<int, 8> Mask;
5456 for (unsigned i = 0; i != NumElems; ++i)
5457 Mask.push_back(EltNo);
5459 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5465 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5466 /// vector of type 'VT', see if the elements can be replaced by a single large
5467 /// load which has the same value as a build_vector whose operands are 'elts'.
5469 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5471 /// FIXME: we'd also like to handle the case where the last elements are zero
5472 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5473 /// There's even a handy isZeroNode for that purpose.
5474 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5475 SDLoc &DL, SelectionDAG &DAG,
5476 bool isAfterLegalize) {
5477 EVT EltVT = VT.getVectorElementType();
5478 unsigned NumElems = Elts.size();
5480 LoadSDNode *LDBase = NULL;
5481 unsigned LastLoadedElt = -1U;
5483 // For each element in the initializer, see if we've found a load or an undef.
5484 // If we don't find an initial load element, or later load elements are
5485 // non-consecutive, bail out.
5486 for (unsigned i = 0; i < NumElems; ++i) {
5487 SDValue Elt = Elts[i];
5489 if (!Elt.getNode() ||
5490 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5493 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5495 LDBase = cast<LoadSDNode>(Elt.getNode());
5499 if (Elt.getOpcode() == ISD::UNDEF)
5502 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5503 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5508 // If we have found an entire vector of loads and undefs, then return a large
5509 // load of the entire vector width starting at the base pointer. If we found
5510 // consecutive loads for the low half, generate a vzext_load node.
5511 if (LastLoadedElt == NumElems - 1) {
5513 if (isAfterLegalize &&
5514 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5517 SDValue NewLd = SDValue();
5519 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5520 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5521 LDBase->getPointerInfo(),
5522 LDBase->isVolatile(), LDBase->isNonTemporal(),
5523 LDBase->isInvariant(), 0);
5524 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5525 LDBase->getPointerInfo(),
5526 LDBase->isVolatile(), LDBase->isNonTemporal(),
5527 LDBase->isInvariant(), LDBase->getAlignment());
5529 if (LDBase->hasAnyUseOfValue(1)) {
5530 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5532 SDValue(NewLd.getNode(), 1));
5533 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5534 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5535 SDValue(NewLd.getNode(), 1));
5540 if (NumElems == 4 && LastLoadedElt == 1 &&
5541 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5542 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5543 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5545 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5546 array_lengthof(Ops), MVT::i64,
5547 LDBase->getPointerInfo(),
5548 LDBase->getAlignment(),
5549 false/*isVolatile*/, true/*ReadMem*/,
5552 // Make sure the newly-created LOAD is in the same position as LDBase in
5553 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5554 // update uses of LDBase's output chain to use the TokenFactor.
5555 if (LDBase->hasAnyUseOfValue(1)) {
5556 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5557 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5558 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5559 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5560 SDValue(ResNode.getNode(), 1));
5563 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5568 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5569 /// to generate a splat value for the following cases:
5570 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5571 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5572 /// a scalar load, or a constant.
5573 /// The VBROADCAST node is returned when a pattern is found,
5574 /// or SDValue() otherwise.
5575 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5576 SelectionDAG &DAG) {
5577 if (!Subtarget->hasFp256())
5580 MVT VT = Op.getSimpleValueType();
5583 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5584 "Unsupported vector type for broadcast.");
5589 switch (Op.getOpcode()) {
5591 // Unknown pattern found.
5594 case ISD::BUILD_VECTOR: {
5595 // The BUILD_VECTOR node must be a splat.
5596 if (!isSplatVector(Op.getNode()))
5599 Ld = Op.getOperand(0);
5600 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5601 Ld.getOpcode() == ISD::ConstantFP);
5603 // The suspected load node has several users. Make sure that all
5604 // of its users are from the BUILD_VECTOR node.
5605 // Constants may have multiple users.
5606 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5611 case ISD::VECTOR_SHUFFLE: {
5612 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5614 // Shuffles must have a splat mask where the first element is
5616 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5619 SDValue Sc = Op.getOperand(0);
5620 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5621 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5623 if (!Subtarget->hasInt256())
5626 // Use the register form of the broadcast instruction available on AVX2.
5627 if (VT.getSizeInBits() >= 256)
5628 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5629 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5632 Ld = Sc.getOperand(0);
5633 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5634 Ld.getOpcode() == ISD::ConstantFP);
5636 // The scalar_to_vector node and the suspected
5637 // load node must have exactly one user.
5638 // Constants may have multiple users.
5640 // AVX-512 has register version of the broadcast
5641 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5642 Ld.getValueType().getSizeInBits() >= 32;
5643 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5650 bool IsGE256 = (VT.getSizeInBits() >= 256);
5652 // Handle the broadcasting a single constant scalar from the constant pool
5653 // into a vector. On Sandybridge it is still better to load a constant vector
5654 // from the constant pool and not to broadcast it from a scalar.
5655 if (ConstSplatVal && Subtarget->hasInt256()) {
5656 EVT CVT = Ld.getValueType();
5657 assert(!CVT.isVector() && "Must not broadcast a vector type");
5658 unsigned ScalarSize = CVT.getSizeInBits();
5660 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5661 const Constant *C = 0;
5662 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5663 C = CI->getConstantIntValue();
5664 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5665 C = CF->getConstantFPValue();
5667 assert(C && "Invalid constant type");
5669 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5670 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5671 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5672 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5673 MachinePointerInfo::getConstantPool(),
5674 false, false, false, Alignment);
5676 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5680 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5681 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5683 // Handle AVX2 in-register broadcasts.
5684 if (!IsLoad && Subtarget->hasInt256() &&
5685 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5686 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5688 // The scalar source must be a normal load.
5692 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5693 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5695 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5696 // double since there is no vbroadcastsd xmm
5697 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5698 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5699 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5702 // Unsupported broadcast.
5706 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5707 MVT VT = Op.getSimpleValueType();
5709 // Skip if insert_vec_elt is not supported.
5710 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5711 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5715 unsigned NumElems = Op.getNumOperands();
5719 SmallVector<unsigned, 4> InsertIndices;
5720 SmallVector<int, 8> Mask(NumElems, -1);
5722 for (unsigned i = 0; i != NumElems; ++i) {
5723 unsigned Opc = Op.getOperand(i).getOpcode();
5725 if (Opc == ISD::UNDEF)
5728 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5729 // Quit if more than 1 elements need inserting.
5730 if (InsertIndices.size() > 1)
5733 InsertIndices.push_back(i);
5737 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5738 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5740 // Quit if extracted from vector of different type.
5741 if (ExtractedFromVec.getValueType() != VT)
5744 // Quit if non-constant index.
5745 if (!isa<ConstantSDNode>(ExtIdx))
5748 if (VecIn1.getNode() == 0)
5749 VecIn1 = ExtractedFromVec;
5750 else if (VecIn1 != ExtractedFromVec) {
5751 if (VecIn2.getNode() == 0)
5752 VecIn2 = ExtractedFromVec;
5753 else if (VecIn2 != ExtractedFromVec)
5754 // Quit if more than 2 vectors to shuffle
5758 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5760 if (ExtractedFromVec == VecIn1)
5762 else if (ExtractedFromVec == VecIn2)
5763 Mask[i] = Idx + NumElems;
5766 if (VecIn1.getNode() == 0)
5769 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5770 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5771 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5772 unsigned Idx = InsertIndices[i];
5773 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5774 DAG.getIntPtrConstant(Idx));
5780 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5782 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5784 MVT VT = Op.getSimpleValueType();
5785 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5786 "Unexpected type in LowerBUILD_VECTORvXi1!");
5789 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5790 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5791 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5792 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5793 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5794 Ops, VT.getVectorNumElements());
5797 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5798 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5799 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5800 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5801 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5802 Ops, VT.getVectorNumElements());
5805 bool AllContants = true;
5806 uint64_t Immediate = 0;
5807 int NonConstIdx = -1;
5808 bool IsSplat = true;
5809 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5810 SDValue In = Op.getOperand(idx);
5811 if (In.getOpcode() == ISD::UNDEF)
5813 if (!isa<ConstantSDNode>(In)) {
5814 AllContants = false;
5817 else if (cast<ConstantSDNode>(In)->getZExtValue())
5818 Immediate |= (1ULL << idx);
5819 if (In != Op.getOperand(0))
5824 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5825 DAG.getConstant(Immediate, MVT::i16));
5826 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5827 DAG.getIntPtrConstant(0));
5830 if (!IsSplat && (NonConstIdx != 0))
5831 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5832 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5835 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5836 DAG.getConstant(-1, SelectVT),
5837 DAG.getConstant(0, SelectVT));
5839 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5840 DAG.getConstant((Immediate | 1), SelectVT),
5841 DAG.getConstant(Immediate, SelectVT));
5842 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5846 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5849 MVT VT = Op.getSimpleValueType();
5850 MVT ExtVT = VT.getVectorElementType();
5851 unsigned NumElems = Op.getNumOperands();
5853 // Generate vectors for predicate vectors.
5854 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5855 return LowerBUILD_VECTORvXi1(Op, DAG);
5857 // Vectors containing all zeros can be matched by pxor and xorps later
5858 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5859 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5860 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5861 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5864 return getZeroVector(VT, Subtarget, DAG, dl);
5867 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5868 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5869 // vpcmpeqd on 256-bit vectors.
5870 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5871 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5874 if (!VT.is512BitVector())
5875 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5878 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5879 if (Broadcast.getNode())
5882 unsigned EVTBits = ExtVT.getSizeInBits();
5884 unsigned NumZero = 0;
5885 unsigned NumNonZero = 0;
5886 unsigned NonZeros = 0;
5887 bool IsAllConstants = true;
5888 SmallSet<SDValue, 8> Values;
5889 for (unsigned i = 0; i < NumElems; ++i) {
5890 SDValue Elt = Op.getOperand(i);
5891 if (Elt.getOpcode() == ISD::UNDEF)
5894 if (Elt.getOpcode() != ISD::Constant &&
5895 Elt.getOpcode() != ISD::ConstantFP)
5896 IsAllConstants = false;
5897 if (X86::isZeroNode(Elt))
5900 NonZeros |= (1 << i);
5905 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5906 if (NumNonZero == 0)
5907 return DAG.getUNDEF(VT);
5909 // Special case for single non-zero, non-undef, element.
5910 if (NumNonZero == 1) {
5911 unsigned Idx = countTrailingZeros(NonZeros);
5912 SDValue Item = Op.getOperand(Idx);
5914 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5915 // the value are obviously zero, truncate the value to i32 and do the
5916 // insertion that way. Only do this if the value is non-constant or if the
5917 // value is a constant being inserted into element 0. It is cheaper to do
5918 // a constant pool load than it is to do a movd + shuffle.
5919 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5920 (!IsAllConstants || Idx == 0)) {
5921 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5923 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5924 EVT VecVT = MVT::v4i32;
5925 unsigned VecElts = 4;
5927 // Truncate the value (which may itself be a constant) to i32, and
5928 // convert it to a vector with movd (S2V+shuffle to zero extend).
5929 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5930 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5931 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5933 // Now we have our 32-bit value zero extended in the low element of
5934 // a vector. If Idx != 0, swizzle it into place.
5936 SmallVector<int, 4> Mask;
5937 Mask.push_back(Idx);
5938 for (unsigned i = 1; i != VecElts; ++i)
5940 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5943 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5947 // If we have a constant or non-constant insertion into the low element of
5948 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5949 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5950 // depending on what the source datatype is.
5953 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5955 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5956 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5957 if (VT.is256BitVector() || VT.is512BitVector()) {
5958 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5959 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5960 Item, DAG.getIntPtrConstant(0));
5962 assert(VT.is128BitVector() && "Expected an SSE value type!");
5963 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5964 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5965 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5968 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5969 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5970 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5971 if (VT.is256BitVector()) {
5972 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5973 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5975 assert(VT.is128BitVector() && "Expected an SSE value type!");
5976 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5978 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5982 // Is it a vector logical left shift?
5983 if (NumElems == 2 && Idx == 1 &&
5984 X86::isZeroNode(Op.getOperand(0)) &&
5985 !X86::isZeroNode(Op.getOperand(1))) {
5986 unsigned NumBits = VT.getSizeInBits();
5987 return getVShift(true, VT,
5988 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5989 VT, Op.getOperand(1)),
5990 NumBits/2, DAG, *this, dl);
5993 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5996 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5997 // is a non-constant being inserted into an element other than the low one,
5998 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5999 // movd/movss) to move this into the low element, then shuffle it into
6001 if (EVTBits == 32) {
6002 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6004 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6005 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6006 SmallVector<int, 8> MaskVec;
6007 for (unsigned i = 0; i != NumElems; ++i)
6008 MaskVec.push_back(i == Idx ? 0 : 1);
6009 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6013 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6014 if (Values.size() == 1) {
6015 if (EVTBits == 32) {
6016 // Instead of a shuffle like this:
6017 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6018 // Check if it's possible to issue this instead.
6019 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6020 unsigned Idx = countTrailingZeros(NonZeros);
6021 SDValue Item = Op.getOperand(Idx);
6022 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6023 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6028 // A vector full of immediates; various special cases are already
6029 // handled, so this is best done with a single constant-pool load.
6033 // For AVX-length vectors, build the individual 128-bit pieces and use
6034 // shuffles to put them in place.
6035 if (VT.is256BitVector() || VT.is512BitVector()) {
6036 SmallVector<SDValue, 64> V;
6037 for (unsigned i = 0; i != NumElems; ++i)
6038 V.push_back(Op.getOperand(i));
6040 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6042 // Build both the lower and upper subvector.
6043 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6044 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6047 // Recreate the wider vector with the lower and upper part.
6048 if (VT.is256BitVector())
6049 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6050 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6053 // Let legalizer expand 2-wide build_vectors.
6054 if (EVTBits == 64) {
6055 if (NumNonZero == 1) {
6056 // One half is zero or undef.
6057 unsigned Idx = countTrailingZeros(NonZeros);
6058 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6059 Op.getOperand(Idx));
6060 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6065 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6066 if (EVTBits == 8 && NumElems == 16) {
6067 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6069 if (V.getNode()) return V;
6072 if (EVTBits == 16 && NumElems == 8) {
6073 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6075 if (V.getNode()) return V;
6078 // If element VT is == 32 bits, turn it into a number of shuffles.
6079 SmallVector<SDValue, 8> V(NumElems);
6080 if (NumElems == 4 && NumZero > 0) {
6081 for (unsigned i = 0; i < 4; ++i) {
6082 bool isZero = !(NonZeros & (1 << i));
6084 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6086 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6089 for (unsigned i = 0; i < 2; ++i) {
6090 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6093 V[i] = V[i*2]; // Must be a zero vector.
6096 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6099 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6102 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6107 bool Reverse1 = (NonZeros & 0x3) == 2;
6108 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6112 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6113 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6115 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6118 if (Values.size() > 1 && VT.is128BitVector()) {
6119 // Check for a build vector of consecutive loads.
6120 for (unsigned i = 0; i < NumElems; ++i)
6121 V[i] = Op.getOperand(i);
6123 // Check for elements which are consecutive loads.
6124 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6128 // Check for a build vector from mostly shuffle plus few inserting.
6129 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6133 // For SSE 4.1, use insertps to put the high elements into the low element.
6134 if (getSubtarget()->hasSSE41()) {
6136 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6137 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6139 Result = DAG.getUNDEF(VT);
6141 for (unsigned i = 1; i < NumElems; ++i) {
6142 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6143 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6144 Op.getOperand(i), DAG.getIntPtrConstant(i));
6149 // Otherwise, expand into a number of unpckl*, start by extending each of
6150 // our (non-undef) elements to the full vector width with the element in the
6151 // bottom slot of the vector (which generates no code for SSE).
6152 for (unsigned i = 0; i < NumElems; ++i) {
6153 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6154 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6156 V[i] = DAG.getUNDEF(VT);
6159 // Next, we iteratively mix elements, e.g. for v4f32:
6160 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6161 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6162 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6163 unsigned EltStride = NumElems >> 1;
6164 while (EltStride != 0) {
6165 for (unsigned i = 0; i < EltStride; ++i) {
6166 // If V[i+EltStride] is undef and this is the first round of mixing,
6167 // then it is safe to just drop this shuffle: V[i] is already in the
6168 // right place, the one element (since it's the first round) being
6169 // inserted as undef can be dropped. This isn't safe for successive
6170 // rounds because they will permute elements within both vectors.
6171 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6172 EltStride == NumElems/2)
6175 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6184 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6185 // to create 256-bit vectors from two other 128-bit ones.
6186 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6188 MVT ResVT = Op.getSimpleValueType();
6190 assert((ResVT.is256BitVector() ||
6191 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6193 SDValue V1 = Op.getOperand(0);
6194 SDValue V2 = Op.getOperand(1);
6195 unsigned NumElems = ResVT.getVectorNumElements();
6196 if(ResVT.is256BitVector())
6197 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6199 if (Op.getNumOperands() == 4) {
6200 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6201 ResVT.getVectorNumElements()/2);
6202 SDValue V3 = Op.getOperand(2);
6203 SDValue V4 = Op.getOperand(3);
6204 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6205 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6207 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6210 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6211 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6212 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6213 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6214 Op.getNumOperands() == 4)));
6216 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6217 // from two other 128-bit ones.
6219 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6220 return LowerAVXCONCAT_VECTORS(Op, DAG);
6223 // Try to lower a shuffle node into a simple blend instruction.
6225 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6226 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6227 SDValue V1 = SVOp->getOperand(0);
6228 SDValue V2 = SVOp->getOperand(1);
6230 MVT VT = SVOp->getSimpleValueType(0);
6231 MVT EltVT = VT.getVectorElementType();
6232 unsigned NumElems = VT.getVectorNumElements();
6234 // There is no blend with immediate in AVX-512.
6235 if (VT.is512BitVector())
6238 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6240 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6243 // Check the mask for BLEND and build the value.
6244 unsigned MaskValue = 0;
6245 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6246 unsigned NumLanes = (NumElems-1)/8 + 1;
6247 unsigned NumElemsInLane = NumElems / NumLanes;
6249 // Blend for v16i16 should be symetric for the both lanes.
6250 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6252 int SndLaneEltIdx = (NumLanes == 2) ?
6253 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6254 int EltIdx = SVOp->getMaskElt(i);
6256 if ((EltIdx < 0 || EltIdx == (int)i) &&
6257 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6260 if (((unsigned)EltIdx == (i + NumElems)) &&
6261 (SndLaneEltIdx < 0 ||
6262 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6263 MaskValue |= (1<<i);
6268 // Convert i32 vectors to floating point if it is not AVX2.
6269 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6271 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6272 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6274 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6275 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6278 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6279 DAG.getConstant(MaskValue, MVT::i32));
6280 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6283 // v8i16 shuffles - Prefer shuffles in the following order:
6284 // 1. [all] pshuflw, pshufhw, optional move
6285 // 2. [ssse3] 1 x pshufb
6286 // 3. [ssse3] 2 x pshufb + 1 x por
6287 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6289 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6290 SelectionDAG &DAG) {
6291 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6292 SDValue V1 = SVOp->getOperand(0);
6293 SDValue V2 = SVOp->getOperand(1);
6295 SmallVector<int, 8> MaskVals;
6297 // Determine if more than 1 of the words in each of the low and high quadwords
6298 // of the result come from the same quadword of one of the two inputs. Undef
6299 // mask values count as coming from any quadword, for better codegen.
6300 unsigned LoQuad[] = { 0, 0, 0, 0 };
6301 unsigned HiQuad[] = { 0, 0, 0, 0 };
6302 std::bitset<4> InputQuads;
6303 for (unsigned i = 0; i < 8; ++i) {
6304 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6305 int EltIdx = SVOp->getMaskElt(i);
6306 MaskVals.push_back(EltIdx);
6315 InputQuads.set(EltIdx / 4);
6318 int BestLoQuad = -1;
6319 unsigned MaxQuad = 1;
6320 for (unsigned i = 0; i < 4; ++i) {
6321 if (LoQuad[i] > MaxQuad) {
6323 MaxQuad = LoQuad[i];
6327 int BestHiQuad = -1;
6329 for (unsigned i = 0; i < 4; ++i) {
6330 if (HiQuad[i] > MaxQuad) {
6332 MaxQuad = HiQuad[i];
6336 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6337 // of the two input vectors, shuffle them into one input vector so only a
6338 // single pshufb instruction is necessary. If There are more than 2 input
6339 // quads, disable the next transformation since it does not help SSSE3.
6340 bool V1Used = InputQuads[0] || InputQuads[1];
6341 bool V2Used = InputQuads[2] || InputQuads[3];
6342 if (Subtarget->hasSSSE3()) {
6343 if (InputQuads.count() == 2 && V1Used && V2Used) {
6344 BestLoQuad = InputQuads[0] ? 0 : 1;
6345 BestHiQuad = InputQuads[2] ? 2 : 3;
6347 if (InputQuads.count() > 2) {
6353 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6354 // the shuffle mask. If a quad is scored as -1, that means that it contains
6355 // words from all 4 input quadwords.
6357 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6359 BestLoQuad < 0 ? 0 : BestLoQuad,
6360 BestHiQuad < 0 ? 1 : BestHiQuad
6362 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6363 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6364 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6365 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6367 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6368 // source words for the shuffle, to aid later transformations.
6369 bool AllWordsInNewV = true;
6370 bool InOrder[2] = { true, true };
6371 for (unsigned i = 0; i != 8; ++i) {
6372 int idx = MaskVals[i];
6374 InOrder[i/4] = false;
6375 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6377 AllWordsInNewV = false;
6381 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6382 if (AllWordsInNewV) {
6383 for (int i = 0; i != 8; ++i) {
6384 int idx = MaskVals[i];
6387 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6388 if ((idx != i) && idx < 4)
6390 if ((idx != i) && idx > 3)
6399 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6400 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6401 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6402 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6403 unsigned TargetMask = 0;
6404 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6405 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6406 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6407 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6408 getShufflePSHUFLWImmediate(SVOp);
6409 V1 = NewV.getOperand(0);
6410 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6414 // Promote splats to a larger type which usually leads to more efficient code.
6415 // FIXME: Is this true if pshufb is available?
6416 if (SVOp->isSplat())
6417 return PromoteSplat(SVOp, DAG);
6419 // If we have SSSE3, and all words of the result are from 1 input vector,
6420 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6421 // is present, fall back to case 4.
6422 if (Subtarget->hasSSSE3()) {
6423 SmallVector<SDValue,16> pshufbMask;
6425 // If we have elements from both input vectors, set the high bit of the
6426 // shuffle mask element to zero out elements that come from V2 in the V1
6427 // mask, and elements that come from V1 in the V2 mask, so that the two
6428 // results can be OR'd together.
6429 bool TwoInputs = V1Used && V2Used;
6430 for (unsigned i = 0; i != 8; ++i) {
6431 int EltIdx = MaskVals[i] * 2;
6432 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6433 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6434 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6435 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6437 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6438 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6439 DAG.getNode(ISD::BUILD_VECTOR, dl,
6440 MVT::v16i8, &pshufbMask[0], 16));
6442 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6444 // Calculate the shuffle mask for the second input, shuffle it, and
6445 // OR it with the first shuffled input.
6447 for (unsigned i = 0; i != 8; ++i) {
6448 int EltIdx = MaskVals[i] * 2;
6449 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6450 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6451 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6452 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6454 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6455 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6456 DAG.getNode(ISD::BUILD_VECTOR, dl,
6457 MVT::v16i8, &pshufbMask[0], 16));
6458 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6459 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6462 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6463 // and update MaskVals with new element order.
6464 std::bitset<8> InOrder;
6465 if (BestLoQuad >= 0) {
6466 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6467 for (int i = 0; i != 4; ++i) {
6468 int idx = MaskVals[i];
6471 } else if ((idx / 4) == BestLoQuad) {
6476 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6479 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6480 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6481 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6483 getShufflePSHUFLWImmediate(SVOp), DAG);
6487 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6488 // and update MaskVals with the new element order.
6489 if (BestHiQuad >= 0) {
6490 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6491 for (unsigned i = 4; i != 8; ++i) {
6492 int idx = MaskVals[i];
6495 } else if ((idx / 4) == BestHiQuad) {
6496 MaskV[i] = (idx & 3) + 4;
6500 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6503 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6504 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6505 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6507 getShufflePSHUFHWImmediate(SVOp), DAG);
6511 // In case BestHi & BestLo were both -1, which means each quadword has a word
6512 // from each of the four input quadwords, calculate the InOrder bitvector now
6513 // before falling through to the insert/extract cleanup.
6514 if (BestLoQuad == -1 && BestHiQuad == -1) {
6516 for (int i = 0; i != 8; ++i)
6517 if (MaskVals[i] < 0 || MaskVals[i] == i)
6521 // The other elements are put in the right place using pextrw and pinsrw.
6522 for (unsigned i = 0; i != 8; ++i) {
6525 int EltIdx = MaskVals[i];
6528 SDValue ExtOp = (EltIdx < 8) ?
6529 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6530 DAG.getIntPtrConstant(EltIdx)) :
6531 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6532 DAG.getIntPtrConstant(EltIdx - 8));
6533 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6534 DAG.getIntPtrConstant(i));
6539 // v16i8 shuffles - Prefer shuffles in the following order:
6540 // 1. [ssse3] 1 x pshufb
6541 // 2. [ssse3] 2 x pshufb + 1 x por
6542 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6543 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6544 const X86Subtarget* Subtarget,
6545 SelectionDAG &DAG) {
6546 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6547 SDValue V1 = SVOp->getOperand(0);
6548 SDValue V2 = SVOp->getOperand(1);
6550 ArrayRef<int> MaskVals = SVOp->getMask();
6552 // Promote splats to a larger type which usually leads to more efficient code.
6553 // FIXME: Is this true if pshufb is available?
6554 if (SVOp->isSplat())
6555 return PromoteSplat(SVOp, DAG);
6557 // If we have SSSE3, case 1 is generated when all result bytes come from
6558 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6559 // present, fall back to case 3.
6561 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6562 if (Subtarget->hasSSSE3()) {
6563 SmallVector<SDValue,16> pshufbMask;
6565 // If all result elements are from one input vector, then only translate
6566 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6568 // Otherwise, we have elements from both input vectors, and must zero out
6569 // elements that come from V2 in the first mask, and V1 in the second mask
6570 // so that we can OR them together.
6571 for (unsigned i = 0; i != 16; ++i) {
6572 int EltIdx = MaskVals[i];
6573 if (EltIdx < 0 || EltIdx >= 16)
6575 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6577 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6578 DAG.getNode(ISD::BUILD_VECTOR, dl,
6579 MVT::v16i8, &pshufbMask[0], 16));
6581 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6582 // the 2nd operand if it's undefined or zero.
6583 if (V2.getOpcode() == ISD::UNDEF ||
6584 ISD::isBuildVectorAllZeros(V2.getNode()))
6587 // Calculate the shuffle mask for the second input, shuffle it, and
6588 // OR it with the first shuffled input.
6590 for (unsigned i = 0; i != 16; ++i) {
6591 int EltIdx = MaskVals[i];
6592 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6593 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6595 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6596 DAG.getNode(ISD::BUILD_VECTOR, dl,
6597 MVT::v16i8, &pshufbMask[0], 16));
6598 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6601 // No SSSE3 - Calculate in place words and then fix all out of place words
6602 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6603 // the 16 different words that comprise the two doublequadword input vectors.
6604 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6605 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6607 for (int i = 0; i != 8; ++i) {
6608 int Elt0 = MaskVals[i*2];
6609 int Elt1 = MaskVals[i*2+1];
6611 // This word of the result is all undef, skip it.
6612 if (Elt0 < 0 && Elt1 < 0)
6615 // This word of the result is already in the correct place, skip it.
6616 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6619 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6620 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6623 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6624 // using a single extract together, load it and store it.
6625 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6626 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6627 DAG.getIntPtrConstant(Elt1 / 2));
6628 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6629 DAG.getIntPtrConstant(i));
6633 // If Elt1 is defined, extract it from the appropriate source. If the
6634 // source byte is not also odd, shift the extracted word left 8 bits
6635 // otherwise clear the bottom 8 bits if we need to do an or.
6637 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6638 DAG.getIntPtrConstant(Elt1 / 2));
6639 if ((Elt1 & 1) == 0)
6640 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6642 TLI.getShiftAmountTy(InsElt.getValueType())));
6644 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6645 DAG.getConstant(0xFF00, MVT::i16));
6647 // If Elt0 is defined, extract it from the appropriate source. If the
6648 // source byte is not also even, shift the extracted word right 8 bits. If
6649 // Elt1 was also defined, OR the extracted values together before
6650 // inserting them in the result.
6652 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6653 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6654 if ((Elt0 & 1) != 0)
6655 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6657 TLI.getShiftAmountTy(InsElt0.getValueType())));
6659 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6660 DAG.getConstant(0x00FF, MVT::i16));
6661 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6664 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6665 DAG.getIntPtrConstant(i));
6667 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6670 // v32i8 shuffles - Translate to VPSHUFB if possible.
6672 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6673 const X86Subtarget *Subtarget,
6674 SelectionDAG &DAG) {
6675 MVT VT = SVOp->getSimpleValueType(0);
6676 SDValue V1 = SVOp->getOperand(0);
6677 SDValue V2 = SVOp->getOperand(1);
6679 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6681 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6682 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6683 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6685 // VPSHUFB may be generated if
6686 // (1) one of input vector is undefined or zeroinitializer.
6687 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6688 // And (2) the mask indexes don't cross the 128-bit lane.
6689 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6690 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6693 if (V1IsAllZero && !V2IsAllZero) {
6694 CommuteVectorShuffleMask(MaskVals, 32);
6697 SmallVector<SDValue, 32> pshufbMask;
6698 for (unsigned i = 0; i != 32; i++) {
6699 int EltIdx = MaskVals[i];
6700 if (EltIdx < 0 || EltIdx >= 32)
6703 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6704 // Cross lane is not allowed.
6708 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6710 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6711 DAG.getNode(ISD::BUILD_VECTOR, dl,
6712 MVT::v32i8, &pshufbMask[0], 32));
6715 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6716 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6717 /// done when every pair / quad of shuffle mask elements point to elements in
6718 /// the right sequence. e.g.
6719 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6721 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6722 SelectionDAG &DAG) {
6723 MVT VT = SVOp->getSimpleValueType(0);
6725 unsigned NumElems = VT.getVectorNumElements();
6728 switch (VT.SimpleTy) {
6729 default: llvm_unreachable("Unexpected!");
6730 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6731 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6732 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6733 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6734 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6735 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6738 SmallVector<int, 8> MaskVec;
6739 for (unsigned i = 0; i != NumElems; i += Scale) {
6741 for (unsigned j = 0; j != Scale; ++j) {
6742 int EltIdx = SVOp->getMaskElt(i+j);
6746 StartIdx = (EltIdx / Scale);
6747 if (EltIdx != (int)(StartIdx*Scale + j))
6750 MaskVec.push_back(StartIdx);
6753 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6754 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6755 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6758 /// getVZextMovL - Return a zero-extending vector move low node.
6760 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6761 SDValue SrcOp, SelectionDAG &DAG,
6762 const X86Subtarget *Subtarget, SDLoc dl) {
6763 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6764 LoadSDNode *LD = NULL;
6765 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6766 LD = dyn_cast<LoadSDNode>(SrcOp);
6768 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6770 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6771 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6772 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6773 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6774 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6776 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6777 return DAG.getNode(ISD::BITCAST, dl, VT,
6778 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6779 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6787 return DAG.getNode(ISD::BITCAST, dl, VT,
6788 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6789 DAG.getNode(ISD::BITCAST, dl,
6793 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6794 /// which could not be matched by any known target speficic shuffle
6796 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6798 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6799 if (NewOp.getNode())
6802 MVT VT = SVOp->getSimpleValueType(0);
6804 unsigned NumElems = VT.getVectorNumElements();
6805 unsigned NumLaneElems = NumElems / 2;
6808 MVT EltVT = VT.getVectorElementType();
6809 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6812 SmallVector<int, 16> Mask;
6813 for (unsigned l = 0; l < 2; ++l) {
6814 // Build a shuffle mask for the output, discovering on the fly which
6815 // input vectors to use as shuffle operands (recorded in InputUsed).
6816 // If building a suitable shuffle vector proves too hard, then bail
6817 // out with UseBuildVector set.
6818 bool UseBuildVector = false;
6819 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6820 unsigned LaneStart = l * NumLaneElems;
6821 for (unsigned i = 0; i != NumLaneElems; ++i) {
6822 // The mask element. This indexes into the input.
6823 int Idx = SVOp->getMaskElt(i+LaneStart);
6825 // the mask element does not index into any input vector.
6830 // The input vector this mask element indexes into.
6831 int Input = Idx / NumLaneElems;
6833 // Turn the index into an offset from the start of the input vector.
6834 Idx -= Input * NumLaneElems;
6836 // Find or create a shuffle vector operand to hold this input.
6838 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6839 if (InputUsed[OpNo] == Input)
6840 // This input vector is already an operand.
6842 if (InputUsed[OpNo] < 0) {
6843 // Create a new operand for this input vector.
6844 InputUsed[OpNo] = Input;
6849 if (OpNo >= array_lengthof(InputUsed)) {
6850 // More than two input vectors used! Give up on trying to create a
6851 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6852 UseBuildVector = true;
6856 // Add the mask index for the new shuffle vector.
6857 Mask.push_back(Idx + OpNo * NumLaneElems);
6860 if (UseBuildVector) {
6861 SmallVector<SDValue, 16> SVOps;
6862 for (unsigned i = 0; i != NumLaneElems; ++i) {
6863 // The mask element. This indexes into the input.
6864 int Idx = SVOp->getMaskElt(i+LaneStart);
6866 SVOps.push_back(DAG.getUNDEF(EltVT));
6870 // The input vector this mask element indexes into.
6871 int Input = Idx / NumElems;
6873 // Turn the index into an offset from the start of the input vector.
6874 Idx -= Input * NumElems;
6876 // Extract the vector element by hand.
6877 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6878 SVOp->getOperand(Input),
6879 DAG.getIntPtrConstant(Idx)));
6882 // Construct the output using a BUILD_VECTOR.
6883 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6885 } else if (InputUsed[0] < 0) {
6886 // No input vectors were used! The result is undefined.
6887 Output[l] = DAG.getUNDEF(NVT);
6889 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6890 (InputUsed[0] % 2) * NumLaneElems,
6892 // If only one input was used, use an undefined vector for the other.
6893 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6894 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6895 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6896 // At least one input vector was used. Create a new shuffle vector.
6897 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6903 // Concatenate the result back
6904 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6907 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6908 /// 4 elements, and match them with several different shuffle types.
6910 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6911 SDValue V1 = SVOp->getOperand(0);
6912 SDValue V2 = SVOp->getOperand(1);
6914 MVT VT = SVOp->getSimpleValueType(0);
6916 assert(VT.is128BitVector() && "Unsupported vector size");
6918 std::pair<int, int> Locs[4];
6919 int Mask1[] = { -1, -1, -1, -1 };
6920 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6924 for (unsigned i = 0; i != 4; ++i) {
6925 int Idx = PermMask[i];
6927 Locs[i] = std::make_pair(-1, -1);
6929 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6931 Locs[i] = std::make_pair(0, NumLo);
6935 Locs[i] = std::make_pair(1, NumHi);
6937 Mask1[2+NumHi] = Idx;
6943 if (NumLo <= 2 && NumHi <= 2) {
6944 // If no more than two elements come from either vector. This can be
6945 // implemented with two shuffles. First shuffle gather the elements.
6946 // The second shuffle, which takes the first shuffle as both of its
6947 // vector operands, put the elements into the right order.
6948 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6950 int Mask2[] = { -1, -1, -1, -1 };
6952 for (unsigned i = 0; i != 4; ++i)
6953 if (Locs[i].first != -1) {
6954 unsigned Idx = (i < 2) ? 0 : 4;
6955 Idx += Locs[i].first * 2 + Locs[i].second;
6959 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6962 if (NumLo == 3 || NumHi == 3) {
6963 // Otherwise, we must have three elements from one vector, call it X, and
6964 // one element from the other, call it Y. First, use a shufps to build an
6965 // intermediate vector with the one element from Y and the element from X
6966 // that will be in the same half in the final destination (the indexes don't
6967 // matter). Then, use a shufps to build the final vector, taking the half
6968 // containing the element from Y from the intermediate, and the other half
6971 // Normalize it so the 3 elements come from V1.
6972 CommuteVectorShuffleMask(PermMask, 4);
6976 // Find the element from V2.
6978 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6979 int Val = PermMask[HiIndex];
6986 Mask1[0] = PermMask[HiIndex];
6988 Mask1[2] = PermMask[HiIndex^1];
6990 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6993 Mask1[0] = PermMask[0];
6994 Mask1[1] = PermMask[1];
6995 Mask1[2] = HiIndex & 1 ? 6 : 4;
6996 Mask1[3] = HiIndex & 1 ? 4 : 6;
6997 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7000 Mask1[0] = HiIndex & 1 ? 2 : 0;
7001 Mask1[1] = HiIndex & 1 ? 0 : 2;
7002 Mask1[2] = PermMask[2];
7003 Mask1[3] = PermMask[3];
7008 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7011 // Break it into (shuffle shuffle_hi, shuffle_lo).
7012 int LoMask[] = { -1, -1, -1, -1 };
7013 int HiMask[] = { -1, -1, -1, -1 };
7015 int *MaskPtr = LoMask;
7016 unsigned MaskIdx = 0;
7019 for (unsigned i = 0; i != 4; ++i) {
7026 int Idx = PermMask[i];
7028 Locs[i] = std::make_pair(-1, -1);
7029 } else if (Idx < 4) {
7030 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7031 MaskPtr[LoIdx] = Idx;
7034 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7035 MaskPtr[HiIdx] = Idx;
7040 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7041 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7042 int MaskOps[] = { -1, -1, -1, -1 };
7043 for (unsigned i = 0; i != 4; ++i)
7044 if (Locs[i].first != -1)
7045 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7046 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7049 static bool MayFoldVectorLoad(SDValue V) {
7050 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7051 V = V.getOperand(0);
7053 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7054 V = V.getOperand(0);
7055 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7056 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7057 // BUILD_VECTOR (load), undef
7058 V = V.getOperand(0);
7060 return MayFoldLoad(V);
7064 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7065 MVT VT = Op.getSimpleValueType();
7067 // Canonizalize to v2f64.
7068 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7069 return DAG.getNode(ISD::BITCAST, dl, VT,
7070 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7075 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7077 SDValue V1 = Op.getOperand(0);
7078 SDValue V2 = Op.getOperand(1);
7079 MVT VT = Op.getSimpleValueType();
7081 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7083 if (HasSSE2 && VT == MVT::v2f64)
7084 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7086 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7087 return DAG.getNode(ISD::BITCAST, dl, VT,
7088 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7089 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7090 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7094 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7095 SDValue V1 = Op.getOperand(0);
7096 SDValue V2 = Op.getOperand(1);
7097 MVT VT = Op.getSimpleValueType();
7099 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7100 "unsupported shuffle type");
7102 if (V2.getOpcode() == ISD::UNDEF)
7106 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7110 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7111 SDValue V1 = Op.getOperand(0);
7112 SDValue V2 = Op.getOperand(1);
7113 MVT VT = Op.getSimpleValueType();
7114 unsigned NumElems = VT.getVectorNumElements();
7116 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7117 // operand of these instructions is only memory, so check if there's a
7118 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7120 bool CanFoldLoad = false;
7122 // Trivial case, when V2 comes from a load.
7123 if (MayFoldVectorLoad(V2))
7126 // When V1 is a load, it can be folded later into a store in isel, example:
7127 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7129 // (MOVLPSmr addr:$src1, VR128:$src2)
7130 // So, recognize this potential and also use MOVLPS or MOVLPD
7131 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7134 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7136 if (HasSSE2 && NumElems == 2)
7137 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7140 // If we don't care about the second element, proceed to use movss.
7141 if (SVOp->getMaskElt(1) != -1)
7142 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7145 // movl and movlp will both match v2i64, but v2i64 is never matched by
7146 // movl earlier because we make it strict to avoid messing with the movlp load
7147 // folding logic (see the code above getMOVLP call). Match it here then,
7148 // this is horrible, but will stay like this until we move all shuffle
7149 // matching to x86 specific nodes. Note that for the 1st condition all
7150 // types are matched with movsd.
7152 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7153 // as to remove this logic from here, as much as possible
7154 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7155 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7156 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7159 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7161 // Invert the operand order and use SHUFPS to match it.
7162 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7163 getShuffleSHUFImmediate(SVOp), DAG);
7166 // Reduce a vector shuffle to zext.
7167 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7168 SelectionDAG &DAG) {
7169 // PMOVZX is only available from SSE41.
7170 if (!Subtarget->hasSSE41())
7173 MVT VT = Op.getSimpleValueType();
7175 // Only AVX2 support 256-bit vector integer extending.
7176 if (!Subtarget->hasInt256() && VT.is256BitVector())
7179 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7181 SDValue V1 = Op.getOperand(0);
7182 SDValue V2 = Op.getOperand(1);
7183 unsigned NumElems = VT.getVectorNumElements();
7185 // Extending is an unary operation and the element type of the source vector
7186 // won't be equal to or larger than i64.
7187 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7188 VT.getVectorElementType() == MVT::i64)
7191 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7192 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7193 while ((1U << Shift) < NumElems) {
7194 if (SVOp->getMaskElt(1U << Shift) == 1)
7197 // The maximal ratio is 8, i.e. from i8 to i64.
7202 // Check the shuffle mask.
7203 unsigned Mask = (1U << Shift) - 1;
7204 for (unsigned i = 0; i != NumElems; ++i) {
7205 int EltIdx = SVOp->getMaskElt(i);
7206 if ((i & Mask) != 0 && EltIdx != -1)
7208 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7212 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7213 MVT NeVT = MVT::getIntegerVT(NBits);
7214 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7216 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7219 // Simplify the operand as it's prepared to be fed into shuffle.
7220 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7221 if (V1.getOpcode() == ISD::BITCAST &&
7222 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7223 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7224 V1.getOperand(0).getOperand(0)
7225 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7226 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7227 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7228 ConstantSDNode *CIdx =
7229 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7230 // If it's foldable, i.e. normal load with single use, we will let code
7231 // selection to fold it. Otherwise, we will short the conversion sequence.
7232 if (CIdx && CIdx->getZExtValue() == 0 &&
7233 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7234 MVT FullVT = V.getSimpleValueType();
7235 MVT V1VT = V1.getSimpleValueType();
7236 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7237 // The "ext_vec_elt" node is wider than the result node.
7238 // In this case we should extract subvector from V.
7239 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7240 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7241 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7242 FullVT.getVectorNumElements()/Ratio);
7243 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7244 DAG.getIntPtrConstant(0));
7246 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7250 return DAG.getNode(ISD::BITCAST, DL, VT,
7251 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7255 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7256 SelectionDAG &DAG) {
7257 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7258 MVT VT = Op.getSimpleValueType();
7260 SDValue V1 = Op.getOperand(0);
7261 SDValue V2 = Op.getOperand(1);
7263 if (isZeroShuffle(SVOp))
7264 return getZeroVector(VT, Subtarget, DAG, dl);
7266 // Handle splat operations
7267 if (SVOp->isSplat()) {
7268 // Use vbroadcast whenever the splat comes from a foldable load
7269 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7270 if (Broadcast.getNode())
7274 // Check integer expanding shuffles.
7275 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7276 if (NewOp.getNode())
7279 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7281 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7282 VT == MVT::v16i16 || VT == MVT::v32i8) {
7283 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7284 if (NewOp.getNode())
7285 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7286 } else if ((VT == MVT::v4i32 ||
7287 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7288 // FIXME: Figure out a cleaner way to do this.
7289 // Try to make use of movq to zero out the top part.
7290 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7291 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7292 if (NewOp.getNode()) {
7293 MVT NewVT = NewOp.getSimpleValueType();
7294 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7295 NewVT, true, false))
7296 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7297 DAG, Subtarget, dl);
7299 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7300 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7301 if (NewOp.getNode()) {
7302 MVT NewVT = NewOp.getSimpleValueType();
7303 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7304 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7305 DAG, Subtarget, dl);
7313 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7314 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7315 SDValue V1 = Op.getOperand(0);
7316 SDValue V2 = Op.getOperand(1);
7317 MVT VT = Op.getSimpleValueType();
7319 unsigned NumElems = VT.getVectorNumElements();
7320 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7321 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7322 bool V1IsSplat = false;
7323 bool V2IsSplat = false;
7324 bool HasSSE2 = Subtarget->hasSSE2();
7325 bool HasFp256 = Subtarget->hasFp256();
7326 bool HasInt256 = Subtarget->hasInt256();
7327 MachineFunction &MF = DAG.getMachineFunction();
7328 bool OptForSize = MF.getFunction()->getAttributes().
7329 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7331 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7333 if (V1IsUndef && V2IsUndef)
7334 return DAG.getUNDEF(VT);
7336 // When we create a shuffle node we put the UNDEF node to second operand,
7337 // but in some cases the first operand may be transformed to UNDEF.
7338 // In this case we should just commute the node.
7340 return CommuteVectorShuffle(SVOp, DAG);
7342 // Vector shuffle lowering takes 3 steps:
7344 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7345 // narrowing and commutation of operands should be handled.
7346 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7348 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7349 // so the shuffle can be broken into other shuffles and the legalizer can
7350 // try the lowering again.
7352 // The general idea is that no vector_shuffle operation should be left to
7353 // be matched during isel, all of them must be converted to a target specific
7356 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7357 // narrowing and commutation of operands should be handled. The actual code
7358 // doesn't include all of those, work in progress...
7359 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7360 if (NewOp.getNode())
7363 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7365 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7366 // unpckh_undef). Only use pshufd if speed is more important than size.
7367 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7368 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7369 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7370 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7372 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7373 V2IsUndef && MayFoldVectorLoad(V1))
7374 return getMOVDDup(Op, dl, V1, DAG);
7376 if (isMOVHLPS_v_undef_Mask(M, VT))
7377 return getMOVHighToLow(Op, dl, DAG);
7379 // Use to match splats
7380 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7381 (VT == MVT::v2f64 || VT == MVT::v2i64))
7382 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7384 if (isPSHUFDMask(M, VT)) {
7385 // The actual implementation will match the mask in the if above and then
7386 // during isel it can match several different instructions, not only pshufd
7387 // as its name says, sad but true, emulate the behavior for now...
7388 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7389 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7391 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7393 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7394 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7396 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7397 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7400 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7404 if (isPALIGNRMask(M, VT, Subtarget))
7405 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7406 getShufflePALIGNRImmediate(SVOp),
7409 // Check if this can be converted into a logical shift.
7410 bool isLeft = false;
7413 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7414 if (isShift && ShVal.hasOneUse()) {
7415 // If the shifted value has multiple uses, it may be cheaper to use
7416 // v_set0 + movlhps or movhlps, etc.
7417 MVT EltVT = VT.getVectorElementType();
7418 ShAmt *= EltVT.getSizeInBits();
7419 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7422 if (isMOVLMask(M, VT)) {
7423 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7424 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7425 if (!isMOVLPMask(M, VT)) {
7426 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7427 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7429 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7430 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7434 // FIXME: fold these into legal mask.
7435 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7436 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7438 if (isMOVHLPSMask(M, VT))
7439 return getMOVHighToLow(Op, dl, DAG);
7441 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7442 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7444 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7445 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7447 if (isMOVLPMask(M, VT))
7448 return getMOVLP(Op, dl, DAG, HasSSE2);
7450 if (ShouldXformToMOVHLPS(M, VT) ||
7451 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7452 return CommuteVectorShuffle(SVOp, DAG);
7455 // No better options. Use a vshldq / vsrldq.
7456 MVT EltVT = VT.getVectorElementType();
7457 ShAmt *= EltVT.getSizeInBits();
7458 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7461 bool Commuted = false;
7462 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7463 // 1,1,1,1 -> v8i16 though.
7464 V1IsSplat = isSplatVector(V1.getNode());
7465 V2IsSplat = isSplatVector(V2.getNode());
7467 // Canonicalize the splat or undef, if present, to be on the RHS.
7468 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7469 CommuteVectorShuffleMask(M, NumElems);
7471 std::swap(V1IsSplat, V2IsSplat);
7475 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7476 // Shuffling low element of v1 into undef, just return v1.
7479 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7480 // the instruction selector will not match, so get a canonical MOVL with
7481 // swapped operands to undo the commute.
7482 return getMOVL(DAG, dl, VT, V2, V1);
7485 if (isUNPCKLMask(M, VT, HasInt256))
7486 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7488 if (isUNPCKHMask(M, VT, HasInt256))
7489 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7492 // Normalize mask so all entries that point to V2 points to its first
7493 // element then try to match unpck{h|l} again. If match, return a
7494 // new vector_shuffle with the corrected mask.p
7495 SmallVector<int, 8> NewMask(M.begin(), M.end());
7496 NormalizeMask(NewMask, NumElems);
7497 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7498 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7499 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7500 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7504 // Commute is back and try unpck* again.
7505 // FIXME: this seems wrong.
7506 CommuteVectorShuffleMask(M, NumElems);
7508 std::swap(V1IsSplat, V2IsSplat);
7511 if (isUNPCKLMask(M, VT, HasInt256))
7512 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7514 if (isUNPCKHMask(M, VT, HasInt256))
7515 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7518 // Normalize the node to match x86 shuffle ops if needed
7519 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7520 return CommuteVectorShuffle(SVOp, DAG);
7522 // The checks below are all present in isShuffleMaskLegal, but they are
7523 // inlined here right now to enable us to directly emit target specific
7524 // nodes, and remove one by one until they don't return Op anymore.
7526 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7527 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7528 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7529 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7532 if (isPSHUFHWMask(M, VT, HasInt256))
7533 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7534 getShufflePSHUFHWImmediate(SVOp),
7537 if (isPSHUFLWMask(M, VT, HasInt256))
7538 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7539 getShufflePSHUFLWImmediate(SVOp),
7542 if (isSHUFPMask(M, VT))
7543 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7544 getShuffleSHUFImmediate(SVOp), DAG);
7546 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7547 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7548 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7549 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7551 //===--------------------------------------------------------------------===//
7552 // Generate target specific nodes for 128 or 256-bit shuffles only
7553 // supported in the AVX instruction set.
7556 // Handle VMOVDDUPY permutations
7557 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7558 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7560 // Handle VPERMILPS/D* permutations
7561 if (isVPERMILPMask(M, VT)) {
7562 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7563 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7564 getShuffleSHUFImmediate(SVOp), DAG);
7565 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7566 getShuffleSHUFImmediate(SVOp), DAG);
7569 // Handle VPERM2F128/VPERM2I128 permutations
7570 if (isVPERM2X128Mask(M, VT, HasFp256))
7571 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7572 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7574 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7575 if (BlendOp.getNode())
7579 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7580 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7582 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7583 VT.is512BitVector()) {
7584 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7585 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7586 SmallVector<SDValue, 16> permclMask;
7587 for (unsigned i = 0; i != NumElems; ++i) {
7588 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7591 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7592 &permclMask[0], NumElems);
7594 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7595 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7596 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7597 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7598 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7601 //===--------------------------------------------------------------------===//
7602 // Since no target specific shuffle was selected for this generic one,
7603 // lower it into other known shuffles. FIXME: this isn't true yet, but
7604 // this is the plan.
7607 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7608 if (VT == MVT::v8i16) {
7609 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7610 if (NewOp.getNode())
7614 if (VT == MVT::v16i8) {
7615 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7616 if (NewOp.getNode())
7620 if (VT == MVT::v32i8) {
7621 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7622 if (NewOp.getNode())
7626 // Handle all 128-bit wide vectors with 4 elements, and match them with
7627 // several different shuffle types.
7628 if (NumElems == 4 && VT.is128BitVector())
7629 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7631 // Handle general 256-bit shuffles
7632 if (VT.is256BitVector())
7633 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7638 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7639 MVT VT = Op.getSimpleValueType();
7642 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7645 if (VT.getSizeInBits() == 8) {
7646 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7647 Op.getOperand(0), Op.getOperand(1));
7648 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7649 DAG.getValueType(VT));
7650 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7653 if (VT.getSizeInBits() == 16) {
7654 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7655 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7657 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7658 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7659 DAG.getNode(ISD::BITCAST, dl,
7663 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7664 Op.getOperand(0), Op.getOperand(1));
7665 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7666 DAG.getValueType(VT));
7667 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7670 if (VT == MVT::f32) {
7671 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7672 // the result back to FR32 register. It's only worth matching if the
7673 // result has a single use which is a store or a bitcast to i32. And in
7674 // the case of a store, it's not worth it if the index is a constant 0,
7675 // because a MOVSSmr can be used instead, which is smaller and faster.
7676 if (!Op.hasOneUse())
7678 SDNode *User = *Op.getNode()->use_begin();
7679 if ((User->getOpcode() != ISD::STORE ||
7680 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7681 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7682 (User->getOpcode() != ISD::BITCAST ||
7683 User->getValueType(0) != MVT::i32))
7685 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7686 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7689 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7692 if (VT == MVT::i32 || VT == MVT::i64) {
7693 // ExtractPS/pextrq works with constant index.
7694 if (isa<ConstantSDNode>(Op.getOperand(1)))
7700 /// Extract one bit from mask vector, like v16i1 or v8i1.
7701 /// AVX-512 feature.
7703 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7704 SDValue Vec = Op.getOperand(0);
7706 MVT VecVT = Vec.getSimpleValueType();
7707 SDValue Idx = Op.getOperand(1);
7708 MVT EltVT = Op.getSimpleValueType();
7710 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7712 // variable index can't be handled in mask registers,
7713 // extend vector to VR512
7714 if (!isa<ConstantSDNode>(Idx)) {
7715 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7716 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7717 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7718 ExtVT.getVectorElementType(), Ext, Idx);
7719 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7722 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7723 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7724 unsigned MaxSift = rc->getSize()*8 - 1;
7725 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7726 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7727 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7728 DAG.getConstant(MaxSift, MVT::i8));
7729 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7730 DAG.getIntPtrConstant(0));
7734 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7735 SelectionDAG &DAG) const {
7737 SDValue Vec = Op.getOperand(0);
7738 MVT VecVT = Vec.getSimpleValueType();
7739 SDValue Idx = Op.getOperand(1);
7741 if (Op.getSimpleValueType() == MVT::i1)
7742 return ExtractBitFromMaskVector(Op, DAG);
7744 if (!isa<ConstantSDNode>(Idx)) {
7745 if (VecVT.is512BitVector() ||
7746 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7747 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7750 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7751 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7752 MaskEltVT.getSizeInBits());
7754 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7755 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7756 getZeroVector(MaskVT, Subtarget, DAG, dl),
7757 Idx, DAG.getConstant(0, getPointerTy()));
7758 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7759 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7760 Perm, DAG.getConstant(0, getPointerTy()));
7765 // If this is a 256-bit vector result, first extract the 128-bit vector and
7766 // then extract the element from the 128-bit vector.
7767 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7769 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7770 // Get the 128-bit vector.
7771 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7772 MVT EltVT = VecVT.getVectorElementType();
7774 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7776 //if (IdxVal >= NumElems/2)
7777 // IdxVal -= NumElems/2;
7778 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7779 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7780 DAG.getConstant(IdxVal, MVT::i32));
7783 assert(VecVT.is128BitVector() && "Unexpected vector length");
7785 if (Subtarget->hasSSE41()) {
7786 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7791 MVT VT = Op.getSimpleValueType();
7792 // TODO: handle v16i8.
7793 if (VT.getSizeInBits() == 16) {
7794 SDValue Vec = Op.getOperand(0);
7795 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7797 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7798 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7799 DAG.getNode(ISD::BITCAST, dl,
7802 // Transform it so it match pextrw which produces a 32-bit result.
7803 MVT EltVT = MVT::i32;
7804 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7805 Op.getOperand(0), Op.getOperand(1));
7806 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7807 DAG.getValueType(VT));
7808 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7811 if (VT.getSizeInBits() == 32) {
7812 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7816 // SHUFPS the element to the lowest double word, then movss.
7817 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7818 MVT VVT = Op.getOperand(0).getSimpleValueType();
7819 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7820 DAG.getUNDEF(VVT), Mask);
7821 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7822 DAG.getIntPtrConstant(0));
7825 if (VT.getSizeInBits() == 64) {
7826 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7827 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7828 // to match extract_elt for f64.
7829 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7833 // UNPCKHPD the element to the lowest double word, then movsd.
7834 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7835 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7836 int Mask[2] = { 1, -1 };
7837 MVT VVT = Op.getOperand(0).getSimpleValueType();
7838 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7839 DAG.getUNDEF(VVT), Mask);
7840 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7841 DAG.getIntPtrConstant(0));
7847 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7848 MVT VT = Op.getSimpleValueType();
7849 MVT EltVT = VT.getVectorElementType();
7852 SDValue N0 = Op.getOperand(0);
7853 SDValue N1 = Op.getOperand(1);
7854 SDValue N2 = Op.getOperand(2);
7856 if (!VT.is128BitVector())
7859 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7860 isa<ConstantSDNode>(N2)) {
7862 if (VT == MVT::v8i16)
7863 Opc = X86ISD::PINSRW;
7864 else if (VT == MVT::v16i8)
7865 Opc = X86ISD::PINSRB;
7867 Opc = X86ISD::PINSRB;
7869 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7871 if (N1.getValueType() != MVT::i32)
7872 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7873 if (N2.getValueType() != MVT::i32)
7874 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7875 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7878 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7879 // Bits [7:6] of the constant are the source select. This will always be
7880 // zero here. The DAG Combiner may combine an extract_elt index into these
7881 // bits. For example (insert (extract, 3), 2) could be matched by putting
7882 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7883 // Bits [5:4] of the constant are the destination select. This is the
7884 // value of the incoming immediate.
7885 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7886 // combine either bitwise AND or insert of float 0.0 to set these bits.
7887 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7888 // Create this as a scalar to vector..
7889 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7890 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7893 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7894 // PINSR* works with constant index.
7901 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7902 MVT VT = Op.getSimpleValueType();
7903 MVT EltVT = VT.getVectorElementType();
7906 SDValue N0 = Op.getOperand(0);
7907 SDValue N1 = Op.getOperand(1);
7908 SDValue N2 = Op.getOperand(2);
7910 // If this is a 256-bit vector result, first extract the 128-bit vector,
7911 // insert the element into the extracted half and then place it back.
7912 if (VT.is256BitVector() || VT.is512BitVector()) {
7913 if (!isa<ConstantSDNode>(N2))
7916 // Get the desired 128-bit vector half.
7917 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7918 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7920 // Insert the element into the desired half.
7921 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7922 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7924 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7925 DAG.getConstant(IdxIn128, MVT::i32));
7927 // Insert the changed part back to the 256-bit vector
7928 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7931 if (Subtarget->hasSSE41())
7932 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7934 if (EltVT == MVT::i8)
7937 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7938 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7939 // as its second argument.
7940 if (N1.getValueType() != MVT::i32)
7941 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7942 if (N2.getValueType() != MVT::i32)
7943 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7944 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7949 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7951 MVT OpVT = Op.getSimpleValueType();
7953 // If this is a 256-bit vector result, first insert into a 128-bit
7954 // vector and then insert into the 256-bit vector.
7955 if (!OpVT.is128BitVector()) {
7956 // Insert into a 128-bit vector.
7957 unsigned SizeFactor = OpVT.getSizeInBits()/128;
7958 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7959 OpVT.getVectorNumElements() / SizeFactor);
7961 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7963 // Insert the 128-bit vector.
7964 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7967 if (OpVT == MVT::v1i64 &&
7968 Op.getOperand(0).getValueType() == MVT::i64)
7969 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7971 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7972 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7973 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7974 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7977 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7978 // a simple subregister reference or explicit instructions to grab
7979 // upper bits of a vector.
7980 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7981 SelectionDAG &DAG) {
7983 SDValue In = Op.getOperand(0);
7984 SDValue Idx = Op.getOperand(1);
7985 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7986 MVT ResVT = Op.getSimpleValueType();
7987 MVT InVT = In.getSimpleValueType();
7989 if (Subtarget->hasFp256()) {
7990 if (ResVT.is128BitVector() &&
7991 (InVT.is256BitVector() || InVT.is512BitVector()) &&
7992 isa<ConstantSDNode>(Idx)) {
7993 return Extract128BitVector(In, IdxVal, DAG, dl);
7995 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7996 isa<ConstantSDNode>(Idx)) {
7997 return Extract256BitVector(In, IdxVal, DAG, dl);
8003 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8004 // simple superregister reference or explicit instructions to insert
8005 // the upper bits of a vector.
8006 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8007 SelectionDAG &DAG) {
8008 if (Subtarget->hasFp256()) {
8009 SDLoc dl(Op.getNode());
8010 SDValue Vec = Op.getNode()->getOperand(0);
8011 SDValue SubVec = Op.getNode()->getOperand(1);
8012 SDValue Idx = Op.getNode()->getOperand(2);
8014 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8015 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8016 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8017 isa<ConstantSDNode>(Idx)) {
8018 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8019 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8022 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8023 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8024 isa<ConstantSDNode>(Idx)) {
8025 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8026 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8032 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8033 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8034 // one of the above mentioned nodes. It has to be wrapped because otherwise
8035 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8036 // be used to form addressing mode. These wrapped nodes will be selected
8039 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8040 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8042 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8044 unsigned char OpFlag = 0;
8045 unsigned WrapperKind = X86ISD::Wrapper;
8046 CodeModel::Model M = getTargetMachine().getCodeModel();
8048 if (Subtarget->isPICStyleRIPRel() &&
8049 (M == CodeModel::Small || M == CodeModel::Kernel))
8050 WrapperKind = X86ISD::WrapperRIP;
8051 else if (Subtarget->isPICStyleGOT())
8052 OpFlag = X86II::MO_GOTOFF;
8053 else if (Subtarget->isPICStyleStubPIC())
8054 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8056 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8058 CP->getOffset(), OpFlag);
8060 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8061 // With PIC, the address is actually $g + Offset.
8063 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8064 DAG.getNode(X86ISD::GlobalBaseReg,
8065 SDLoc(), getPointerTy()),
8072 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8073 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8075 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8077 unsigned char OpFlag = 0;
8078 unsigned WrapperKind = X86ISD::Wrapper;
8079 CodeModel::Model M = getTargetMachine().getCodeModel();
8081 if (Subtarget->isPICStyleRIPRel() &&
8082 (M == CodeModel::Small || M == CodeModel::Kernel))
8083 WrapperKind = X86ISD::WrapperRIP;
8084 else if (Subtarget->isPICStyleGOT())
8085 OpFlag = X86II::MO_GOTOFF;
8086 else if (Subtarget->isPICStyleStubPIC())
8087 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8089 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8092 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8094 // With PIC, the address is actually $g + Offset.
8096 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8097 DAG.getNode(X86ISD::GlobalBaseReg,
8098 SDLoc(), getPointerTy()),
8105 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8106 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8108 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8110 unsigned char OpFlag = 0;
8111 unsigned WrapperKind = X86ISD::Wrapper;
8112 CodeModel::Model M = getTargetMachine().getCodeModel();
8114 if (Subtarget->isPICStyleRIPRel() &&
8115 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8116 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8117 OpFlag = X86II::MO_GOTPCREL;
8118 WrapperKind = X86ISD::WrapperRIP;
8119 } else if (Subtarget->isPICStyleGOT()) {
8120 OpFlag = X86II::MO_GOT;
8121 } else if (Subtarget->isPICStyleStubPIC()) {
8122 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8123 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8124 OpFlag = X86II::MO_DARWIN_NONLAZY;
8127 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8130 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8132 // With PIC, the address is actually $g + Offset.
8133 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8134 !Subtarget->is64Bit()) {
8135 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8136 DAG.getNode(X86ISD::GlobalBaseReg,
8137 SDLoc(), getPointerTy()),
8141 // For symbols that require a load from a stub to get the address, emit the
8143 if (isGlobalStubReference(OpFlag))
8144 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8145 MachinePointerInfo::getGOT(), false, false, false, 0);
8151 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8152 // Create the TargetBlockAddressAddress node.
8153 unsigned char OpFlags =
8154 Subtarget->ClassifyBlockAddressReference();
8155 CodeModel::Model M = getTargetMachine().getCodeModel();
8156 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8157 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8159 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8162 if (Subtarget->isPICStyleRIPRel() &&
8163 (M == CodeModel::Small || M == CodeModel::Kernel))
8164 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8166 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8168 // With PIC, the address is actually $g + Offset.
8169 if (isGlobalRelativeToPICBase(OpFlags)) {
8170 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8171 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8179 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8180 int64_t Offset, SelectionDAG &DAG) const {
8181 // Create the TargetGlobalAddress node, folding in the constant
8182 // offset if it is legal.
8183 unsigned char OpFlags =
8184 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8185 CodeModel::Model M = getTargetMachine().getCodeModel();
8187 if (OpFlags == X86II::MO_NO_FLAG &&
8188 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8189 // A direct static reference to a global.
8190 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8193 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8196 if (Subtarget->isPICStyleRIPRel() &&
8197 (M == CodeModel::Small || M == CodeModel::Kernel))
8198 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8200 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8202 // With PIC, the address is actually $g + Offset.
8203 if (isGlobalRelativeToPICBase(OpFlags)) {
8204 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8205 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8209 // For globals that require a load from a stub to get the address, emit the
8211 if (isGlobalStubReference(OpFlags))
8212 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8213 MachinePointerInfo::getGOT(), false, false, false, 0);
8215 // If there was a non-zero offset that we didn't fold, create an explicit
8218 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8219 DAG.getConstant(Offset, getPointerTy()));
8225 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8226 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8227 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8228 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8232 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8233 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8234 unsigned char OperandFlags, bool LocalDynamic = false) {
8235 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8236 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8238 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8239 GA->getValueType(0),
8243 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8247 SDValue Ops[] = { Chain, TGA, *InFlag };
8248 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8250 SDValue Ops[] = { Chain, TGA };
8251 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8254 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8255 MFI->setAdjustsStack(true);
8257 SDValue Flag = Chain.getValue(1);
8258 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8261 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8263 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8266 SDLoc dl(GA); // ? function entry point might be better
8267 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8268 DAG.getNode(X86ISD::GlobalBaseReg,
8269 SDLoc(), PtrVT), InFlag);
8270 InFlag = Chain.getValue(1);
8272 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8275 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8277 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8279 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8280 X86::RAX, X86II::MO_TLSGD);
8283 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8289 // Get the start address of the TLS block for this module.
8290 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8291 .getInfo<X86MachineFunctionInfo>();
8292 MFI->incNumLocalDynamicTLSAccesses();
8296 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8297 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8300 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8301 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8302 InFlag = Chain.getValue(1);
8303 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8304 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8307 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8311 unsigned char OperandFlags = X86II::MO_DTPOFF;
8312 unsigned WrapperKind = X86ISD::Wrapper;
8313 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8314 GA->getValueType(0),
8315 GA->getOffset(), OperandFlags);
8316 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8318 // Add x@dtpoff with the base.
8319 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8322 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8323 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8324 const EVT PtrVT, TLSModel::Model model,
8325 bool is64Bit, bool isPIC) {
8328 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8329 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8330 is64Bit ? 257 : 256));
8332 SDValue ThreadPointer =
8333 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8334 MachinePointerInfo(Ptr), false, false, false, 0);
8336 unsigned char OperandFlags = 0;
8337 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8339 unsigned WrapperKind = X86ISD::Wrapper;
8340 if (model == TLSModel::LocalExec) {
8341 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8342 } else if (model == TLSModel::InitialExec) {
8344 OperandFlags = X86II::MO_GOTTPOFF;
8345 WrapperKind = X86ISD::WrapperRIP;
8347 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8350 llvm_unreachable("Unexpected model");
8353 // emit "addl x@ntpoff,%eax" (local exec)
8354 // or "addl x@indntpoff,%eax" (initial exec)
8355 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8357 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8358 GA->getOffset(), OperandFlags);
8359 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8361 if (model == TLSModel::InitialExec) {
8362 if (isPIC && !is64Bit) {
8363 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8364 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8368 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8369 MachinePointerInfo::getGOT(), false, false, false, 0);
8372 // The address of the thread local variable is the add of the thread
8373 // pointer with the offset of the variable.
8374 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8378 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8380 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8381 const GlobalValue *GV = GA->getGlobal();
8383 if (Subtarget->isTargetELF()) {
8384 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8387 case TLSModel::GeneralDynamic:
8388 if (Subtarget->is64Bit())
8389 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8390 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8391 case TLSModel::LocalDynamic:
8392 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8393 Subtarget->is64Bit());
8394 case TLSModel::InitialExec:
8395 case TLSModel::LocalExec:
8396 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8397 Subtarget->is64Bit(),
8398 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8400 llvm_unreachable("Unknown TLS model.");
8403 if (Subtarget->isTargetDarwin()) {
8404 // Darwin only has one model of TLS. Lower to that.
8405 unsigned char OpFlag = 0;
8406 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8407 X86ISD::WrapperRIP : X86ISD::Wrapper;
8409 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8411 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8412 !Subtarget->is64Bit();
8414 OpFlag = X86II::MO_TLVP_PIC_BASE;
8416 OpFlag = X86II::MO_TLVP;
8418 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8419 GA->getValueType(0),
8420 GA->getOffset(), OpFlag);
8421 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8423 // With PIC32, the address is actually $g + Offset.
8425 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8426 DAG.getNode(X86ISD::GlobalBaseReg,
8427 SDLoc(), getPointerTy()),
8430 // Lowering the machine isd will make sure everything is in the right
8432 SDValue Chain = DAG.getEntryNode();
8433 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8434 SDValue Args[] = { Chain, Offset };
8435 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8437 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8438 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8439 MFI->setAdjustsStack(true);
8441 // And our return value (tls address) is in the standard call return value
8443 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8444 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8448 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8449 // Just use the implicit TLS architecture
8450 // Need to generate someting similar to:
8451 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8453 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8454 // mov rcx, qword [rdx+rcx*8]
8455 // mov eax, .tls$:tlsvar
8456 // [rax+rcx] contains the address
8457 // Windows 64bit: gs:0x58
8458 // Windows 32bit: fs:__tls_array
8460 // If GV is an alias then use the aliasee for determining
8461 // thread-localness.
8462 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8463 GV = GA->resolveAliasedGlobal(false);
8465 SDValue Chain = DAG.getEntryNode();
8467 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8468 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8469 // use its literal value of 0x2C.
8470 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8471 ? Type::getInt8PtrTy(*DAG.getContext(),
8473 : Type::getInt32PtrTy(*DAG.getContext(),
8476 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8477 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8478 DAG.getExternalSymbol("_tls_array", getPointerTy()));
8480 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8481 MachinePointerInfo(Ptr),
8482 false, false, false, 0);
8484 // Load the _tls_index variable
8485 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8486 if (Subtarget->is64Bit())
8487 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8488 IDX, MachinePointerInfo(), MVT::i32,
8491 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8492 false, false, false, 0);
8494 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8496 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8498 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8499 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8500 false, false, false, 0);
8502 // Get the offset of start of .tls section
8503 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8504 GA->getValueType(0),
8505 GA->getOffset(), X86II::MO_SECREL);
8506 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8508 // The address of the thread local variable is the add of the thread
8509 // pointer with the offset of the variable.
8510 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8513 llvm_unreachable("TLS not implemented for this target.");
8516 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8517 /// and take a 2 x i32 value to shift plus a shift amount.
8518 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8519 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8520 MVT VT = Op.getSimpleValueType();
8521 unsigned VTBits = VT.getSizeInBits();
8523 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8524 SDValue ShOpLo = Op.getOperand(0);
8525 SDValue ShOpHi = Op.getOperand(1);
8526 SDValue ShAmt = Op.getOperand(2);
8527 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8528 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8530 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8531 DAG.getConstant(VTBits - 1, MVT::i8));
8532 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8533 DAG.getConstant(VTBits - 1, MVT::i8))
8534 : DAG.getConstant(0, VT);
8537 if (Op.getOpcode() == ISD::SHL_PARTS) {
8538 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8539 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8541 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8542 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8545 // If the shift amount is larger or equal than the width of a part we can't
8546 // rely on the results of shld/shrd. Insert a test and select the appropriate
8547 // values for large shift amounts.
8548 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8549 DAG.getConstant(VTBits, MVT::i8));
8550 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8551 AndNode, DAG.getConstant(0, MVT::i8));
8554 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8555 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8556 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8558 if (Op.getOpcode() == ISD::SHL_PARTS) {
8559 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8560 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8562 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8563 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8566 SDValue Ops[2] = { Lo, Hi };
8567 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8570 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8571 SelectionDAG &DAG) const {
8572 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8574 if (SrcVT.isVector())
8577 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8578 "Unknown SINT_TO_FP to lower!");
8580 // These are really Legal; return the operand so the caller accepts it as
8582 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8584 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8585 Subtarget->is64Bit()) {
8590 unsigned Size = SrcVT.getSizeInBits()/8;
8591 MachineFunction &MF = DAG.getMachineFunction();
8592 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8593 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8594 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8596 MachinePointerInfo::getFixedStack(SSFI),
8598 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8601 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8603 SelectionDAG &DAG) const {
8607 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8609 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8611 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8613 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8615 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8616 MachineMemOperand *MMO;
8618 int SSFI = FI->getIndex();
8620 DAG.getMachineFunction()
8621 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8622 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8624 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8625 StackSlot = StackSlot.getOperand(1);
8627 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8628 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8630 Tys, Ops, array_lengthof(Ops),
8634 Chain = Result.getValue(1);
8635 SDValue InFlag = Result.getValue(2);
8637 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8638 // shouldn't be necessary except that RFP cannot be live across
8639 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8640 MachineFunction &MF = DAG.getMachineFunction();
8641 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8642 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8643 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8644 Tys = DAG.getVTList(MVT::Other);
8646 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8648 MachineMemOperand *MMO =
8649 DAG.getMachineFunction()
8650 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8651 MachineMemOperand::MOStore, SSFISize, SSFISize);
8653 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8654 Ops, array_lengthof(Ops),
8655 Op.getValueType(), MMO);
8656 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8657 MachinePointerInfo::getFixedStack(SSFI),
8658 false, false, false, 0);
8664 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8665 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8666 SelectionDAG &DAG) const {
8667 // This algorithm is not obvious. Here it is what we're trying to output:
8670 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8671 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8675 pshufd $0x4e, %xmm0, %xmm1
8681 LLVMContext *Context = DAG.getContext();
8683 // Build some magic constants.
8684 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8685 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8686 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8688 SmallVector<Constant*,2> CV1;
8690 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8691 APInt(64, 0x4330000000000000ULL))));
8693 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8694 APInt(64, 0x4530000000000000ULL))));
8695 Constant *C1 = ConstantVector::get(CV1);
8696 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8698 // Load the 64-bit value into an XMM register.
8699 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8701 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8702 MachinePointerInfo::getConstantPool(),
8703 false, false, false, 16);
8704 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8705 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8708 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8709 MachinePointerInfo::getConstantPool(),
8710 false, false, false, 16);
8711 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8712 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8715 if (Subtarget->hasSSE3()) {
8716 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8717 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8719 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8720 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8722 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8723 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8727 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8728 DAG.getIntPtrConstant(0));
8731 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8732 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8733 SelectionDAG &DAG) const {
8735 // FP constant to bias correct the final result.
8736 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8739 // Load the 32-bit value into an XMM register.
8740 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8743 // Zero out the upper parts of the register.
8744 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8746 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8747 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8748 DAG.getIntPtrConstant(0));
8750 // Or the load with the bias.
8751 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8752 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8753 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8755 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8756 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8757 MVT::v2f64, Bias)));
8758 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8759 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8760 DAG.getIntPtrConstant(0));
8762 // Subtract the bias.
8763 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8765 // Handle final rounding.
8766 EVT DestVT = Op.getValueType();
8768 if (DestVT.bitsLT(MVT::f64))
8769 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8770 DAG.getIntPtrConstant(0));
8771 if (DestVT.bitsGT(MVT::f64))
8772 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8774 // Handle final rounding.
8778 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8779 SelectionDAG &DAG) const {
8780 SDValue N0 = Op.getOperand(0);
8781 MVT SVT = N0.getSimpleValueType();
8784 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8785 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8786 "Custom UINT_TO_FP is not supported!");
8788 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8789 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8790 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8793 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8794 SelectionDAG &DAG) const {
8795 SDValue N0 = Op.getOperand(0);
8798 if (Op.getValueType().isVector())
8799 return lowerUINT_TO_FP_vec(Op, DAG);
8801 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8802 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8803 // the optimization here.
8804 if (DAG.SignBitIsZero(N0))
8805 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8807 MVT SrcVT = N0.getSimpleValueType();
8808 MVT DstVT = Op.getSimpleValueType();
8809 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8810 return LowerUINT_TO_FP_i64(Op, DAG);
8811 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8812 return LowerUINT_TO_FP_i32(Op, DAG);
8813 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8816 // Make a 64-bit buffer, and use it to build an FILD.
8817 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8818 if (SrcVT == MVT::i32) {
8819 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8820 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8821 getPointerTy(), StackSlot, WordOff);
8822 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8823 StackSlot, MachinePointerInfo(),
8825 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8826 OffsetSlot, MachinePointerInfo(),
8828 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8832 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8833 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8834 StackSlot, MachinePointerInfo(),
8836 // For i64 source, we need to add the appropriate power of 2 if the input
8837 // was negative. This is the same as the optimization in
8838 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8839 // we must be careful to do the computation in x87 extended precision, not
8840 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8841 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8842 MachineMemOperand *MMO =
8843 DAG.getMachineFunction()
8844 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8845 MachineMemOperand::MOLoad, 8, 8);
8847 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8848 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8849 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8850 array_lengthof(Ops), MVT::i64, MMO);
8852 APInt FF(32, 0x5F800000ULL);
8854 // Check whether the sign bit is set.
8855 SDValue SignSet = DAG.getSetCC(dl,
8856 getSetCCResultType(*DAG.getContext(), MVT::i64),
8857 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8860 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8861 SDValue FudgePtr = DAG.getConstantPool(
8862 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8865 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8866 SDValue Zero = DAG.getIntPtrConstant(0);
8867 SDValue Four = DAG.getIntPtrConstant(4);
8868 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8870 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8872 // Load the value out, extending it from f32 to f80.
8873 // FIXME: Avoid the extend by constructing the right constant pool?
8874 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8875 FudgePtr, MachinePointerInfo::getConstantPool(),
8876 MVT::f32, false, false, 4);
8877 // Extend everything to 80 bits to force it to be done on x87.
8878 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8879 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8882 std::pair<SDValue,SDValue>
8883 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8884 bool IsSigned, bool IsReplace) const {
8887 EVT DstTy = Op.getValueType();
8889 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8890 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8894 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8895 DstTy.getSimpleVT() >= MVT::i16 &&
8896 "Unknown FP_TO_INT to lower!");
8898 // These are really Legal.
8899 if (DstTy == MVT::i32 &&
8900 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8901 return std::make_pair(SDValue(), SDValue());
8902 if (Subtarget->is64Bit() &&
8903 DstTy == MVT::i64 &&
8904 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8905 return std::make_pair(SDValue(), SDValue());
8907 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8908 // stack slot, or into the FTOL runtime function.
8909 MachineFunction &MF = DAG.getMachineFunction();
8910 unsigned MemSize = DstTy.getSizeInBits()/8;
8911 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8912 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8915 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8916 Opc = X86ISD::WIN_FTOL;
8918 switch (DstTy.getSimpleVT().SimpleTy) {
8919 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8920 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8921 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8922 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8925 SDValue Chain = DAG.getEntryNode();
8926 SDValue Value = Op.getOperand(0);
8927 EVT TheVT = Op.getOperand(0).getValueType();
8928 // FIXME This causes a redundant load/store if the SSE-class value is already
8929 // in memory, such as if it is on the callstack.
8930 if (isScalarFPTypeInSSEReg(TheVT)) {
8931 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8932 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8933 MachinePointerInfo::getFixedStack(SSFI),
8935 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8937 Chain, StackSlot, DAG.getValueType(TheVT)
8940 MachineMemOperand *MMO =
8941 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8942 MachineMemOperand::MOLoad, MemSize, MemSize);
8943 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8944 array_lengthof(Ops), DstTy, MMO);
8945 Chain = Value.getValue(1);
8946 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8947 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8950 MachineMemOperand *MMO =
8951 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8952 MachineMemOperand::MOStore, MemSize, MemSize);
8954 if (Opc != X86ISD::WIN_FTOL) {
8955 // Build the FP_TO_INT*_IN_MEM
8956 SDValue Ops[] = { Chain, Value, StackSlot };
8957 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8958 Ops, array_lengthof(Ops), DstTy,
8960 return std::make_pair(FIST, StackSlot);
8962 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8963 DAG.getVTList(MVT::Other, MVT::Glue),
8965 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8966 MVT::i32, ftol.getValue(1));
8967 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8968 MVT::i32, eax.getValue(2));
8969 SDValue Ops[] = { eax, edx };
8970 SDValue pair = IsReplace
8971 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8972 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8973 return std::make_pair(pair, SDValue());
8977 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8978 const X86Subtarget *Subtarget) {
8979 MVT VT = Op->getSimpleValueType(0);
8980 SDValue In = Op->getOperand(0);
8981 MVT InVT = In.getSimpleValueType();
8984 // Optimize vectors in AVX mode:
8987 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8988 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8989 // Concat upper and lower parts.
8992 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8993 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8994 // Concat upper and lower parts.
8997 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
8998 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8999 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9002 if (Subtarget->hasInt256())
9003 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9005 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9006 SDValue Undef = DAG.getUNDEF(InVT);
9007 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9008 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9009 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9011 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9012 VT.getVectorNumElements()/2);
9014 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9015 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9017 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9020 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9021 SelectionDAG &DAG) {
9022 MVT VT = Op->getSimpleValueType(0);
9023 SDValue In = Op->getOperand(0);
9024 MVT InVT = In.getSimpleValueType();
9026 unsigned int NumElts = VT.getVectorNumElements();
9027 if (NumElts != 8 && NumElts != 16)
9030 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9031 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9033 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9034 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9035 // Now we have only mask extension
9036 assert(InVT.getVectorElementType() == MVT::i1);
9037 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9038 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9039 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9040 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9041 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9042 MachinePointerInfo::getConstantPool(),
9043 false, false, false, Alignment);
9045 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9046 if (VT.is512BitVector())
9048 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9051 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9052 SelectionDAG &DAG) {
9053 if (Subtarget->hasFp256()) {
9054 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9062 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9063 SelectionDAG &DAG) {
9065 MVT VT = Op.getSimpleValueType();
9066 SDValue In = Op.getOperand(0);
9067 MVT SVT = In.getSimpleValueType();
9069 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9070 return LowerZERO_EXTEND_AVX512(Op, DAG);
9072 if (Subtarget->hasFp256()) {
9073 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9078 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9079 VT.getVectorNumElements() != SVT.getVectorNumElements());
9083 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9085 MVT VT = Op.getSimpleValueType();
9086 SDValue In = Op.getOperand(0);
9087 MVT InVT = In.getSimpleValueType();
9089 if (VT == MVT::i1) {
9090 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9091 "Invalid scalar TRUNCATE operation");
9092 if (InVT == MVT::i32)
9094 if (InVT.getSizeInBits() == 64)
9095 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9096 else if (InVT.getSizeInBits() < 32)
9097 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9098 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9100 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9101 "Invalid TRUNCATE operation");
9103 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9104 if (VT.getVectorElementType().getSizeInBits() >=8)
9105 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9107 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9108 unsigned NumElts = InVT.getVectorNumElements();
9109 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9110 if (InVT.getSizeInBits() < 512) {
9111 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9112 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9116 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9117 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9118 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9119 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9120 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9121 MachinePointerInfo::getConstantPool(),
9122 false, false, false, Alignment);
9123 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9124 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9125 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9128 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9129 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9130 if (Subtarget->hasInt256()) {
9131 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9132 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9133 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9135 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9136 DAG.getIntPtrConstant(0));
9139 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9140 DAG.getIntPtrConstant(0));
9141 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9142 DAG.getIntPtrConstant(2));
9143 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9144 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9145 static const int ShufMask[] = {0, 2, 4, 6};
9146 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9149 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9150 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9151 if (Subtarget->hasInt256()) {
9152 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9154 SmallVector<SDValue,32> pshufbMask;
9155 for (unsigned i = 0; i < 2; ++i) {
9156 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9157 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9158 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9159 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9160 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9161 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9162 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9163 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9164 for (unsigned j = 0; j < 8; ++j)
9165 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9167 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9168 &pshufbMask[0], 32);
9169 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9170 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9172 static const int ShufMask[] = {0, 2, -1, -1};
9173 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9175 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9176 DAG.getIntPtrConstant(0));
9177 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9180 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9181 DAG.getIntPtrConstant(0));
9183 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9184 DAG.getIntPtrConstant(4));
9186 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9187 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9190 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9191 -1, -1, -1, -1, -1, -1, -1, -1};
9193 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9194 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9195 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9197 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9198 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9200 // The MOVLHPS Mask:
9201 static const int ShufMask2[] = {0, 1, 4, 5};
9202 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9203 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9206 // Handle truncation of V256 to V128 using shuffles.
9207 if (!VT.is128BitVector() || !InVT.is256BitVector())
9210 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9212 unsigned NumElems = VT.getVectorNumElements();
9213 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9215 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9216 // Prepare truncation shuffle mask
9217 for (unsigned i = 0; i != NumElems; ++i)
9219 SDValue V = DAG.getVectorShuffle(NVT, DL,
9220 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9221 DAG.getUNDEF(NVT), &MaskVec[0]);
9222 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9223 DAG.getIntPtrConstant(0));
9226 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9227 SelectionDAG &DAG) const {
9228 MVT VT = Op.getSimpleValueType();
9229 if (VT.isVector()) {
9230 if (VT == MVT::v8i16)
9231 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9232 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9233 MVT::v8i32, Op.getOperand(0)));
9237 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9238 /*IsSigned=*/ true, /*IsReplace=*/ false);
9239 SDValue FIST = Vals.first, StackSlot = Vals.second;
9240 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9241 if (FIST.getNode() == 0) return Op;
9243 if (StackSlot.getNode())
9245 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9246 FIST, StackSlot, MachinePointerInfo(),
9247 false, false, false, 0);
9249 // The node is the result.
9253 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9254 SelectionDAG &DAG) const {
9255 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9256 /*IsSigned=*/ false, /*IsReplace=*/ false);
9257 SDValue FIST = Vals.first, StackSlot = Vals.second;
9258 assert(FIST.getNode() && "Unexpected failure");
9260 if (StackSlot.getNode())
9262 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9263 FIST, StackSlot, MachinePointerInfo(),
9264 false, false, false, 0);
9266 // The node is the result.
9270 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9272 MVT VT = Op.getSimpleValueType();
9273 SDValue In = Op.getOperand(0);
9274 MVT SVT = In.getSimpleValueType();
9276 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9278 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9279 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9280 In, DAG.getUNDEF(SVT)));
9283 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9284 LLVMContext *Context = DAG.getContext();
9286 MVT VT = Op.getSimpleValueType();
9288 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9289 if (VT.isVector()) {
9290 EltVT = VT.getVectorElementType();
9291 NumElts = VT.getVectorNumElements();
9294 if (EltVT == MVT::f64)
9295 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9296 APInt(64, ~(1ULL << 63))));
9298 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9299 APInt(32, ~(1U << 31))));
9300 C = ConstantVector::getSplat(NumElts, C);
9301 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9302 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9303 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9304 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9305 MachinePointerInfo::getConstantPool(),
9306 false, false, false, Alignment);
9307 if (VT.isVector()) {
9308 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9309 return DAG.getNode(ISD::BITCAST, dl, VT,
9310 DAG.getNode(ISD::AND, dl, ANDVT,
9311 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9313 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9315 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9318 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9319 LLVMContext *Context = DAG.getContext();
9321 MVT VT = Op.getSimpleValueType();
9323 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9324 if (VT.isVector()) {
9325 EltVT = VT.getVectorElementType();
9326 NumElts = VT.getVectorNumElements();
9329 if (EltVT == MVT::f64)
9330 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9331 APInt(64, 1ULL << 63)));
9333 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9334 APInt(32, 1U << 31)));
9335 C = ConstantVector::getSplat(NumElts, C);
9336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9337 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9338 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9339 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9340 MachinePointerInfo::getConstantPool(),
9341 false, false, false, Alignment);
9342 if (VT.isVector()) {
9343 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9344 return DAG.getNode(ISD::BITCAST, dl, VT,
9345 DAG.getNode(ISD::XOR, dl, XORVT,
9346 DAG.getNode(ISD::BITCAST, dl, XORVT,
9348 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9351 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9354 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9355 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9356 LLVMContext *Context = DAG.getContext();
9357 SDValue Op0 = Op.getOperand(0);
9358 SDValue Op1 = Op.getOperand(1);
9360 MVT VT = Op.getSimpleValueType();
9361 MVT SrcVT = Op1.getSimpleValueType();
9363 // If second operand is smaller, extend it first.
9364 if (SrcVT.bitsLT(VT)) {
9365 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9368 // And if it is bigger, shrink it first.
9369 if (SrcVT.bitsGT(VT)) {
9370 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9374 // At this point the operands and the result should have the same
9375 // type, and that won't be f80 since that is not custom lowered.
9377 // First get the sign bit of second operand.
9378 SmallVector<Constant*,4> CV;
9379 if (SrcVT == MVT::f64) {
9380 const fltSemantics &Sem = APFloat::IEEEdouble;
9381 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9382 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9384 const fltSemantics &Sem = APFloat::IEEEsingle;
9385 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9386 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9387 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9388 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9390 Constant *C = ConstantVector::get(CV);
9391 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9392 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9393 MachinePointerInfo::getConstantPool(),
9394 false, false, false, 16);
9395 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9397 // Shift sign bit right or left if the two operands have different types.
9398 if (SrcVT.bitsGT(VT)) {
9399 // Op0 is MVT::f32, Op1 is MVT::f64.
9400 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9401 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9402 DAG.getConstant(32, MVT::i32));
9403 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9404 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9405 DAG.getIntPtrConstant(0));
9408 // Clear first operand sign bit.
9410 if (VT == MVT::f64) {
9411 const fltSemantics &Sem = APFloat::IEEEdouble;
9412 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9413 APInt(64, ~(1ULL << 63)))));
9414 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9416 const fltSemantics &Sem = APFloat::IEEEsingle;
9417 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9418 APInt(32, ~(1U << 31)))));
9419 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9420 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9421 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9423 C = ConstantVector::get(CV);
9424 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9425 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9426 MachinePointerInfo::getConstantPool(),
9427 false, false, false, 16);
9428 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9430 // Or the value with the sign bit.
9431 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9434 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9435 SDValue N0 = Op.getOperand(0);
9437 MVT VT = Op.getSimpleValueType();
9439 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9440 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9441 DAG.getConstant(1, VT));
9442 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9445 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9447 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9448 SelectionDAG &DAG) {
9449 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9451 if (!Subtarget->hasSSE41())
9454 if (!Op->hasOneUse())
9457 SDNode *N = Op.getNode();
9460 SmallVector<SDValue, 8> Opnds;
9461 DenseMap<SDValue, unsigned> VecInMap;
9462 EVT VT = MVT::Other;
9464 // Recognize a special case where a vector is casted into wide integer to
9466 Opnds.push_back(N->getOperand(0));
9467 Opnds.push_back(N->getOperand(1));
9469 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9470 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9471 // BFS traverse all OR'd operands.
9472 if (I->getOpcode() == ISD::OR) {
9473 Opnds.push_back(I->getOperand(0));
9474 Opnds.push_back(I->getOperand(1));
9475 // Re-evaluate the number of nodes to be traversed.
9476 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9480 // Quit if a non-EXTRACT_VECTOR_ELT
9481 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9484 // Quit if without a constant index.
9485 SDValue Idx = I->getOperand(1);
9486 if (!isa<ConstantSDNode>(Idx))
9489 SDValue ExtractedFromVec = I->getOperand(0);
9490 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9491 if (M == VecInMap.end()) {
9492 VT = ExtractedFromVec.getValueType();
9493 // Quit if not 128/256-bit vector.
9494 if (!VT.is128BitVector() && !VT.is256BitVector())
9496 // Quit if not the same type.
9497 if (VecInMap.begin() != VecInMap.end() &&
9498 VT != VecInMap.begin()->first.getValueType())
9500 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9502 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9505 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9506 "Not extracted from 128-/256-bit vector.");
9508 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9509 SmallVector<SDValue, 8> VecIns;
9511 for (DenseMap<SDValue, unsigned>::const_iterator
9512 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9513 // Quit if not all elements are used.
9514 if (I->second != FullMask)
9516 VecIns.push_back(I->first);
9519 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9521 // Cast all vectors into TestVT for PTEST.
9522 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9523 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9525 // If more than one full vectors are evaluated, OR them first before PTEST.
9526 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9527 // Each iteration will OR 2 nodes and append the result until there is only
9528 // 1 node left, i.e. the final OR'd value of all vectors.
9529 SDValue LHS = VecIns[Slot];
9530 SDValue RHS = VecIns[Slot + 1];
9531 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9534 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9535 VecIns.back(), VecIns.back());
9538 /// Emit nodes that will be selected as "test Op0,Op0", or something
9540 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9541 SelectionDAG &DAG) const {
9544 if (Op.getValueType() == MVT::i1)
9545 // KORTEST instruction should be selected
9546 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9547 DAG.getConstant(0, Op.getValueType()));
9549 // CF and OF aren't always set the way we want. Determine which
9550 // of these we need.
9551 bool NeedCF = false;
9552 bool NeedOF = false;
9555 case X86::COND_A: case X86::COND_AE:
9556 case X86::COND_B: case X86::COND_BE:
9559 case X86::COND_G: case X86::COND_GE:
9560 case X86::COND_L: case X86::COND_LE:
9561 case X86::COND_O: case X86::COND_NO:
9565 // See if we can use the EFLAGS value from the operand instead of
9566 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9567 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9568 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9569 // Emit a CMP with 0, which is the TEST pattern.
9570 //if (Op.getValueType() == MVT::i1)
9571 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9572 // DAG.getConstant(0, MVT::i1));
9573 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9574 DAG.getConstant(0, Op.getValueType()));
9576 unsigned Opcode = 0;
9577 unsigned NumOperands = 0;
9579 // Truncate operations may prevent the merge of the SETCC instruction
9580 // and the arithmetic instruction before it. Attempt to truncate the operands
9581 // of the arithmetic instruction and use a reduced bit-width instruction.
9582 bool NeedTruncation = false;
9583 SDValue ArithOp = Op;
9584 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9585 SDValue Arith = Op->getOperand(0);
9586 // Both the trunc and the arithmetic op need to have one user each.
9587 if (Arith->hasOneUse())
9588 switch (Arith.getOpcode()) {
9595 NeedTruncation = true;
9601 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9602 // which may be the result of a CAST. We use the variable 'Op', which is the
9603 // non-casted variable when we check for possible users.
9604 switch (ArithOp.getOpcode()) {
9606 // Due to an isel shortcoming, be conservative if this add is likely to be
9607 // selected as part of a load-modify-store instruction. When the root node
9608 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9609 // uses of other nodes in the match, such as the ADD in this case. This
9610 // leads to the ADD being left around and reselected, with the result being
9611 // two adds in the output. Alas, even if none our users are stores, that
9612 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9613 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9614 // climbing the DAG back to the root, and it doesn't seem to be worth the
9616 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9617 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9618 if (UI->getOpcode() != ISD::CopyToReg &&
9619 UI->getOpcode() != ISD::SETCC &&
9620 UI->getOpcode() != ISD::STORE)
9623 if (ConstantSDNode *C =
9624 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9625 // An add of one will be selected as an INC.
9626 if (C->getAPIntValue() == 1) {
9627 Opcode = X86ISD::INC;
9632 // An add of negative one (subtract of one) will be selected as a DEC.
9633 if (C->getAPIntValue().isAllOnesValue()) {
9634 Opcode = X86ISD::DEC;
9640 // Otherwise use a regular EFLAGS-setting add.
9641 Opcode = X86ISD::ADD;
9645 // If the primary and result isn't used, don't bother using X86ISD::AND,
9646 // because a TEST instruction will be better.
9647 bool NonFlagUse = false;
9648 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9649 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9651 unsigned UOpNo = UI.getOperandNo();
9652 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9653 // Look pass truncate.
9654 UOpNo = User->use_begin().getOperandNo();
9655 User = *User->use_begin();
9658 if (User->getOpcode() != ISD::BRCOND &&
9659 User->getOpcode() != ISD::SETCC &&
9660 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9673 // Due to the ISEL shortcoming noted above, be conservative if this op is
9674 // likely to be selected as part of a load-modify-store instruction.
9675 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9676 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9677 if (UI->getOpcode() == ISD::STORE)
9680 // Otherwise use a regular EFLAGS-setting instruction.
9681 switch (ArithOp.getOpcode()) {
9682 default: llvm_unreachable("unexpected operator!");
9683 case ISD::SUB: Opcode = X86ISD::SUB; break;
9684 case ISD::XOR: Opcode = X86ISD::XOR; break;
9685 case ISD::AND: Opcode = X86ISD::AND; break;
9687 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9688 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9689 if (EFLAGS.getNode())
9692 Opcode = X86ISD::OR;
9706 return SDValue(Op.getNode(), 1);
9712 // If we found that truncation is beneficial, perform the truncation and
9714 if (NeedTruncation) {
9715 EVT VT = Op.getValueType();
9716 SDValue WideVal = Op->getOperand(0);
9717 EVT WideVT = WideVal.getValueType();
9718 unsigned ConvertedOp = 0;
9719 // Use a target machine opcode to prevent further DAGCombine
9720 // optimizations that may separate the arithmetic operations
9721 // from the setcc node.
9722 switch (WideVal.getOpcode()) {
9724 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9725 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9726 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9727 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9728 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9732 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9733 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9734 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9735 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9736 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9742 // Emit a CMP with 0, which is the TEST pattern.
9743 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9744 DAG.getConstant(0, Op.getValueType()));
9746 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9747 SmallVector<SDValue, 4> Ops;
9748 for (unsigned i = 0; i != NumOperands; ++i)
9749 Ops.push_back(Op.getOperand(i));
9751 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9752 DAG.ReplaceAllUsesWith(Op, New);
9753 return SDValue(New.getNode(), 1);
9756 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9758 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9759 SelectionDAG &DAG) const {
9761 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9762 if (C->getAPIntValue() == 0)
9763 return EmitTest(Op0, X86CC, DAG);
9765 if (Op0.getValueType() == MVT::i1)
9766 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9769 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9770 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9771 // Do the comparison at i32 if it's smaller. This avoids subregister
9772 // aliasing issues. Keep the smaller reference if we're optimizing for
9773 // size, however, as that'll allow better folding of memory operations.
9774 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9775 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9776 AttributeSet::FunctionIndex, Attribute::MinSize)) {
9778 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9779 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9780 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9782 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9783 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9784 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9786 return SDValue(Sub.getNode(), 1);
9788 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9791 /// Convert a comparison if required by the subtarget.
9792 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9793 SelectionDAG &DAG) const {
9794 // If the subtarget does not support the FUCOMI instruction, floating-point
9795 // comparisons have to be converted.
9796 if (Subtarget->hasCMov() ||
9797 Cmp.getOpcode() != X86ISD::CMP ||
9798 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9799 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9802 // The instruction selector will select an FUCOM instruction instead of
9803 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9804 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9805 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9807 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9808 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9809 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9810 DAG.getConstant(8, MVT::i8));
9811 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9812 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9815 static bool isAllOnes(SDValue V) {
9816 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9817 return C && C->isAllOnesValue();
9820 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9821 /// if it's possible.
9822 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9823 SDLoc dl, SelectionDAG &DAG) const {
9824 SDValue Op0 = And.getOperand(0);
9825 SDValue Op1 = And.getOperand(1);
9826 if (Op0.getOpcode() == ISD::TRUNCATE)
9827 Op0 = Op0.getOperand(0);
9828 if (Op1.getOpcode() == ISD::TRUNCATE)
9829 Op1 = Op1.getOperand(0);
9832 if (Op1.getOpcode() == ISD::SHL)
9833 std::swap(Op0, Op1);
9834 if (Op0.getOpcode() == ISD::SHL) {
9835 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9836 if (And00C->getZExtValue() == 1) {
9837 // If we looked past a truncate, check that it's only truncating away
9839 unsigned BitWidth = Op0.getValueSizeInBits();
9840 unsigned AndBitWidth = And.getValueSizeInBits();
9841 if (BitWidth > AndBitWidth) {
9843 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9844 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9848 RHS = Op0.getOperand(1);
9850 } else if (Op1.getOpcode() == ISD::Constant) {
9851 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9852 uint64_t AndRHSVal = AndRHS->getZExtValue();
9853 SDValue AndLHS = Op0;
9855 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9856 LHS = AndLHS.getOperand(0);
9857 RHS = AndLHS.getOperand(1);
9860 // Use BT if the immediate can't be encoded in a TEST instruction.
9861 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9863 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9867 if (LHS.getNode()) {
9868 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9869 // instruction. Since the shift amount is in-range-or-undefined, we know
9870 // that doing a bittest on the i32 value is ok. We extend to i32 because
9871 // the encoding for the i16 version is larger than the i32 version.
9872 // Also promote i16 to i32 for performance / code size reason.
9873 if (LHS.getValueType() == MVT::i8 ||
9874 LHS.getValueType() == MVT::i16)
9875 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9877 // If the operand types disagree, extend the shift amount to match. Since
9878 // BT ignores high bits (like shifts) we can use anyextend.
9879 if (LHS.getValueType() != RHS.getValueType())
9880 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9882 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9883 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9884 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9885 DAG.getConstant(Cond, MVT::i8), BT);
9891 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9893 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9898 // SSE Condition code mapping:
9907 switch (SetCCOpcode) {
9908 default: llvm_unreachable("Unexpected SETCC condition");
9910 case ISD::SETEQ: SSECC = 0; break;
9912 case ISD::SETGT: Swap = true; // Fallthrough
9914 case ISD::SETOLT: SSECC = 1; break;
9916 case ISD::SETGE: Swap = true; // Fallthrough
9918 case ISD::SETOLE: SSECC = 2; break;
9919 case ISD::SETUO: SSECC = 3; break;
9921 case ISD::SETNE: SSECC = 4; break;
9922 case ISD::SETULE: Swap = true; // Fallthrough
9923 case ISD::SETUGE: SSECC = 5; break;
9924 case ISD::SETULT: Swap = true; // Fallthrough
9925 case ISD::SETUGT: SSECC = 6; break;
9926 case ISD::SETO: SSECC = 7; break;
9928 case ISD::SETONE: SSECC = 8; break;
9931 std::swap(Op0, Op1);
9936 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9937 // ones, and then concatenate the result back.
9938 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9939 MVT VT = Op.getSimpleValueType();
9941 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9942 "Unsupported value type for operation");
9944 unsigned NumElems = VT.getVectorNumElements();
9946 SDValue CC = Op.getOperand(2);
9948 // Extract the LHS vectors
9949 SDValue LHS = Op.getOperand(0);
9950 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9951 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9953 // Extract the RHS vectors
9954 SDValue RHS = Op.getOperand(1);
9955 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9956 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9958 // Issue the operation on the smaller types and concatenate the result back
9959 MVT EltVT = VT.getVectorElementType();
9960 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9961 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9962 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9963 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9966 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
9967 const X86Subtarget *Subtarget) {
9968 SDValue Op0 = Op.getOperand(0);
9969 SDValue Op1 = Op.getOperand(1);
9970 SDValue CC = Op.getOperand(2);
9971 MVT VT = Op.getSimpleValueType();
9974 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9975 Op.getValueType().getScalarType() == MVT::i1 &&
9976 "Cannot set masked compare for this operation");
9978 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9980 bool Unsigned = false;
9983 switch (SetCCOpcode) {
9984 default: llvm_unreachable("Unexpected SETCC condition");
9985 case ISD::SETNE: SSECC = 4; break;
9986 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
9987 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
9988 case ISD::SETLT: Swap = true; //fall-through
9989 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
9990 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
9991 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
9992 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
9993 case ISD::SETULE: Unsigned = true; //fall-through
9994 case ISD::SETLE: SSECC = 2; break;
9998 std::swap(Op0, Op1);
10000 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10001 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10002 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10003 DAG.getConstant(SSECC, MVT::i8));
10006 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10007 /// operand \p Op1. If non-trivial (for example because it's not constant)
10008 /// return an empty value.
10009 static SDValue ChangeVSETULTtoVSETULE(SDValue Op1, SelectionDAG &DAG)
10011 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10015 MVT VT = Op1.getSimpleValueType();
10016 MVT EVT = VT.getVectorElementType();
10017 unsigned n = VT.getVectorNumElements();
10018 SmallVector<SDValue, 8> ULTOp1;
10020 for (unsigned i = 0; i < n; ++i) {
10021 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10022 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10025 // Avoid underflow.
10026 APInt Val = Elt->getAPIntValue();
10030 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10033 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Op1), VT, ULTOp1.data(),
10037 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10038 SelectionDAG &DAG) {
10039 SDValue Op0 = Op.getOperand(0);
10040 SDValue Op1 = Op.getOperand(1);
10041 SDValue CC = Op.getOperand(2);
10042 MVT VT = Op.getSimpleValueType();
10043 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10044 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10049 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10050 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10053 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10054 unsigned Opc = X86ISD::CMPP;
10055 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10056 assert(VT.getVectorNumElements() <= 16);
10057 Opc = X86ISD::CMPM;
10059 // In the two special cases we can't handle, emit two comparisons.
10062 unsigned CombineOpc;
10063 if (SetCCOpcode == ISD::SETUEQ) {
10064 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10066 assert(SetCCOpcode == ISD::SETONE);
10067 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10070 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10071 DAG.getConstant(CC0, MVT::i8));
10072 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10073 DAG.getConstant(CC1, MVT::i8));
10074 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10076 // Handle all other FP comparisons here.
10077 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10078 DAG.getConstant(SSECC, MVT::i8));
10081 // Break 256-bit integer vector compare into smaller ones.
10082 if (VT.is256BitVector() && !Subtarget->hasInt256())
10083 return Lower256IntVSETCC(Op, DAG);
10085 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10086 EVT OpVT = Op1.getValueType();
10087 if (Subtarget->hasAVX512()) {
10088 if (Op1.getValueType().is512BitVector() ||
10089 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10090 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10092 // In AVX-512 architecture setcc returns mask with i1 elements,
10093 // But there is no compare instruction for i8 and i16 elements.
10094 // We are not talking about 512-bit operands in this case, these
10095 // types are illegal.
10097 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10098 OpVT.getVectorElementType().getSizeInBits() >= 8))
10099 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10100 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10103 // We are handling one of the integer comparisons here. Since SSE only has
10104 // GT and EQ comparisons for integer, swapping operands and multiple
10105 // operations may be required for some comparisons.
10107 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10108 bool Subus = false;
10110 switch (SetCCOpcode) {
10111 default: llvm_unreachable("Unexpected SETCC condition");
10112 case ISD::SETNE: Invert = true;
10113 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10114 case ISD::SETLT: Swap = true;
10115 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10116 case ISD::SETGE: Swap = true;
10117 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10118 Invert = true; break;
10119 case ISD::SETULT: Swap = true;
10120 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10121 FlipSigns = true; break;
10122 case ISD::SETUGE: Swap = true;
10123 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10124 FlipSigns = true; Invert = true; break;
10127 // Special case: Use min/max operations for SETULE/SETUGE
10128 MVT VET = VT.getVectorElementType();
10130 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10131 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10134 switch (SetCCOpcode) {
10136 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10137 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10140 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10143 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10144 if (!MinMax && hasSubus) {
10145 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10147 // t = psubus Op0, Op1
10148 // pcmpeq t, <0..0>
10149 switch (SetCCOpcode) {
10151 case ISD::SETULT: {
10152 // If the comparison is against a constant we can turn this into a
10153 // setule. With psubus, setule does not require a swap. This is
10154 // beneficial because the constant in the register is no longer
10155 // destructed as the destination so it can be hoisted out of a loop.
10156 // Only do this pre-AVX since vpcmp* is no longer destructive.
10157 if (Subtarget->hasAVX())
10159 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(Op1, DAG);
10160 if (ULEOp1.getNode()) {
10162 Subus = true; Invert = false; Swap = false;
10166 // Psubus is better than flip-sign because it requires no inversion.
10167 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10168 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10172 Opc = X86ISD::SUBUS;
10178 std::swap(Op0, Op1);
10180 // Check that the operation in question is available (most are plain SSE2,
10181 // but PCMPGTQ and PCMPEQQ have different requirements).
10182 if (VT == MVT::v2i64) {
10183 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10184 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10186 // First cast everything to the right type.
10187 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10188 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10190 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10191 // bits of the inputs before performing those operations. The lower
10192 // compare is always unsigned.
10195 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10197 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10198 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10199 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10200 Sign, Zero, Sign, Zero);
10202 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10203 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10205 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10206 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10207 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10209 // Create masks for only the low parts/high parts of the 64 bit integers.
10210 static const int MaskHi[] = { 1, 1, 3, 3 };
10211 static const int MaskLo[] = { 0, 0, 2, 2 };
10212 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10213 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10214 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10216 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10217 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10220 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10222 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10225 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10226 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10227 // pcmpeqd + pshufd + pand.
10228 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10230 // First cast everything to the right type.
10231 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10232 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10235 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10237 // Make sure the lower and upper halves are both all-ones.
10238 static const int Mask[] = { 1, 0, 3, 2 };
10239 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10240 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10243 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10245 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10249 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10250 // bits of the inputs before performing those operations.
10252 EVT EltVT = VT.getVectorElementType();
10253 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10254 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10255 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10258 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10260 // If the logical-not of the result is required, perform that now.
10262 Result = DAG.getNOT(dl, Result, VT);
10265 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10268 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10269 getZeroVector(VT, Subtarget, DAG, dl));
10274 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10276 MVT VT = Op.getSimpleValueType();
10278 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10280 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10281 && "SetCC type must be 8-bit or 1-bit integer");
10282 SDValue Op0 = Op.getOperand(0);
10283 SDValue Op1 = Op.getOperand(1);
10285 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10287 // Optimize to BT if possible.
10288 // Lower (X & (1 << N)) == 0 to BT(X, N).
10289 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10290 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10291 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10292 Op1.getOpcode() == ISD::Constant &&
10293 cast<ConstantSDNode>(Op1)->isNullValue() &&
10294 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10295 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10296 if (NewSetCC.getNode())
10300 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10302 if (Op1.getOpcode() == ISD::Constant &&
10303 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10304 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10305 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10307 // If the input is a setcc, then reuse the input setcc or use a new one with
10308 // the inverted condition.
10309 if (Op0.getOpcode() == X86ISD::SETCC) {
10310 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10311 bool Invert = (CC == ISD::SETNE) ^
10312 cast<ConstantSDNode>(Op1)->isNullValue();
10316 CCode = X86::GetOppositeBranchCondition(CCode);
10317 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10318 DAG.getConstant(CCode, MVT::i8),
10319 Op0.getOperand(1));
10321 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10325 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10326 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10327 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10329 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10330 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10333 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10334 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10335 if (X86CC == X86::COND_INVALID)
10338 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10339 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10340 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10341 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10343 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10347 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10348 static bool isX86LogicalCmp(SDValue Op) {
10349 unsigned Opc = Op.getNode()->getOpcode();
10350 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10351 Opc == X86ISD::SAHF)
10353 if (Op.getResNo() == 1 &&
10354 (Opc == X86ISD::ADD ||
10355 Opc == X86ISD::SUB ||
10356 Opc == X86ISD::ADC ||
10357 Opc == X86ISD::SBB ||
10358 Opc == X86ISD::SMUL ||
10359 Opc == X86ISD::UMUL ||
10360 Opc == X86ISD::INC ||
10361 Opc == X86ISD::DEC ||
10362 Opc == X86ISD::OR ||
10363 Opc == X86ISD::XOR ||
10364 Opc == X86ISD::AND))
10367 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10373 static bool isZero(SDValue V) {
10374 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10375 return C && C->isNullValue();
10378 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10379 if (V.getOpcode() != ISD::TRUNCATE)
10382 SDValue VOp0 = V.getOperand(0);
10383 unsigned InBits = VOp0.getValueSizeInBits();
10384 unsigned Bits = V.getValueSizeInBits();
10385 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10388 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10389 bool addTest = true;
10390 SDValue Cond = Op.getOperand(0);
10391 SDValue Op1 = Op.getOperand(1);
10392 SDValue Op2 = Op.getOperand(2);
10394 EVT VT = Op1.getValueType();
10397 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10398 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10399 // sequence later on.
10400 if (Cond.getOpcode() == ISD::SETCC &&
10401 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10402 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10403 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10404 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10405 int SSECC = translateX86FSETCC(
10406 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10409 if (Subtarget->hasAVX512()) {
10410 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10411 DAG.getConstant(SSECC, MVT::i8));
10412 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10414 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10415 DAG.getConstant(SSECC, MVT::i8));
10416 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10417 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10418 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10422 if (Cond.getOpcode() == ISD::SETCC) {
10423 SDValue NewCond = LowerSETCC(Cond, DAG);
10424 if (NewCond.getNode())
10428 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10429 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10430 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10431 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10432 if (Cond.getOpcode() == X86ISD::SETCC &&
10433 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10434 isZero(Cond.getOperand(1).getOperand(1))) {
10435 SDValue Cmp = Cond.getOperand(1);
10437 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10439 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10440 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10441 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10443 SDValue CmpOp0 = Cmp.getOperand(0);
10444 // Apply further optimizations for special cases
10445 // (select (x != 0), -1, 0) -> neg & sbb
10446 // (select (x == 0), 0, -1) -> neg & sbb
10447 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10448 if (YC->isNullValue() &&
10449 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10450 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10451 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10452 DAG.getConstant(0, CmpOp0.getValueType()),
10454 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10455 DAG.getConstant(X86::COND_B, MVT::i8),
10456 SDValue(Neg.getNode(), 1));
10460 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10461 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10462 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10464 SDValue Res = // Res = 0 or -1.
10465 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10466 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10468 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10469 Res = DAG.getNOT(DL, Res, Res.getValueType());
10471 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10472 if (N2C == 0 || !N2C->isNullValue())
10473 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10478 // Look past (and (setcc_carry (cmp ...)), 1).
10479 if (Cond.getOpcode() == ISD::AND &&
10480 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10481 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10482 if (C && C->getAPIntValue() == 1)
10483 Cond = Cond.getOperand(0);
10486 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10487 // setting operand in place of the X86ISD::SETCC.
10488 unsigned CondOpcode = Cond.getOpcode();
10489 if (CondOpcode == X86ISD::SETCC ||
10490 CondOpcode == X86ISD::SETCC_CARRY) {
10491 CC = Cond.getOperand(0);
10493 SDValue Cmp = Cond.getOperand(1);
10494 unsigned Opc = Cmp.getOpcode();
10495 MVT VT = Op.getSimpleValueType();
10497 bool IllegalFPCMov = false;
10498 if (VT.isFloatingPoint() && !VT.isVector() &&
10499 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10500 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10502 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10503 Opc == X86ISD::BT) { // FIXME
10507 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10508 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10509 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10510 Cond.getOperand(0).getValueType() != MVT::i8)) {
10511 SDValue LHS = Cond.getOperand(0);
10512 SDValue RHS = Cond.getOperand(1);
10513 unsigned X86Opcode;
10516 switch (CondOpcode) {
10517 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10518 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10519 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10520 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10521 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10522 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10523 default: llvm_unreachable("unexpected overflowing operator");
10525 if (CondOpcode == ISD::UMULO)
10526 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10529 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10531 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10533 if (CondOpcode == ISD::UMULO)
10534 Cond = X86Op.getValue(2);
10536 Cond = X86Op.getValue(1);
10538 CC = DAG.getConstant(X86Cond, MVT::i8);
10543 // Look pass the truncate if the high bits are known zero.
10544 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10545 Cond = Cond.getOperand(0);
10547 // We know the result of AND is compared against zero. Try to match
10549 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10550 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10551 if (NewSetCC.getNode()) {
10552 CC = NewSetCC.getOperand(0);
10553 Cond = NewSetCC.getOperand(1);
10560 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10561 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10564 // a < b ? -1 : 0 -> RES = ~setcc_carry
10565 // a < b ? 0 : -1 -> RES = setcc_carry
10566 // a >= b ? -1 : 0 -> RES = setcc_carry
10567 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10568 if (Cond.getOpcode() == X86ISD::SUB) {
10569 Cond = ConvertCmpIfNecessary(Cond, DAG);
10570 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10572 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10573 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10574 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10575 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10576 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10577 return DAG.getNOT(DL, Res, Res.getValueType());
10582 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10583 // widen the cmov and push the truncate through. This avoids introducing a new
10584 // branch during isel and doesn't add any extensions.
10585 if (Op.getValueType() == MVT::i8 &&
10586 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10587 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10588 if (T1.getValueType() == T2.getValueType() &&
10589 // Blacklist CopyFromReg to avoid partial register stalls.
10590 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10591 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10592 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10593 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10597 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10598 // condition is true.
10599 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10600 SDValue Ops[] = { Op2, Op1, CC, Cond };
10601 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10604 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10605 MVT VT = Op->getSimpleValueType(0);
10606 SDValue In = Op->getOperand(0);
10607 MVT InVT = In.getSimpleValueType();
10610 unsigned int NumElts = VT.getVectorNumElements();
10611 if (NumElts != 8 && NumElts != 16)
10614 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10615 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10617 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10618 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10620 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10621 Constant *C = ConstantInt::get(*DAG.getContext(),
10622 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10624 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10625 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10626 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10627 MachinePointerInfo::getConstantPool(),
10628 false, false, false, Alignment);
10629 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10630 if (VT.is512BitVector())
10632 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10635 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10636 SelectionDAG &DAG) {
10637 MVT VT = Op->getSimpleValueType(0);
10638 SDValue In = Op->getOperand(0);
10639 MVT InVT = In.getSimpleValueType();
10642 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10643 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10645 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10646 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10647 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10650 if (Subtarget->hasInt256())
10651 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10653 // Optimize vectors in AVX mode
10654 // Sign extend v8i16 to v8i32 and
10657 // Divide input vector into two parts
10658 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10659 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10660 // concat the vectors to original VT
10662 unsigned NumElems = InVT.getVectorNumElements();
10663 SDValue Undef = DAG.getUNDEF(InVT);
10665 SmallVector<int,8> ShufMask1(NumElems, -1);
10666 for (unsigned i = 0; i != NumElems/2; ++i)
10669 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10671 SmallVector<int,8> ShufMask2(NumElems, -1);
10672 for (unsigned i = 0; i != NumElems/2; ++i)
10673 ShufMask2[i] = i + NumElems/2;
10675 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10677 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10678 VT.getVectorNumElements()/2);
10680 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10681 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10683 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10686 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10687 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10688 // from the AND / OR.
10689 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10690 Opc = Op.getOpcode();
10691 if (Opc != ISD::OR && Opc != ISD::AND)
10693 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10694 Op.getOperand(0).hasOneUse() &&
10695 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10696 Op.getOperand(1).hasOneUse());
10699 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10700 // 1 and that the SETCC node has a single use.
10701 static bool isXor1OfSetCC(SDValue Op) {
10702 if (Op.getOpcode() != ISD::XOR)
10704 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10705 if (N1C && N1C->getAPIntValue() == 1) {
10706 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10707 Op.getOperand(0).hasOneUse();
10712 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10713 bool addTest = true;
10714 SDValue Chain = Op.getOperand(0);
10715 SDValue Cond = Op.getOperand(1);
10716 SDValue Dest = Op.getOperand(2);
10719 bool Inverted = false;
10721 if (Cond.getOpcode() == ISD::SETCC) {
10722 // Check for setcc([su]{add,sub,mul}o == 0).
10723 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10724 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10725 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10726 Cond.getOperand(0).getResNo() == 1 &&
10727 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10728 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10729 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10730 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10731 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10732 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10734 Cond = Cond.getOperand(0);
10736 SDValue NewCond = LowerSETCC(Cond, DAG);
10737 if (NewCond.getNode())
10742 // FIXME: LowerXALUO doesn't handle these!!
10743 else if (Cond.getOpcode() == X86ISD::ADD ||
10744 Cond.getOpcode() == X86ISD::SUB ||
10745 Cond.getOpcode() == X86ISD::SMUL ||
10746 Cond.getOpcode() == X86ISD::UMUL)
10747 Cond = LowerXALUO(Cond, DAG);
10750 // Look pass (and (setcc_carry (cmp ...)), 1).
10751 if (Cond.getOpcode() == ISD::AND &&
10752 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10753 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10754 if (C && C->getAPIntValue() == 1)
10755 Cond = Cond.getOperand(0);
10758 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10759 // setting operand in place of the X86ISD::SETCC.
10760 unsigned CondOpcode = Cond.getOpcode();
10761 if (CondOpcode == X86ISD::SETCC ||
10762 CondOpcode == X86ISD::SETCC_CARRY) {
10763 CC = Cond.getOperand(0);
10765 SDValue Cmp = Cond.getOperand(1);
10766 unsigned Opc = Cmp.getOpcode();
10767 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10768 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10772 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10776 // These can only come from an arithmetic instruction with overflow,
10777 // e.g. SADDO, UADDO.
10778 Cond = Cond.getNode()->getOperand(1);
10784 CondOpcode = Cond.getOpcode();
10785 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10786 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10787 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10788 Cond.getOperand(0).getValueType() != MVT::i8)) {
10789 SDValue LHS = Cond.getOperand(0);
10790 SDValue RHS = Cond.getOperand(1);
10791 unsigned X86Opcode;
10794 // Keep this in sync with LowerXALUO, otherwise we might create redundant
10795 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10797 switch (CondOpcode) {
10798 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10800 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10802 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10805 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10806 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10808 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10810 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10813 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10814 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10815 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10816 default: llvm_unreachable("unexpected overflowing operator");
10819 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10820 if (CondOpcode == ISD::UMULO)
10821 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10824 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10826 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10828 if (CondOpcode == ISD::UMULO)
10829 Cond = X86Op.getValue(2);
10831 Cond = X86Op.getValue(1);
10833 CC = DAG.getConstant(X86Cond, MVT::i8);
10837 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10838 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10839 if (CondOpc == ISD::OR) {
10840 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10841 // two branches instead of an explicit OR instruction with a
10843 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10844 isX86LogicalCmp(Cmp)) {
10845 CC = Cond.getOperand(0).getOperand(0);
10846 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10847 Chain, Dest, CC, Cmp);
10848 CC = Cond.getOperand(1).getOperand(0);
10852 } else { // ISD::AND
10853 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10854 // two branches instead of an explicit AND instruction with a
10855 // separate test. However, we only do this if this block doesn't
10856 // have a fall-through edge, because this requires an explicit
10857 // jmp when the condition is false.
10858 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10859 isX86LogicalCmp(Cmp) &&
10860 Op.getNode()->hasOneUse()) {
10861 X86::CondCode CCode =
10862 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10863 CCode = X86::GetOppositeBranchCondition(CCode);
10864 CC = DAG.getConstant(CCode, MVT::i8);
10865 SDNode *User = *Op.getNode()->use_begin();
10866 // Look for an unconditional branch following this conditional branch.
10867 // We need this because we need to reverse the successors in order
10868 // to implement FCMP_OEQ.
10869 if (User->getOpcode() == ISD::BR) {
10870 SDValue FalseBB = User->getOperand(1);
10872 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10873 assert(NewBR == User);
10877 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10878 Chain, Dest, CC, Cmp);
10879 X86::CondCode CCode =
10880 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10881 CCode = X86::GetOppositeBranchCondition(CCode);
10882 CC = DAG.getConstant(CCode, MVT::i8);
10888 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10889 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10890 // It should be transformed during dag combiner except when the condition
10891 // is set by a arithmetics with overflow node.
10892 X86::CondCode CCode =
10893 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10894 CCode = X86::GetOppositeBranchCondition(CCode);
10895 CC = DAG.getConstant(CCode, MVT::i8);
10896 Cond = Cond.getOperand(0).getOperand(1);
10898 } else if (Cond.getOpcode() == ISD::SETCC &&
10899 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10900 // For FCMP_OEQ, we can emit
10901 // two branches instead of an explicit AND instruction with a
10902 // separate test. However, we only do this if this block doesn't
10903 // have a fall-through edge, because this requires an explicit
10904 // jmp when the condition is false.
10905 if (Op.getNode()->hasOneUse()) {
10906 SDNode *User = *Op.getNode()->use_begin();
10907 // Look for an unconditional branch following this conditional branch.
10908 // We need this because we need to reverse the successors in order
10909 // to implement FCMP_OEQ.
10910 if (User->getOpcode() == ISD::BR) {
10911 SDValue FalseBB = User->getOperand(1);
10913 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10914 assert(NewBR == User);
10918 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10919 Cond.getOperand(0), Cond.getOperand(1));
10920 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10921 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10922 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10923 Chain, Dest, CC, Cmp);
10924 CC = DAG.getConstant(X86::COND_P, MVT::i8);
10929 } else if (Cond.getOpcode() == ISD::SETCC &&
10930 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10931 // For FCMP_UNE, we can emit
10932 // two branches instead of an explicit AND instruction with a
10933 // separate test. However, we only do this if this block doesn't
10934 // have a fall-through edge, because this requires an explicit
10935 // jmp when the condition is false.
10936 if (Op.getNode()->hasOneUse()) {
10937 SDNode *User = *Op.getNode()->use_begin();
10938 // Look for an unconditional branch following this conditional branch.
10939 // We need this because we need to reverse the successors in order
10940 // to implement FCMP_UNE.
10941 if (User->getOpcode() == ISD::BR) {
10942 SDValue FalseBB = User->getOperand(1);
10944 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10945 assert(NewBR == User);
10948 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10949 Cond.getOperand(0), Cond.getOperand(1));
10950 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10951 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10952 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10953 Chain, Dest, CC, Cmp);
10954 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10964 // Look pass the truncate if the high bits are known zero.
10965 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10966 Cond = Cond.getOperand(0);
10968 // We know the result of AND is compared against zero. Try to match
10970 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10971 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10972 if (NewSetCC.getNode()) {
10973 CC = NewSetCC.getOperand(0);
10974 Cond = NewSetCC.getOperand(1);
10981 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10982 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10984 Cond = ConvertCmpIfNecessary(Cond, DAG);
10985 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10986 Chain, Dest, CC, Cond);
10989 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10990 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10991 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10992 // that the guard pages used by the OS virtual memory manager are allocated in
10993 // correct sequence.
10995 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10996 SelectionDAG &DAG) const {
10997 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10998 getTargetMachine().Options.EnableSegmentedStacks) &&
10999 "This should be used only on Windows targets or when segmented stacks "
11001 assert(!Subtarget->isTargetMacho() && "Not implemented");
11005 SDValue Chain = Op.getOperand(0);
11006 SDValue Size = Op.getOperand(1);
11007 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11008 EVT VT = Op.getNode()->getValueType(0);
11010 bool Is64Bit = Subtarget->is64Bit();
11011 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11013 if (getTargetMachine().Options.EnableSegmentedStacks) {
11014 MachineFunction &MF = DAG.getMachineFunction();
11015 MachineRegisterInfo &MRI = MF.getRegInfo();
11018 // The 64 bit implementation of segmented stacks needs to clobber both r10
11019 // r11. This makes it impossible to use it along with nested parameters.
11020 const Function *F = MF.getFunction();
11022 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11024 if (I->hasNestAttr())
11025 report_fatal_error("Cannot use segmented stacks with functions that "
11026 "have nested arguments.");
11029 const TargetRegisterClass *AddrRegClass =
11030 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11031 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11032 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11033 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11034 DAG.getRegister(Vreg, SPTy));
11035 SDValue Ops1[2] = { Value, Chain };
11036 return DAG.getMergeValues(Ops1, 2, dl);
11039 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11041 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11042 Flag = Chain.getValue(1);
11043 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11045 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11047 const X86RegisterInfo *RegInfo =
11048 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11049 unsigned SPReg = RegInfo->getStackRegister();
11050 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11051 Chain = SP.getValue(1);
11054 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11055 DAG.getConstant(-(uint64_t)Align, VT));
11056 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11059 SDValue Ops1[2] = { SP, Chain };
11060 return DAG.getMergeValues(Ops1, 2, dl);
11064 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11065 MachineFunction &MF = DAG.getMachineFunction();
11066 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11068 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11071 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11072 // vastart just stores the address of the VarArgsFrameIndex slot into the
11073 // memory location argument.
11074 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11076 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11077 MachinePointerInfo(SV), false, false, 0);
11081 // gp_offset (0 - 6 * 8)
11082 // fp_offset (48 - 48 + 8 * 16)
11083 // overflow_arg_area (point to parameters coming in memory).
11085 SmallVector<SDValue, 8> MemOps;
11086 SDValue FIN = Op.getOperand(1);
11088 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11089 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11091 FIN, MachinePointerInfo(SV), false, false, 0);
11092 MemOps.push_back(Store);
11095 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11096 FIN, DAG.getIntPtrConstant(4));
11097 Store = DAG.getStore(Op.getOperand(0), DL,
11098 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11100 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11101 MemOps.push_back(Store);
11103 // Store ptr to overflow_arg_area
11104 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11105 FIN, DAG.getIntPtrConstant(4));
11106 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11108 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11109 MachinePointerInfo(SV, 8),
11111 MemOps.push_back(Store);
11113 // Store ptr to reg_save_area.
11114 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11115 FIN, DAG.getIntPtrConstant(8));
11116 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11118 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11119 MachinePointerInfo(SV, 16), false, false, 0);
11120 MemOps.push_back(Store);
11121 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11122 &MemOps[0], MemOps.size());
11125 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11126 assert(Subtarget->is64Bit() &&
11127 "LowerVAARG only handles 64-bit va_arg!");
11128 assert((Subtarget->isTargetLinux() ||
11129 Subtarget->isTargetDarwin()) &&
11130 "Unhandled target in LowerVAARG");
11131 assert(Op.getNode()->getNumOperands() == 4);
11132 SDValue Chain = Op.getOperand(0);
11133 SDValue SrcPtr = Op.getOperand(1);
11134 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11135 unsigned Align = Op.getConstantOperandVal(3);
11138 EVT ArgVT = Op.getNode()->getValueType(0);
11139 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11140 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11143 // Decide which area this value should be read from.
11144 // TODO: Implement the AMD64 ABI in its entirety. This simple
11145 // selection mechanism works only for the basic types.
11146 if (ArgVT == MVT::f80) {
11147 llvm_unreachable("va_arg for f80 not yet implemented");
11148 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11149 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11150 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11151 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11153 llvm_unreachable("Unhandled argument type in LowerVAARG");
11156 if (ArgMode == 2) {
11157 // Sanity Check: Make sure using fp_offset makes sense.
11158 assert(!getTargetMachine().Options.UseSoftFloat &&
11159 !(DAG.getMachineFunction()
11160 .getFunction()->getAttributes()
11161 .hasAttribute(AttributeSet::FunctionIndex,
11162 Attribute::NoImplicitFloat)) &&
11163 Subtarget->hasSSE1());
11166 // Insert VAARG_64 node into the DAG
11167 // VAARG_64 returns two values: Variable Argument Address, Chain
11168 SmallVector<SDValue, 11> InstOps;
11169 InstOps.push_back(Chain);
11170 InstOps.push_back(SrcPtr);
11171 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11172 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11173 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11174 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11175 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11176 VTs, &InstOps[0], InstOps.size(),
11178 MachinePointerInfo(SV),
11180 /*Volatile=*/false,
11182 /*WriteMem=*/true);
11183 Chain = VAARG.getValue(1);
11185 // Load the next argument and return it
11186 return DAG.getLoad(ArgVT, dl,
11189 MachinePointerInfo(),
11190 false, false, false, 0);
11193 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11194 SelectionDAG &DAG) {
11195 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11196 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11197 SDValue Chain = Op.getOperand(0);
11198 SDValue DstPtr = Op.getOperand(1);
11199 SDValue SrcPtr = Op.getOperand(2);
11200 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11201 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11204 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11205 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11207 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11210 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11211 // amount is a constant. Takes immediate version of shift as input.
11212 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11213 SDValue SrcOp, uint64_t ShiftAmt,
11214 SelectionDAG &DAG) {
11215 MVT ElementType = VT.getVectorElementType();
11217 // Check for ShiftAmt >= element width
11218 if (ShiftAmt >= ElementType.getSizeInBits()) {
11219 if (Opc == X86ISD::VSRAI)
11220 ShiftAmt = ElementType.getSizeInBits() - 1;
11222 return DAG.getConstant(0, VT);
11225 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11226 && "Unknown target vector shift-by-constant node");
11228 // Fold this packed vector shift into a build vector if SrcOp is a
11229 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11230 if (VT == SrcOp.getSimpleValueType() &&
11231 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11232 SmallVector<SDValue, 8> Elts;
11233 unsigned NumElts = SrcOp->getNumOperands();
11234 ConstantSDNode *ND;
11237 default: llvm_unreachable(0);
11238 case X86ISD::VSHLI:
11239 for (unsigned i=0; i!=NumElts; ++i) {
11240 SDValue CurrentOp = SrcOp->getOperand(i);
11241 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11242 Elts.push_back(CurrentOp);
11245 ND = cast<ConstantSDNode>(CurrentOp);
11246 const APInt &C = ND->getAPIntValue();
11247 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11250 case X86ISD::VSRLI:
11251 for (unsigned i=0; i!=NumElts; ++i) {
11252 SDValue CurrentOp = SrcOp->getOperand(i);
11253 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11254 Elts.push_back(CurrentOp);
11257 ND = cast<ConstantSDNode>(CurrentOp);
11258 const APInt &C = ND->getAPIntValue();
11259 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11262 case X86ISD::VSRAI:
11263 for (unsigned i=0; i!=NumElts; ++i) {
11264 SDValue CurrentOp = SrcOp->getOperand(i);
11265 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11266 Elts.push_back(CurrentOp);
11269 ND = cast<ConstantSDNode>(CurrentOp);
11270 const APInt &C = ND->getAPIntValue();
11271 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11276 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11279 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11282 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11283 // may or may not be a constant. Takes immediate version of shift as input.
11284 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11285 SDValue SrcOp, SDValue ShAmt,
11286 SelectionDAG &DAG) {
11287 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11289 // Catch shift-by-constant.
11290 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11291 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11292 CShAmt->getZExtValue(), DAG);
11294 // Change opcode to non-immediate version
11296 default: llvm_unreachable("Unknown target vector shift node");
11297 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11298 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11299 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11302 // Need to build a vector containing shift amount
11303 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11306 ShOps[1] = DAG.getConstant(0, MVT::i32);
11307 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11308 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11310 // The return type has to be a 128-bit type with the same element
11311 // type as the input type.
11312 MVT EltVT = VT.getVectorElementType();
11313 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11315 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11316 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11319 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11321 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11323 default: return SDValue(); // Don't custom lower most intrinsics.
11324 // Comparison intrinsics.
11325 case Intrinsic::x86_sse_comieq_ss:
11326 case Intrinsic::x86_sse_comilt_ss:
11327 case Intrinsic::x86_sse_comile_ss:
11328 case Intrinsic::x86_sse_comigt_ss:
11329 case Intrinsic::x86_sse_comige_ss:
11330 case Intrinsic::x86_sse_comineq_ss:
11331 case Intrinsic::x86_sse_ucomieq_ss:
11332 case Intrinsic::x86_sse_ucomilt_ss:
11333 case Intrinsic::x86_sse_ucomile_ss:
11334 case Intrinsic::x86_sse_ucomigt_ss:
11335 case Intrinsic::x86_sse_ucomige_ss:
11336 case Intrinsic::x86_sse_ucomineq_ss:
11337 case Intrinsic::x86_sse2_comieq_sd:
11338 case Intrinsic::x86_sse2_comilt_sd:
11339 case Intrinsic::x86_sse2_comile_sd:
11340 case Intrinsic::x86_sse2_comigt_sd:
11341 case Intrinsic::x86_sse2_comige_sd:
11342 case Intrinsic::x86_sse2_comineq_sd:
11343 case Intrinsic::x86_sse2_ucomieq_sd:
11344 case Intrinsic::x86_sse2_ucomilt_sd:
11345 case Intrinsic::x86_sse2_ucomile_sd:
11346 case Intrinsic::x86_sse2_ucomigt_sd:
11347 case Intrinsic::x86_sse2_ucomige_sd:
11348 case Intrinsic::x86_sse2_ucomineq_sd: {
11352 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11353 case Intrinsic::x86_sse_comieq_ss:
11354 case Intrinsic::x86_sse2_comieq_sd:
11355 Opc = X86ISD::COMI;
11358 case Intrinsic::x86_sse_comilt_ss:
11359 case Intrinsic::x86_sse2_comilt_sd:
11360 Opc = X86ISD::COMI;
11363 case Intrinsic::x86_sse_comile_ss:
11364 case Intrinsic::x86_sse2_comile_sd:
11365 Opc = X86ISD::COMI;
11368 case Intrinsic::x86_sse_comigt_ss:
11369 case Intrinsic::x86_sse2_comigt_sd:
11370 Opc = X86ISD::COMI;
11373 case Intrinsic::x86_sse_comige_ss:
11374 case Intrinsic::x86_sse2_comige_sd:
11375 Opc = X86ISD::COMI;
11378 case Intrinsic::x86_sse_comineq_ss:
11379 case Intrinsic::x86_sse2_comineq_sd:
11380 Opc = X86ISD::COMI;
11383 case Intrinsic::x86_sse_ucomieq_ss:
11384 case Intrinsic::x86_sse2_ucomieq_sd:
11385 Opc = X86ISD::UCOMI;
11388 case Intrinsic::x86_sse_ucomilt_ss:
11389 case Intrinsic::x86_sse2_ucomilt_sd:
11390 Opc = X86ISD::UCOMI;
11393 case Intrinsic::x86_sse_ucomile_ss:
11394 case Intrinsic::x86_sse2_ucomile_sd:
11395 Opc = X86ISD::UCOMI;
11398 case Intrinsic::x86_sse_ucomigt_ss:
11399 case Intrinsic::x86_sse2_ucomigt_sd:
11400 Opc = X86ISD::UCOMI;
11403 case Intrinsic::x86_sse_ucomige_ss:
11404 case Intrinsic::x86_sse2_ucomige_sd:
11405 Opc = X86ISD::UCOMI;
11408 case Intrinsic::x86_sse_ucomineq_ss:
11409 case Intrinsic::x86_sse2_ucomineq_sd:
11410 Opc = X86ISD::UCOMI;
11415 SDValue LHS = Op.getOperand(1);
11416 SDValue RHS = Op.getOperand(2);
11417 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11418 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11419 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11420 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11421 DAG.getConstant(X86CC, MVT::i8), Cond);
11422 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11425 // Arithmetic intrinsics.
11426 case Intrinsic::x86_sse2_pmulu_dq:
11427 case Intrinsic::x86_avx2_pmulu_dq:
11428 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11429 Op.getOperand(1), Op.getOperand(2));
11431 // SSE2/AVX2 sub with unsigned saturation intrinsics
11432 case Intrinsic::x86_sse2_psubus_b:
11433 case Intrinsic::x86_sse2_psubus_w:
11434 case Intrinsic::x86_avx2_psubus_b:
11435 case Intrinsic::x86_avx2_psubus_w:
11436 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11437 Op.getOperand(1), Op.getOperand(2));
11439 // SSE3/AVX horizontal add/sub intrinsics
11440 case Intrinsic::x86_sse3_hadd_ps:
11441 case Intrinsic::x86_sse3_hadd_pd:
11442 case Intrinsic::x86_avx_hadd_ps_256:
11443 case Intrinsic::x86_avx_hadd_pd_256:
11444 case Intrinsic::x86_sse3_hsub_ps:
11445 case Intrinsic::x86_sse3_hsub_pd:
11446 case Intrinsic::x86_avx_hsub_ps_256:
11447 case Intrinsic::x86_avx_hsub_pd_256:
11448 case Intrinsic::x86_ssse3_phadd_w_128:
11449 case Intrinsic::x86_ssse3_phadd_d_128:
11450 case Intrinsic::x86_avx2_phadd_w:
11451 case Intrinsic::x86_avx2_phadd_d:
11452 case Intrinsic::x86_ssse3_phsub_w_128:
11453 case Intrinsic::x86_ssse3_phsub_d_128:
11454 case Intrinsic::x86_avx2_phsub_w:
11455 case Intrinsic::x86_avx2_phsub_d: {
11458 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11459 case Intrinsic::x86_sse3_hadd_ps:
11460 case Intrinsic::x86_sse3_hadd_pd:
11461 case Intrinsic::x86_avx_hadd_ps_256:
11462 case Intrinsic::x86_avx_hadd_pd_256:
11463 Opcode = X86ISD::FHADD;
11465 case Intrinsic::x86_sse3_hsub_ps:
11466 case Intrinsic::x86_sse3_hsub_pd:
11467 case Intrinsic::x86_avx_hsub_ps_256:
11468 case Intrinsic::x86_avx_hsub_pd_256:
11469 Opcode = X86ISD::FHSUB;
11471 case Intrinsic::x86_ssse3_phadd_w_128:
11472 case Intrinsic::x86_ssse3_phadd_d_128:
11473 case Intrinsic::x86_avx2_phadd_w:
11474 case Intrinsic::x86_avx2_phadd_d:
11475 Opcode = X86ISD::HADD;
11477 case Intrinsic::x86_ssse3_phsub_w_128:
11478 case Intrinsic::x86_ssse3_phsub_d_128:
11479 case Intrinsic::x86_avx2_phsub_w:
11480 case Intrinsic::x86_avx2_phsub_d:
11481 Opcode = X86ISD::HSUB;
11484 return DAG.getNode(Opcode, dl, Op.getValueType(),
11485 Op.getOperand(1), Op.getOperand(2));
11488 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11489 case Intrinsic::x86_sse2_pmaxu_b:
11490 case Intrinsic::x86_sse41_pmaxuw:
11491 case Intrinsic::x86_sse41_pmaxud:
11492 case Intrinsic::x86_avx2_pmaxu_b:
11493 case Intrinsic::x86_avx2_pmaxu_w:
11494 case Intrinsic::x86_avx2_pmaxu_d:
11495 case Intrinsic::x86_sse2_pminu_b:
11496 case Intrinsic::x86_sse41_pminuw:
11497 case Intrinsic::x86_sse41_pminud:
11498 case Intrinsic::x86_avx2_pminu_b:
11499 case Intrinsic::x86_avx2_pminu_w:
11500 case Intrinsic::x86_avx2_pminu_d:
11501 case Intrinsic::x86_sse41_pmaxsb:
11502 case Intrinsic::x86_sse2_pmaxs_w:
11503 case Intrinsic::x86_sse41_pmaxsd:
11504 case Intrinsic::x86_avx2_pmaxs_b:
11505 case Intrinsic::x86_avx2_pmaxs_w:
11506 case Intrinsic::x86_avx2_pmaxs_d:
11507 case Intrinsic::x86_sse41_pminsb:
11508 case Intrinsic::x86_sse2_pmins_w:
11509 case Intrinsic::x86_sse41_pminsd:
11510 case Intrinsic::x86_avx2_pmins_b:
11511 case Intrinsic::x86_avx2_pmins_w:
11512 case Intrinsic::x86_avx2_pmins_d: {
11515 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11516 case Intrinsic::x86_sse2_pmaxu_b:
11517 case Intrinsic::x86_sse41_pmaxuw:
11518 case Intrinsic::x86_sse41_pmaxud:
11519 case Intrinsic::x86_avx2_pmaxu_b:
11520 case Intrinsic::x86_avx2_pmaxu_w:
11521 case Intrinsic::x86_avx2_pmaxu_d:
11522 Opcode = X86ISD::UMAX;
11524 case Intrinsic::x86_sse2_pminu_b:
11525 case Intrinsic::x86_sse41_pminuw:
11526 case Intrinsic::x86_sse41_pminud:
11527 case Intrinsic::x86_avx2_pminu_b:
11528 case Intrinsic::x86_avx2_pminu_w:
11529 case Intrinsic::x86_avx2_pminu_d:
11530 Opcode = X86ISD::UMIN;
11532 case Intrinsic::x86_sse41_pmaxsb:
11533 case Intrinsic::x86_sse2_pmaxs_w:
11534 case Intrinsic::x86_sse41_pmaxsd:
11535 case Intrinsic::x86_avx2_pmaxs_b:
11536 case Intrinsic::x86_avx2_pmaxs_w:
11537 case Intrinsic::x86_avx2_pmaxs_d:
11538 Opcode = X86ISD::SMAX;
11540 case Intrinsic::x86_sse41_pminsb:
11541 case Intrinsic::x86_sse2_pmins_w:
11542 case Intrinsic::x86_sse41_pminsd:
11543 case Intrinsic::x86_avx2_pmins_b:
11544 case Intrinsic::x86_avx2_pmins_w:
11545 case Intrinsic::x86_avx2_pmins_d:
11546 Opcode = X86ISD::SMIN;
11549 return DAG.getNode(Opcode, dl, Op.getValueType(),
11550 Op.getOperand(1), Op.getOperand(2));
11553 // SSE/SSE2/AVX floating point max/min intrinsics.
11554 case Intrinsic::x86_sse_max_ps:
11555 case Intrinsic::x86_sse2_max_pd:
11556 case Intrinsic::x86_avx_max_ps_256:
11557 case Intrinsic::x86_avx_max_pd_256:
11558 case Intrinsic::x86_sse_min_ps:
11559 case Intrinsic::x86_sse2_min_pd:
11560 case Intrinsic::x86_avx_min_ps_256:
11561 case Intrinsic::x86_avx_min_pd_256: {
11564 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11565 case Intrinsic::x86_sse_max_ps:
11566 case Intrinsic::x86_sse2_max_pd:
11567 case Intrinsic::x86_avx_max_ps_256:
11568 case Intrinsic::x86_avx_max_pd_256:
11569 Opcode = X86ISD::FMAX;
11571 case Intrinsic::x86_sse_min_ps:
11572 case Intrinsic::x86_sse2_min_pd:
11573 case Intrinsic::x86_avx_min_ps_256:
11574 case Intrinsic::x86_avx_min_pd_256:
11575 Opcode = X86ISD::FMIN;
11578 return DAG.getNode(Opcode, dl, Op.getValueType(),
11579 Op.getOperand(1), Op.getOperand(2));
11582 // AVX2 variable shift intrinsics
11583 case Intrinsic::x86_avx2_psllv_d:
11584 case Intrinsic::x86_avx2_psllv_q:
11585 case Intrinsic::x86_avx2_psllv_d_256:
11586 case Intrinsic::x86_avx2_psllv_q_256:
11587 case Intrinsic::x86_avx2_psrlv_d:
11588 case Intrinsic::x86_avx2_psrlv_q:
11589 case Intrinsic::x86_avx2_psrlv_d_256:
11590 case Intrinsic::x86_avx2_psrlv_q_256:
11591 case Intrinsic::x86_avx2_psrav_d:
11592 case Intrinsic::x86_avx2_psrav_d_256: {
11595 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11596 case Intrinsic::x86_avx2_psllv_d:
11597 case Intrinsic::x86_avx2_psllv_q:
11598 case Intrinsic::x86_avx2_psllv_d_256:
11599 case Intrinsic::x86_avx2_psllv_q_256:
11602 case Intrinsic::x86_avx2_psrlv_d:
11603 case Intrinsic::x86_avx2_psrlv_q:
11604 case Intrinsic::x86_avx2_psrlv_d_256:
11605 case Intrinsic::x86_avx2_psrlv_q_256:
11608 case Intrinsic::x86_avx2_psrav_d:
11609 case Intrinsic::x86_avx2_psrav_d_256:
11613 return DAG.getNode(Opcode, dl, Op.getValueType(),
11614 Op.getOperand(1), Op.getOperand(2));
11617 case Intrinsic::x86_ssse3_pshuf_b_128:
11618 case Intrinsic::x86_avx2_pshuf_b:
11619 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11620 Op.getOperand(1), Op.getOperand(2));
11622 case Intrinsic::x86_ssse3_psign_b_128:
11623 case Intrinsic::x86_ssse3_psign_w_128:
11624 case Intrinsic::x86_ssse3_psign_d_128:
11625 case Intrinsic::x86_avx2_psign_b:
11626 case Intrinsic::x86_avx2_psign_w:
11627 case Intrinsic::x86_avx2_psign_d:
11628 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11629 Op.getOperand(1), Op.getOperand(2));
11631 case Intrinsic::x86_sse41_insertps:
11632 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11633 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11635 case Intrinsic::x86_avx_vperm2f128_ps_256:
11636 case Intrinsic::x86_avx_vperm2f128_pd_256:
11637 case Intrinsic::x86_avx_vperm2f128_si_256:
11638 case Intrinsic::x86_avx2_vperm2i128:
11639 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11640 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11642 case Intrinsic::x86_avx2_permd:
11643 case Intrinsic::x86_avx2_permps:
11644 // Operands intentionally swapped. Mask is last operand to intrinsic,
11645 // but second operand for node/instruction.
11646 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11647 Op.getOperand(2), Op.getOperand(1));
11649 case Intrinsic::x86_sse_sqrt_ps:
11650 case Intrinsic::x86_sse2_sqrt_pd:
11651 case Intrinsic::x86_avx_sqrt_ps_256:
11652 case Intrinsic::x86_avx_sqrt_pd_256:
11653 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11655 // ptest and testp intrinsics. The intrinsic these come from are designed to
11656 // return an integer value, not just an instruction so lower it to the ptest
11657 // or testp pattern and a setcc for the result.
11658 case Intrinsic::x86_sse41_ptestz:
11659 case Intrinsic::x86_sse41_ptestc:
11660 case Intrinsic::x86_sse41_ptestnzc:
11661 case Intrinsic::x86_avx_ptestz_256:
11662 case Intrinsic::x86_avx_ptestc_256:
11663 case Intrinsic::x86_avx_ptestnzc_256:
11664 case Intrinsic::x86_avx_vtestz_ps:
11665 case Intrinsic::x86_avx_vtestc_ps:
11666 case Intrinsic::x86_avx_vtestnzc_ps:
11667 case Intrinsic::x86_avx_vtestz_pd:
11668 case Intrinsic::x86_avx_vtestc_pd:
11669 case Intrinsic::x86_avx_vtestnzc_pd:
11670 case Intrinsic::x86_avx_vtestz_ps_256:
11671 case Intrinsic::x86_avx_vtestc_ps_256:
11672 case Intrinsic::x86_avx_vtestnzc_ps_256:
11673 case Intrinsic::x86_avx_vtestz_pd_256:
11674 case Intrinsic::x86_avx_vtestc_pd_256:
11675 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11676 bool IsTestPacked = false;
11679 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11680 case Intrinsic::x86_avx_vtestz_ps:
11681 case Intrinsic::x86_avx_vtestz_pd:
11682 case Intrinsic::x86_avx_vtestz_ps_256:
11683 case Intrinsic::x86_avx_vtestz_pd_256:
11684 IsTestPacked = true; // Fallthrough
11685 case Intrinsic::x86_sse41_ptestz:
11686 case Intrinsic::x86_avx_ptestz_256:
11688 X86CC = X86::COND_E;
11690 case Intrinsic::x86_avx_vtestc_ps:
11691 case Intrinsic::x86_avx_vtestc_pd:
11692 case Intrinsic::x86_avx_vtestc_ps_256:
11693 case Intrinsic::x86_avx_vtestc_pd_256:
11694 IsTestPacked = true; // Fallthrough
11695 case Intrinsic::x86_sse41_ptestc:
11696 case Intrinsic::x86_avx_ptestc_256:
11698 X86CC = X86::COND_B;
11700 case Intrinsic::x86_avx_vtestnzc_ps:
11701 case Intrinsic::x86_avx_vtestnzc_pd:
11702 case Intrinsic::x86_avx_vtestnzc_ps_256:
11703 case Intrinsic::x86_avx_vtestnzc_pd_256:
11704 IsTestPacked = true; // Fallthrough
11705 case Intrinsic::x86_sse41_ptestnzc:
11706 case Intrinsic::x86_avx_ptestnzc_256:
11708 X86CC = X86::COND_A;
11712 SDValue LHS = Op.getOperand(1);
11713 SDValue RHS = Op.getOperand(2);
11714 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11715 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11716 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11717 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11718 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11720 case Intrinsic::x86_avx512_kortestz_w:
11721 case Intrinsic::x86_avx512_kortestc_w: {
11722 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11723 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11724 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11725 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11726 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11727 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11728 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11731 // SSE/AVX shift intrinsics
11732 case Intrinsic::x86_sse2_psll_w:
11733 case Intrinsic::x86_sse2_psll_d:
11734 case Intrinsic::x86_sse2_psll_q:
11735 case Intrinsic::x86_avx2_psll_w:
11736 case Intrinsic::x86_avx2_psll_d:
11737 case Intrinsic::x86_avx2_psll_q:
11738 case Intrinsic::x86_sse2_psrl_w:
11739 case Intrinsic::x86_sse2_psrl_d:
11740 case Intrinsic::x86_sse2_psrl_q:
11741 case Intrinsic::x86_avx2_psrl_w:
11742 case Intrinsic::x86_avx2_psrl_d:
11743 case Intrinsic::x86_avx2_psrl_q:
11744 case Intrinsic::x86_sse2_psra_w:
11745 case Intrinsic::x86_sse2_psra_d:
11746 case Intrinsic::x86_avx2_psra_w:
11747 case Intrinsic::x86_avx2_psra_d: {
11750 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11751 case Intrinsic::x86_sse2_psll_w:
11752 case Intrinsic::x86_sse2_psll_d:
11753 case Intrinsic::x86_sse2_psll_q:
11754 case Intrinsic::x86_avx2_psll_w:
11755 case Intrinsic::x86_avx2_psll_d:
11756 case Intrinsic::x86_avx2_psll_q:
11757 Opcode = X86ISD::VSHL;
11759 case Intrinsic::x86_sse2_psrl_w:
11760 case Intrinsic::x86_sse2_psrl_d:
11761 case Intrinsic::x86_sse2_psrl_q:
11762 case Intrinsic::x86_avx2_psrl_w:
11763 case Intrinsic::x86_avx2_psrl_d:
11764 case Intrinsic::x86_avx2_psrl_q:
11765 Opcode = X86ISD::VSRL;
11767 case Intrinsic::x86_sse2_psra_w:
11768 case Intrinsic::x86_sse2_psra_d:
11769 case Intrinsic::x86_avx2_psra_w:
11770 case Intrinsic::x86_avx2_psra_d:
11771 Opcode = X86ISD::VSRA;
11774 return DAG.getNode(Opcode, dl, Op.getValueType(),
11775 Op.getOperand(1), Op.getOperand(2));
11778 // SSE/AVX immediate shift intrinsics
11779 case Intrinsic::x86_sse2_pslli_w:
11780 case Intrinsic::x86_sse2_pslli_d:
11781 case Intrinsic::x86_sse2_pslli_q:
11782 case Intrinsic::x86_avx2_pslli_w:
11783 case Intrinsic::x86_avx2_pslli_d:
11784 case Intrinsic::x86_avx2_pslli_q:
11785 case Intrinsic::x86_sse2_psrli_w:
11786 case Intrinsic::x86_sse2_psrli_d:
11787 case Intrinsic::x86_sse2_psrli_q:
11788 case Intrinsic::x86_avx2_psrli_w:
11789 case Intrinsic::x86_avx2_psrli_d:
11790 case Intrinsic::x86_avx2_psrli_q:
11791 case Intrinsic::x86_sse2_psrai_w:
11792 case Intrinsic::x86_sse2_psrai_d:
11793 case Intrinsic::x86_avx2_psrai_w:
11794 case Intrinsic::x86_avx2_psrai_d: {
11797 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11798 case Intrinsic::x86_sse2_pslli_w:
11799 case Intrinsic::x86_sse2_pslli_d:
11800 case Intrinsic::x86_sse2_pslli_q:
11801 case Intrinsic::x86_avx2_pslli_w:
11802 case Intrinsic::x86_avx2_pslli_d:
11803 case Intrinsic::x86_avx2_pslli_q:
11804 Opcode = X86ISD::VSHLI;
11806 case Intrinsic::x86_sse2_psrli_w:
11807 case Intrinsic::x86_sse2_psrli_d:
11808 case Intrinsic::x86_sse2_psrli_q:
11809 case Intrinsic::x86_avx2_psrli_w:
11810 case Intrinsic::x86_avx2_psrli_d:
11811 case Intrinsic::x86_avx2_psrli_q:
11812 Opcode = X86ISD::VSRLI;
11814 case Intrinsic::x86_sse2_psrai_w:
11815 case Intrinsic::x86_sse2_psrai_d:
11816 case Intrinsic::x86_avx2_psrai_w:
11817 case Intrinsic::x86_avx2_psrai_d:
11818 Opcode = X86ISD::VSRAI;
11821 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11822 Op.getOperand(1), Op.getOperand(2), DAG);
11825 case Intrinsic::x86_sse42_pcmpistria128:
11826 case Intrinsic::x86_sse42_pcmpestria128:
11827 case Intrinsic::x86_sse42_pcmpistric128:
11828 case Intrinsic::x86_sse42_pcmpestric128:
11829 case Intrinsic::x86_sse42_pcmpistrio128:
11830 case Intrinsic::x86_sse42_pcmpestrio128:
11831 case Intrinsic::x86_sse42_pcmpistris128:
11832 case Intrinsic::x86_sse42_pcmpestris128:
11833 case Intrinsic::x86_sse42_pcmpistriz128:
11834 case Intrinsic::x86_sse42_pcmpestriz128: {
11838 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11839 case Intrinsic::x86_sse42_pcmpistria128:
11840 Opcode = X86ISD::PCMPISTRI;
11841 X86CC = X86::COND_A;
11843 case Intrinsic::x86_sse42_pcmpestria128:
11844 Opcode = X86ISD::PCMPESTRI;
11845 X86CC = X86::COND_A;
11847 case Intrinsic::x86_sse42_pcmpistric128:
11848 Opcode = X86ISD::PCMPISTRI;
11849 X86CC = X86::COND_B;
11851 case Intrinsic::x86_sse42_pcmpestric128:
11852 Opcode = X86ISD::PCMPESTRI;
11853 X86CC = X86::COND_B;
11855 case Intrinsic::x86_sse42_pcmpistrio128:
11856 Opcode = X86ISD::PCMPISTRI;
11857 X86CC = X86::COND_O;
11859 case Intrinsic::x86_sse42_pcmpestrio128:
11860 Opcode = X86ISD::PCMPESTRI;
11861 X86CC = X86::COND_O;
11863 case Intrinsic::x86_sse42_pcmpistris128:
11864 Opcode = X86ISD::PCMPISTRI;
11865 X86CC = X86::COND_S;
11867 case Intrinsic::x86_sse42_pcmpestris128:
11868 Opcode = X86ISD::PCMPESTRI;
11869 X86CC = X86::COND_S;
11871 case Intrinsic::x86_sse42_pcmpistriz128:
11872 Opcode = X86ISD::PCMPISTRI;
11873 X86CC = X86::COND_E;
11875 case Intrinsic::x86_sse42_pcmpestriz128:
11876 Opcode = X86ISD::PCMPESTRI;
11877 X86CC = X86::COND_E;
11880 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11881 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11882 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11883 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11884 DAG.getConstant(X86CC, MVT::i8),
11885 SDValue(PCMP.getNode(), 1));
11886 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11889 case Intrinsic::x86_sse42_pcmpistri128:
11890 case Intrinsic::x86_sse42_pcmpestri128: {
11892 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11893 Opcode = X86ISD::PCMPISTRI;
11895 Opcode = X86ISD::PCMPESTRI;
11897 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11898 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11899 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11901 case Intrinsic::x86_fma_vfmadd_ps:
11902 case Intrinsic::x86_fma_vfmadd_pd:
11903 case Intrinsic::x86_fma_vfmsub_ps:
11904 case Intrinsic::x86_fma_vfmsub_pd:
11905 case Intrinsic::x86_fma_vfnmadd_ps:
11906 case Intrinsic::x86_fma_vfnmadd_pd:
11907 case Intrinsic::x86_fma_vfnmsub_ps:
11908 case Intrinsic::x86_fma_vfnmsub_pd:
11909 case Intrinsic::x86_fma_vfmaddsub_ps:
11910 case Intrinsic::x86_fma_vfmaddsub_pd:
11911 case Intrinsic::x86_fma_vfmsubadd_ps:
11912 case Intrinsic::x86_fma_vfmsubadd_pd:
11913 case Intrinsic::x86_fma_vfmadd_ps_256:
11914 case Intrinsic::x86_fma_vfmadd_pd_256:
11915 case Intrinsic::x86_fma_vfmsub_ps_256:
11916 case Intrinsic::x86_fma_vfmsub_pd_256:
11917 case Intrinsic::x86_fma_vfnmadd_ps_256:
11918 case Intrinsic::x86_fma_vfnmadd_pd_256:
11919 case Intrinsic::x86_fma_vfnmsub_ps_256:
11920 case Intrinsic::x86_fma_vfnmsub_pd_256:
11921 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11922 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11923 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11924 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11925 case Intrinsic::x86_fma_vfmadd_ps_512:
11926 case Intrinsic::x86_fma_vfmadd_pd_512:
11927 case Intrinsic::x86_fma_vfmsub_ps_512:
11928 case Intrinsic::x86_fma_vfmsub_pd_512:
11929 case Intrinsic::x86_fma_vfnmadd_ps_512:
11930 case Intrinsic::x86_fma_vfnmadd_pd_512:
11931 case Intrinsic::x86_fma_vfnmsub_ps_512:
11932 case Intrinsic::x86_fma_vfnmsub_pd_512:
11933 case Intrinsic::x86_fma_vfmaddsub_ps_512:
11934 case Intrinsic::x86_fma_vfmaddsub_pd_512:
11935 case Intrinsic::x86_fma_vfmsubadd_ps_512:
11936 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11939 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11940 case Intrinsic::x86_fma_vfmadd_ps:
11941 case Intrinsic::x86_fma_vfmadd_pd:
11942 case Intrinsic::x86_fma_vfmadd_ps_256:
11943 case Intrinsic::x86_fma_vfmadd_pd_256:
11944 case Intrinsic::x86_fma_vfmadd_ps_512:
11945 case Intrinsic::x86_fma_vfmadd_pd_512:
11946 Opc = X86ISD::FMADD;
11948 case Intrinsic::x86_fma_vfmsub_ps:
11949 case Intrinsic::x86_fma_vfmsub_pd:
11950 case Intrinsic::x86_fma_vfmsub_ps_256:
11951 case Intrinsic::x86_fma_vfmsub_pd_256:
11952 case Intrinsic::x86_fma_vfmsub_ps_512:
11953 case Intrinsic::x86_fma_vfmsub_pd_512:
11954 Opc = X86ISD::FMSUB;
11956 case Intrinsic::x86_fma_vfnmadd_ps:
11957 case Intrinsic::x86_fma_vfnmadd_pd:
11958 case Intrinsic::x86_fma_vfnmadd_ps_256:
11959 case Intrinsic::x86_fma_vfnmadd_pd_256:
11960 case Intrinsic::x86_fma_vfnmadd_ps_512:
11961 case Intrinsic::x86_fma_vfnmadd_pd_512:
11962 Opc = X86ISD::FNMADD;
11964 case Intrinsic::x86_fma_vfnmsub_ps:
11965 case Intrinsic::x86_fma_vfnmsub_pd:
11966 case Intrinsic::x86_fma_vfnmsub_ps_256:
11967 case Intrinsic::x86_fma_vfnmsub_pd_256:
11968 case Intrinsic::x86_fma_vfnmsub_ps_512:
11969 case Intrinsic::x86_fma_vfnmsub_pd_512:
11970 Opc = X86ISD::FNMSUB;
11972 case Intrinsic::x86_fma_vfmaddsub_ps:
11973 case Intrinsic::x86_fma_vfmaddsub_pd:
11974 case Intrinsic::x86_fma_vfmaddsub_ps_256:
11975 case Intrinsic::x86_fma_vfmaddsub_pd_256:
11976 case Intrinsic::x86_fma_vfmaddsub_ps_512:
11977 case Intrinsic::x86_fma_vfmaddsub_pd_512:
11978 Opc = X86ISD::FMADDSUB;
11980 case Intrinsic::x86_fma_vfmsubadd_ps:
11981 case Intrinsic::x86_fma_vfmsubadd_pd:
11982 case Intrinsic::x86_fma_vfmsubadd_ps_256:
11983 case Intrinsic::x86_fma_vfmsubadd_pd_256:
11984 case Intrinsic::x86_fma_vfmsubadd_ps_512:
11985 case Intrinsic::x86_fma_vfmsubadd_pd_512:
11986 Opc = X86ISD::FMSUBADD;
11990 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11991 Op.getOperand(2), Op.getOperand(3));
11996 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11997 SDValue Base, SDValue Index,
11998 SDValue ScaleOp, SDValue Chain,
11999 const X86Subtarget * Subtarget) {
12001 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12002 assert(C && "Invalid scale type");
12003 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12004 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12005 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12006 Index.getSimpleValueType().getVectorNumElements());
12007 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12008 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12009 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12010 SDValue Segment = DAG.getRegister(0, MVT::i32);
12011 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12012 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12013 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12014 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12017 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12018 SDValue Src, SDValue Mask, SDValue Base,
12019 SDValue Index, SDValue ScaleOp, SDValue Chain,
12020 const X86Subtarget * Subtarget) {
12022 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12023 assert(C && "Invalid scale type");
12024 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12025 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12026 Index.getSimpleValueType().getVectorNumElements());
12027 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12028 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12029 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12030 SDValue Segment = DAG.getRegister(0, MVT::i32);
12031 if (Src.getOpcode() == ISD::UNDEF)
12032 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12033 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12034 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12035 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12036 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12039 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12040 SDValue Src, SDValue Base, SDValue Index,
12041 SDValue ScaleOp, SDValue Chain) {
12043 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12044 assert(C && "Invalid scale type");
12045 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12046 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12047 SDValue Segment = DAG.getRegister(0, MVT::i32);
12048 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12049 Index.getSimpleValueType().getVectorNumElements());
12050 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12051 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12052 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12053 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12054 return SDValue(Res, 1);
12057 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12058 SDValue Src, SDValue Mask, SDValue Base,
12059 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12061 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12062 assert(C && "Invalid scale type");
12063 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12064 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12065 SDValue Segment = DAG.getRegister(0, MVT::i32);
12066 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12067 Index.getSimpleValueType().getVectorNumElements());
12068 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12069 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12070 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12071 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12072 return SDValue(Res, 1);
12075 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12076 SelectionDAG &DAG) {
12078 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12080 default: return SDValue(); // Don't custom lower most intrinsics.
12082 // RDRAND/RDSEED intrinsics.
12083 case Intrinsic::x86_rdrand_16:
12084 case Intrinsic::x86_rdrand_32:
12085 case Intrinsic::x86_rdrand_64:
12086 case Intrinsic::x86_rdseed_16:
12087 case Intrinsic::x86_rdseed_32:
12088 case Intrinsic::x86_rdseed_64: {
12089 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12090 IntNo == Intrinsic::x86_rdseed_32 ||
12091 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12093 // Emit the node with the right value type.
12094 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12095 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12097 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12098 // Otherwise return the value from Rand, which is always 0, casted to i32.
12099 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12100 DAG.getConstant(1, Op->getValueType(1)),
12101 DAG.getConstant(X86::COND_B, MVT::i32),
12102 SDValue(Result.getNode(), 1) };
12103 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12104 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12105 Ops, array_lengthof(Ops));
12107 // Return { result, isValid, chain }.
12108 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12109 SDValue(Result.getNode(), 2));
12111 //int_gather(index, base, scale);
12112 case Intrinsic::x86_avx512_gather_qpd_512:
12113 case Intrinsic::x86_avx512_gather_qps_512:
12114 case Intrinsic::x86_avx512_gather_dpd_512:
12115 case Intrinsic::x86_avx512_gather_qpi_512:
12116 case Intrinsic::x86_avx512_gather_qpq_512:
12117 case Intrinsic::x86_avx512_gather_dpq_512:
12118 case Intrinsic::x86_avx512_gather_dps_512:
12119 case Intrinsic::x86_avx512_gather_dpi_512: {
12122 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12123 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12124 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12125 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12126 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12127 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12128 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12129 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12130 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12132 SDValue Chain = Op.getOperand(0);
12133 SDValue Index = Op.getOperand(2);
12134 SDValue Base = Op.getOperand(3);
12135 SDValue Scale = Op.getOperand(4);
12136 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12138 //int_gather_mask(v1, mask, index, base, scale);
12139 case Intrinsic::x86_avx512_gather_qps_mask_512:
12140 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12141 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12142 case Intrinsic::x86_avx512_gather_dps_mask_512:
12143 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12144 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12145 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12146 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12149 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12150 case Intrinsic::x86_avx512_gather_qps_mask_512:
12151 Opc = X86::VGATHERQPSZrm; break;
12152 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12153 Opc = X86::VGATHERQPDZrm; break;
12154 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12155 Opc = X86::VGATHERDPDZrm; break;
12156 case Intrinsic::x86_avx512_gather_dps_mask_512:
12157 Opc = X86::VGATHERDPSZrm; break;
12158 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12159 Opc = X86::VPGATHERQDZrm; break;
12160 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12161 Opc = X86::VPGATHERQQZrm; break;
12162 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12163 Opc = X86::VPGATHERDDZrm; break;
12164 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12165 Opc = X86::VPGATHERDQZrm; break;
12167 SDValue Chain = Op.getOperand(0);
12168 SDValue Src = Op.getOperand(2);
12169 SDValue Mask = Op.getOperand(3);
12170 SDValue Index = Op.getOperand(4);
12171 SDValue Base = Op.getOperand(5);
12172 SDValue Scale = Op.getOperand(6);
12173 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12176 //int_scatter(base, index, v1, scale);
12177 case Intrinsic::x86_avx512_scatter_qpd_512:
12178 case Intrinsic::x86_avx512_scatter_qps_512:
12179 case Intrinsic::x86_avx512_scatter_dpd_512:
12180 case Intrinsic::x86_avx512_scatter_qpi_512:
12181 case Intrinsic::x86_avx512_scatter_qpq_512:
12182 case Intrinsic::x86_avx512_scatter_dpq_512:
12183 case Intrinsic::x86_avx512_scatter_dps_512:
12184 case Intrinsic::x86_avx512_scatter_dpi_512: {
12187 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12188 case Intrinsic::x86_avx512_scatter_qpd_512:
12189 Opc = X86::VSCATTERQPDZmr; break;
12190 case Intrinsic::x86_avx512_scatter_qps_512:
12191 Opc = X86::VSCATTERQPSZmr; break;
12192 case Intrinsic::x86_avx512_scatter_dpd_512:
12193 Opc = X86::VSCATTERDPDZmr; break;
12194 case Intrinsic::x86_avx512_scatter_dps_512:
12195 Opc = X86::VSCATTERDPSZmr; break;
12196 case Intrinsic::x86_avx512_scatter_qpi_512:
12197 Opc = X86::VPSCATTERQDZmr; break;
12198 case Intrinsic::x86_avx512_scatter_qpq_512:
12199 Opc = X86::VPSCATTERQQZmr; break;
12200 case Intrinsic::x86_avx512_scatter_dpq_512:
12201 Opc = X86::VPSCATTERDQZmr; break;
12202 case Intrinsic::x86_avx512_scatter_dpi_512:
12203 Opc = X86::VPSCATTERDDZmr; break;
12205 SDValue Chain = Op.getOperand(0);
12206 SDValue Base = Op.getOperand(2);
12207 SDValue Index = Op.getOperand(3);
12208 SDValue Src = Op.getOperand(4);
12209 SDValue Scale = Op.getOperand(5);
12210 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12212 //int_scatter_mask(base, mask, index, v1, scale);
12213 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12214 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12215 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12216 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12217 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12218 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12219 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12220 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12223 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12224 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12225 Opc = X86::VSCATTERQPDZmr; break;
12226 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12227 Opc = X86::VSCATTERQPSZmr; break;
12228 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12229 Opc = X86::VSCATTERDPDZmr; break;
12230 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12231 Opc = X86::VSCATTERDPSZmr; break;
12232 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12233 Opc = X86::VPSCATTERQDZmr; break;
12234 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12235 Opc = X86::VPSCATTERQQZmr; break;
12236 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12237 Opc = X86::VPSCATTERDQZmr; break;
12238 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12239 Opc = X86::VPSCATTERDDZmr; break;
12241 SDValue Chain = Op.getOperand(0);
12242 SDValue Base = Op.getOperand(2);
12243 SDValue Mask = Op.getOperand(3);
12244 SDValue Index = Op.getOperand(4);
12245 SDValue Src = Op.getOperand(5);
12246 SDValue Scale = Op.getOperand(6);
12247 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12249 // XTEST intrinsics.
12250 case Intrinsic::x86_xtest: {
12251 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12252 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12253 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12254 DAG.getConstant(X86::COND_NE, MVT::i8),
12256 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12257 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12258 Ret, SDValue(InTrans.getNode(), 1));
12263 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12264 SelectionDAG &DAG) const {
12265 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12266 MFI->setReturnAddressIsTaken(true);
12268 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12271 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12273 EVT PtrVT = getPointerTy();
12276 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12277 const X86RegisterInfo *RegInfo =
12278 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12279 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12280 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12281 DAG.getNode(ISD::ADD, dl, PtrVT,
12282 FrameAddr, Offset),
12283 MachinePointerInfo(), false, false, false, 0);
12286 // Just load the return address.
12287 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12288 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12289 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12292 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12293 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12294 MFI->setFrameAddressIsTaken(true);
12296 EVT VT = Op.getValueType();
12297 SDLoc dl(Op); // FIXME probably not meaningful
12298 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12299 const X86RegisterInfo *RegInfo =
12300 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12301 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12302 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12303 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12304 "Invalid Frame Register!");
12305 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12307 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12308 MachinePointerInfo(),
12309 false, false, false, 0);
12313 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12314 SelectionDAG &DAG) const {
12315 const X86RegisterInfo *RegInfo =
12316 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12317 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12320 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12321 SDValue Chain = Op.getOperand(0);
12322 SDValue Offset = Op.getOperand(1);
12323 SDValue Handler = Op.getOperand(2);
12326 EVT PtrVT = getPointerTy();
12327 const X86RegisterInfo *RegInfo =
12328 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12329 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12330 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12331 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12332 "Invalid Frame Register!");
12333 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12334 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12336 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12337 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12338 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12339 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12341 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12343 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12344 DAG.getRegister(StoreAddrReg, PtrVT));
12347 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12348 SelectionDAG &DAG) const {
12350 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12351 DAG.getVTList(MVT::i32, MVT::Other),
12352 Op.getOperand(0), Op.getOperand(1));
12355 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12356 SelectionDAG &DAG) const {
12358 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12359 Op.getOperand(0), Op.getOperand(1));
12362 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12363 return Op.getOperand(0);
12366 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12367 SelectionDAG &DAG) const {
12368 SDValue Root = Op.getOperand(0);
12369 SDValue Trmp = Op.getOperand(1); // trampoline
12370 SDValue FPtr = Op.getOperand(2); // nested function
12371 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12374 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12375 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12377 if (Subtarget->is64Bit()) {
12378 SDValue OutChains[6];
12380 // Large code-model.
12381 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12382 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12384 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12385 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12387 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12389 // Load the pointer to the nested function into R11.
12390 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12391 SDValue Addr = Trmp;
12392 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12393 Addr, MachinePointerInfo(TrmpAddr),
12396 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12397 DAG.getConstant(2, MVT::i64));
12398 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12399 MachinePointerInfo(TrmpAddr, 2),
12402 // Load the 'nest' parameter value into R10.
12403 // R10 is specified in X86CallingConv.td
12404 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12405 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12406 DAG.getConstant(10, MVT::i64));
12407 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12408 Addr, MachinePointerInfo(TrmpAddr, 10),
12411 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12412 DAG.getConstant(12, MVT::i64));
12413 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12414 MachinePointerInfo(TrmpAddr, 12),
12417 // Jump to the nested function.
12418 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12419 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12420 DAG.getConstant(20, MVT::i64));
12421 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12422 Addr, MachinePointerInfo(TrmpAddr, 20),
12425 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12426 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12427 DAG.getConstant(22, MVT::i64));
12428 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12429 MachinePointerInfo(TrmpAddr, 22),
12432 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12434 const Function *Func =
12435 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12436 CallingConv::ID CC = Func->getCallingConv();
12441 llvm_unreachable("Unsupported calling convention");
12442 case CallingConv::C:
12443 case CallingConv::X86_StdCall: {
12444 // Pass 'nest' parameter in ECX.
12445 // Must be kept in sync with X86CallingConv.td
12446 NestReg = X86::ECX;
12448 // Check that ECX wasn't needed by an 'inreg' parameter.
12449 FunctionType *FTy = Func->getFunctionType();
12450 const AttributeSet &Attrs = Func->getAttributes();
12452 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12453 unsigned InRegCount = 0;
12456 for (FunctionType::param_iterator I = FTy->param_begin(),
12457 E = FTy->param_end(); I != E; ++I, ++Idx)
12458 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12459 // FIXME: should only count parameters that are lowered to integers.
12460 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12462 if (InRegCount > 2) {
12463 report_fatal_error("Nest register in use - reduce number of inreg"
12469 case CallingConv::X86_FastCall:
12470 case CallingConv::X86_ThisCall:
12471 case CallingConv::Fast:
12472 // Pass 'nest' parameter in EAX.
12473 // Must be kept in sync with X86CallingConv.td
12474 NestReg = X86::EAX;
12478 SDValue OutChains[4];
12479 SDValue Addr, Disp;
12481 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12482 DAG.getConstant(10, MVT::i32));
12483 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12485 // This is storing the opcode for MOV32ri.
12486 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12487 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12488 OutChains[0] = DAG.getStore(Root, dl,
12489 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12490 Trmp, MachinePointerInfo(TrmpAddr),
12493 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12494 DAG.getConstant(1, MVT::i32));
12495 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12496 MachinePointerInfo(TrmpAddr, 1),
12499 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12500 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12501 DAG.getConstant(5, MVT::i32));
12502 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12503 MachinePointerInfo(TrmpAddr, 5),
12506 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12507 DAG.getConstant(6, MVT::i32));
12508 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12509 MachinePointerInfo(TrmpAddr, 6),
12512 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12516 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12517 SelectionDAG &DAG) const {
12519 The rounding mode is in bits 11:10 of FPSR, and has the following
12521 00 Round to nearest
12526 FLT_ROUNDS, on the other hand, expects the following:
12533 To perform the conversion, we do:
12534 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12537 MachineFunction &MF = DAG.getMachineFunction();
12538 const TargetMachine &TM = MF.getTarget();
12539 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12540 unsigned StackAlignment = TFI.getStackAlignment();
12541 MVT VT = Op.getSimpleValueType();
12544 // Save FP Control Word to stack slot
12545 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12546 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12548 MachineMemOperand *MMO =
12549 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12550 MachineMemOperand::MOStore, 2, 2);
12552 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12553 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12554 DAG.getVTList(MVT::Other),
12555 Ops, array_lengthof(Ops), MVT::i16,
12558 // Load FP Control Word from stack slot
12559 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12560 MachinePointerInfo(), false, false, false, 0);
12562 // Transform as necessary
12564 DAG.getNode(ISD::SRL, DL, MVT::i16,
12565 DAG.getNode(ISD::AND, DL, MVT::i16,
12566 CWD, DAG.getConstant(0x800, MVT::i16)),
12567 DAG.getConstant(11, MVT::i8));
12569 DAG.getNode(ISD::SRL, DL, MVT::i16,
12570 DAG.getNode(ISD::AND, DL, MVT::i16,
12571 CWD, DAG.getConstant(0x400, MVT::i16)),
12572 DAG.getConstant(9, MVT::i8));
12575 DAG.getNode(ISD::AND, DL, MVT::i16,
12576 DAG.getNode(ISD::ADD, DL, MVT::i16,
12577 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12578 DAG.getConstant(1, MVT::i16)),
12579 DAG.getConstant(3, MVT::i16));
12581 return DAG.getNode((VT.getSizeInBits() < 16 ?
12582 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12585 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12586 MVT VT = Op.getSimpleValueType();
12588 unsigned NumBits = VT.getSizeInBits();
12591 Op = Op.getOperand(0);
12592 if (VT == MVT::i8) {
12593 // Zero extend to i32 since there is not an i8 bsr.
12595 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12598 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12599 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12600 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12602 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12605 DAG.getConstant(NumBits+NumBits-1, OpVT),
12606 DAG.getConstant(X86::COND_E, MVT::i8),
12609 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12611 // Finally xor with NumBits-1.
12612 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12615 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12619 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12620 MVT VT = Op.getSimpleValueType();
12622 unsigned NumBits = VT.getSizeInBits();
12625 Op = Op.getOperand(0);
12626 if (VT == MVT::i8) {
12627 // Zero extend to i32 since there is not an i8 bsr.
12629 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12632 // Issue a bsr (scan bits in reverse).
12633 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12634 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12636 // And xor with NumBits-1.
12637 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12640 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12644 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12645 MVT VT = Op.getSimpleValueType();
12646 unsigned NumBits = VT.getSizeInBits();
12648 Op = Op.getOperand(0);
12650 // Issue a bsf (scan bits forward) which also sets EFLAGS.
12651 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12652 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12654 // If src is zero (i.e. bsf sets ZF), returns NumBits.
12657 DAG.getConstant(NumBits, VT),
12658 DAG.getConstant(X86::COND_E, MVT::i8),
12661 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12664 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12665 // ones, and then concatenate the result back.
12666 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12667 MVT VT = Op.getSimpleValueType();
12669 assert(VT.is256BitVector() && VT.isInteger() &&
12670 "Unsupported value type for operation");
12672 unsigned NumElems = VT.getVectorNumElements();
12675 // Extract the LHS vectors
12676 SDValue LHS = Op.getOperand(0);
12677 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12678 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12680 // Extract the RHS vectors
12681 SDValue RHS = Op.getOperand(1);
12682 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12683 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12685 MVT EltVT = VT.getVectorElementType();
12686 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12688 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12689 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12690 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12693 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12694 assert(Op.getSimpleValueType().is256BitVector() &&
12695 Op.getSimpleValueType().isInteger() &&
12696 "Only handle AVX 256-bit vector integer operation");
12697 return Lower256IntArith(Op, DAG);
12700 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12701 assert(Op.getSimpleValueType().is256BitVector() &&
12702 Op.getSimpleValueType().isInteger() &&
12703 "Only handle AVX 256-bit vector integer operation");
12704 return Lower256IntArith(Op, DAG);
12707 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12708 SelectionDAG &DAG) {
12710 MVT VT = Op.getSimpleValueType();
12712 // Decompose 256-bit ops into smaller 128-bit ops.
12713 if (VT.is256BitVector() && !Subtarget->hasInt256())
12714 return Lower256IntArith(Op, DAG);
12716 SDValue A = Op.getOperand(0);
12717 SDValue B = Op.getOperand(1);
12719 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12720 if (VT == MVT::v4i32) {
12721 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12722 "Should not custom lower when pmuldq is available!");
12724 // Extract the odd parts.
12725 static const int UnpackMask[] = { 1, -1, 3, -1 };
12726 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12727 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12729 // Multiply the even parts.
12730 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12731 // Now multiply odd parts.
12732 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12734 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12735 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12737 // Merge the two vectors back together with a shuffle. This expands into 2
12739 static const int ShufMask[] = { 0, 4, 2, 6 };
12740 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12743 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12744 "Only know how to lower V2I64/V4I64/V8I64 multiply");
12746 // Ahi = psrlqi(a, 32);
12747 // Bhi = psrlqi(b, 32);
12749 // AloBlo = pmuludq(a, b);
12750 // AloBhi = pmuludq(a, Bhi);
12751 // AhiBlo = pmuludq(Ahi, b);
12753 // AloBhi = psllqi(AloBhi, 32);
12754 // AhiBlo = psllqi(AhiBlo, 32);
12755 // return AloBlo + AloBhi + AhiBlo;
12757 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12758 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12760 // Bit cast to 32-bit vectors for MULUDQ
12761 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12762 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12763 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12764 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12765 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12766 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12768 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12769 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12770 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12772 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12773 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12775 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12776 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12779 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12780 MVT VT = Op.getSimpleValueType();
12781 MVT EltTy = VT.getVectorElementType();
12782 unsigned NumElts = VT.getVectorNumElements();
12783 SDValue N0 = Op.getOperand(0);
12786 // Lower sdiv X, pow2-const.
12787 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12791 APInt SplatValue, SplatUndef;
12792 unsigned SplatBitSize;
12794 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12796 EltTy.getSizeInBits() < SplatBitSize)
12799 if ((SplatValue != 0) &&
12800 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12801 unsigned Lg2 = SplatValue.countTrailingZeros();
12802 // Splat the sign bit.
12803 SmallVector<SDValue, 16> Sz(NumElts,
12804 DAG.getConstant(EltTy.getSizeInBits() - 1,
12806 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12807 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12809 // Add (N0 < 0) ? abs2 - 1 : 0;
12810 SmallVector<SDValue, 16> Amt(NumElts,
12811 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12813 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12814 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12816 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12817 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12818 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12819 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12822 // If we're dividing by a positive value, we're done. Otherwise, we must
12823 // negate the result.
12824 if (SplatValue.isNonNegative())
12827 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12828 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12829 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12834 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12835 const X86Subtarget *Subtarget) {
12836 MVT VT = Op.getSimpleValueType();
12838 SDValue R = Op.getOperand(0);
12839 SDValue Amt = Op.getOperand(1);
12841 // Optimize shl/srl/sra with constant shift amount.
12842 if (isSplatVector(Amt.getNode())) {
12843 SDValue SclrAmt = Amt->getOperand(0);
12844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12845 uint64_t ShiftAmt = C->getZExtValue();
12847 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12848 (Subtarget->hasInt256() &&
12849 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12850 (Subtarget->hasAVX512() &&
12851 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12852 if (Op.getOpcode() == ISD::SHL)
12853 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12855 if (Op.getOpcode() == ISD::SRL)
12856 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12858 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12859 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12863 if (VT == MVT::v16i8) {
12864 if (Op.getOpcode() == ISD::SHL) {
12865 // Make a large shift.
12866 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12867 MVT::v8i16, R, ShiftAmt,
12869 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12870 // Zero out the rightmost bits.
12871 SmallVector<SDValue, 16> V(16,
12872 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12874 return DAG.getNode(ISD::AND, dl, VT, SHL,
12875 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12877 if (Op.getOpcode() == ISD::SRL) {
12878 // Make a large shift.
12879 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12880 MVT::v8i16, R, ShiftAmt,
12882 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12883 // Zero out the leftmost bits.
12884 SmallVector<SDValue, 16> V(16,
12885 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12887 return DAG.getNode(ISD::AND, dl, VT, SRL,
12888 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12890 if (Op.getOpcode() == ISD::SRA) {
12891 if (ShiftAmt == 7) {
12892 // R s>> 7 === R s< 0
12893 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12894 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12897 // R s>> a === ((R u>> a) ^ m) - m
12898 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12899 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12901 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12902 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12903 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12906 llvm_unreachable("Unknown shift opcode.");
12909 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12910 if (Op.getOpcode() == ISD::SHL) {
12911 // Make a large shift.
12912 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12913 MVT::v16i16, R, ShiftAmt,
12915 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12916 // Zero out the rightmost bits.
12917 SmallVector<SDValue, 32> V(32,
12918 DAG.getConstant(uint8_t(-1U << ShiftAmt),
12920 return DAG.getNode(ISD::AND, dl, VT, SHL,
12921 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12923 if (Op.getOpcode() == ISD::SRL) {
12924 // Make a large shift.
12925 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12926 MVT::v16i16, R, ShiftAmt,
12928 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12929 // Zero out the leftmost bits.
12930 SmallVector<SDValue, 32> V(32,
12931 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12933 return DAG.getNode(ISD::AND, dl, VT, SRL,
12934 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12936 if (Op.getOpcode() == ISD::SRA) {
12937 if (ShiftAmt == 7) {
12938 // R s>> 7 === R s< 0
12939 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12940 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12943 // R s>> a === ((R u>> a) ^ m) - m
12944 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12945 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12947 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12948 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12949 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12952 llvm_unreachable("Unknown shift opcode.");
12957 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12958 if (!Subtarget->is64Bit() &&
12959 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12960 Amt.getOpcode() == ISD::BITCAST &&
12961 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12962 Amt = Amt.getOperand(0);
12963 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
12964 VT.getVectorNumElements();
12965 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12966 uint64_t ShiftAmt = 0;
12967 for (unsigned i = 0; i != Ratio; ++i) {
12968 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12972 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12974 // Check remaining shift amounts.
12975 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12976 uint64_t ShAmt = 0;
12977 for (unsigned j = 0; j != Ratio; ++j) {
12978 ConstantSDNode *C =
12979 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12983 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12985 if (ShAmt != ShiftAmt)
12988 switch (Op.getOpcode()) {
12990 llvm_unreachable("Unknown shift opcode!");
12992 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12995 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12998 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13006 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13007 const X86Subtarget* Subtarget) {
13008 MVT VT = Op.getSimpleValueType();
13010 SDValue R = Op.getOperand(0);
13011 SDValue Amt = Op.getOperand(1);
13013 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13014 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13015 (Subtarget->hasInt256() &&
13016 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13017 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13018 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13020 EVT EltVT = VT.getVectorElementType();
13022 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13023 unsigned NumElts = VT.getVectorNumElements();
13025 for (i = 0; i != NumElts; ++i) {
13026 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13030 for (j = i; j != NumElts; ++j) {
13031 SDValue Arg = Amt.getOperand(j);
13032 if (Arg.getOpcode() == ISD::UNDEF) continue;
13033 if (Arg != Amt.getOperand(i))
13036 if (i != NumElts && j == NumElts)
13037 BaseShAmt = Amt.getOperand(i);
13039 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13040 Amt = Amt.getOperand(0);
13041 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13042 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13043 SDValue InVec = Amt.getOperand(0);
13044 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13045 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13047 for (; i != NumElts; ++i) {
13048 SDValue Arg = InVec.getOperand(i);
13049 if (Arg.getOpcode() == ISD::UNDEF) continue;
13053 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13054 if (ConstantSDNode *C =
13055 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13056 unsigned SplatIdx =
13057 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13058 if (C->getZExtValue() == SplatIdx)
13059 BaseShAmt = InVec.getOperand(1);
13062 if (BaseShAmt.getNode() == 0)
13063 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13064 DAG.getIntPtrConstant(0));
13068 if (BaseShAmt.getNode()) {
13069 if (EltVT.bitsGT(MVT::i32))
13070 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13071 else if (EltVT.bitsLT(MVT::i32))
13072 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13074 switch (Op.getOpcode()) {
13076 llvm_unreachable("Unknown shift opcode!");
13078 switch (VT.SimpleTy) {
13079 default: return SDValue();
13088 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13091 switch (VT.SimpleTy) {
13092 default: return SDValue();
13099 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13102 switch (VT.SimpleTy) {
13103 default: return SDValue();
13112 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13118 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13119 if (!Subtarget->is64Bit() &&
13120 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13121 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13122 Amt.getOpcode() == ISD::BITCAST &&
13123 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13124 Amt = Amt.getOperand(0);
13125 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13126 VT.getVectorNumElements();
13127 std::vector<SDValue> Vals(Ratio);
13128 for (unsigned i = 0; i != Ratio; ++i)
13129 Vals[i] = Amt.getOperand(i);
13130 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13131 for (unsigned j = 0; j != Ratio; ++j)
13132 if (Vals[j] != Amt.getOperand(i + j))
13135 switch (Op.getOpcode()) {
13137 llvm_unreachable("Unknown shift opcode!");
13139 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13141 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13143 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13150 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13151 SelectionDAG &DAG) {
13153 MVT VT = Op.getSimpleValueType();
13155 SDValue R = Op.getOperand(0);
13156 SDValue Amt = Op.getOperand(1);
13159 if (!Subtarget->hasSSE2())
13162 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13166 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13170 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13172 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13173 if (Subtarget->hasInt256()) {
13174 if (Op.getOpcode() == ISD::SRL &&
13175 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13176 VT == MVT::v4i64 || VT == MVT::v8i32))
13178 if (Op.getOpcode() == ISD::SHL &&
13179 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13180 VT == MVT::v4i64 || VT == MVT::v8i32))
13182 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13186 // If possible, lower this packed shift into a vector multiply instead of
13187 // expanding it into a sequence of scalar shifts.
13188 // Do this only if the vector shift count is a constant build_vector.
13189 if (Op.getOpcode() == ISD::SHL &&
13190 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13191 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13192 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13193 SmallVector<SDValue, 8> Elts;
13194 EVT SVT = VT.getScalarType();
13195 unsigned SVTBits = SVT.getSizeInBits();
13196 const APInt &One = APInt(SVTBits, 1);
13197 unsigned NumElems = VT.getVectorNumElements();
13199 for (unsigned i=0; i !=NumElems; ++i) {
13200 SDValue Op = Amt->getOperand(i);
13201 if (Op->getOpcode() == ISD::UNDEF) {
13202 Elts.push_back(Op);
13206 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13207 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13208 uint64_t ShAmt = C.getZExtValue();
13209 if (ShAmt >= SVTBits) {
13210 Elts.push_back(DAG.getUNDEF(SVT));
13213 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13215 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13216 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13219 // Lower SHL with variable shift amount.
13220 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13221 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13223 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13224 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13225 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13226 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13229 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13230 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13233 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13234 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13236 // Turn 'a' into a mask suitable for VSELECT
13237 SDValue VSelM = DAG.getConstant(0x80, VT);
13238 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13239 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13241 SDValue CM1 = DAG.getConstant(0x0f, VT);
13242 SDValue CM2 = DAG.getConstant(0x3f, VT);
13244 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13245 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13246 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13247 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13248 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13251 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13252 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13253 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13255 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13256 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13257 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13258 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13259 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13262 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13263 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13264 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13266 // return VSELECT(r, r+r, a);
13267 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13268 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13272 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13273 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13274 // solution better.
13275 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13276 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13278 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13279 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13280 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13281 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13282 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13285 // Decompose 256-bit shifts into smaller 128-bit shifts.
13286 if (VT.is256BitVector()) {
13287 unsigned NumElems = VT.getVectorNumElements();
13288 MVT EltVT = VT.getVectorElementType();
13289 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13291 // Extract the two vectors
13292 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13293 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13295 // Recreate the shift amount vectors
13296 SDValue Amt1, Amt2;
13297 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13298 // Constant shift amount
13299 SmallVector<SDValue, 4> Amt1Csts;
13300 SmallVector<SDValue, 4> Amt2Csts;
13301 for (unsigned i = 0; i != NumElems/2; ++i)
13302 Amt1Csts.push_back(Amt->getOperand(i));
13303 for (unsigned i = NumElems/2; i != NumElems; ++i)
13304 Amt2Csts.push_back(Amt->getOperand(i));
13306 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13307 &Amt1Csts[0], NumElems/2);
13308 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13309 &Amt2Csts[0], NumElems/2);
13311 // Variable shift amount
13312 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13313 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13316 // Issue new vector shifts for the smaller types
13317 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13318 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13320 // Concatenate the result back
13321 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13327 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13328 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13329 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13330 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13331 // has only one use.
13332 SDNode *N = Op.getNode();
13333 SDValue LHS = N->getOperand(0);
13334 SDValue RHS = N->getOperand(1);
13335 unsigned BaseOp = 0;
13338 switch (Op.getOpcode()) {
13339 default: llvm_unreachable("Unknown ovf instruction!");
13341 // A subtract of one will be selected as a INC. Note that INC doesn't
13342 // set CF, so we can't do this for UADDO.
13343 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13345 BaseOp = X86ISD::INC;
13346 Cond = X86::COND_O;
13349 BaseOp = X86ISD::ADD;
13350 Cond = X86::COND_O;
13353 BaseOp = X86ISD::ADD;
13354 Cond = X86::COND_B;
13357 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13358 // set CF, so we can't do this for USUBO.
13359 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13361 BaseOp = X86ISD::DEC;
13362 Cond = X86::COND_O;
13365 BaseOp = X86ISD::SUB;
13366 Cond = X86::COND_O;
13369 BaseOp = X86ISD::SUB;
13370 Cond = X86::COND_B;
13373 BaseOp = X86ISD::SMUL;
13374 Cond = X86::COND_O;
13376 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13377 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13379 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13382 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13383 DAG.getConstant(X86::COND_O, MVT::i32),
13384 SDValue(Sum.getNode(), 2));
13386 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13390 // Also sets EFLAGS.
13391 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13392 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13395 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13396 DAG.getConstant(Cond, MVT::i32),
13397 SDValue(Sum.getNode(), 1));
13399 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13402 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13403 SelectionDAG &DAG) const {
13405 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13406 MVT VT = Op.getSimpleValueType();
13408 if (!Subtarget->hasSSE2() || !VT.isVector())
13411 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13412 ExtraVT.getScalarType().getSizeInBits();
13414 switch (VT.SimpleTy) {
13415 default: return SDValue();
13418 if (!Subtarget->hasFp256())
13420 if (!Subtarget->hasInt256()) {
13421 // needs to be split
13422 unsigned NumElems = VT.getVectorNumElements();
13424 // Extract the LHS vectors
13425 SDValue LHS = Op.getOperand(0);
13426 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13427 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13429 MVT EltVT = VT.getVectorElementType();
13430 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13432 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13433 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13434 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13436 SDValue Extra = DAG.getValueType(ExtraVT);
13438 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13439 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13441 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13446 SDValue Op0 = Op.getOperand(0);
13447 SDValue Op00 = Op0.getOperand(0);
13449 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13450 if (Op0.getOpcode() == ISD::BITCAST &&
13451 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13452 // (sext (vzext x)) -> (vsext x)
13453 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13454 if (Tmp1.getNode()) {
13455 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13456 // This folding is only valid when the in-reg type is a vector of i8,
13458 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13459 ExtraEltVT == MVT::i32) {
13460 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13461 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13462 "This optimization is invalid without a VZEXT.");
13463 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13469 // If the above didn't work, then just use Shift-Left + Shift-Right.
13470 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13472 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13478 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13479 SelectionDAG &DAG) {
13481 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13482 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13483 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13484 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13486 // The only fence that needs an instruction is a sequentially-consistent
13487 // cross-thread fence.
13488 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13489 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13490 // no-sse2). There isn't any reason to disable it if the target processor
13492 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13493 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13495 SDValue Chain = Op.getOperand(0);
13496 SDValue Zero = DAG.getConstant(0, MVT::i32);
13498 DAG.getRegister(X86::ESP, MVT::i32), // Base
13499 DAG.getTargetConstant(1, MVT::i8), // Scale
13500 DAG.getRegister(0, MVT::i32), // Index
13501 DAG.getTargetConstant(0, MVT::i32), // Disp
13502 DAG.getRegister(0, MVT::i32), // Segment.
13506 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13507 return SDValue(Res, 0);
13510 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13511 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13514 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13515 SelectionDAG &DAG) {
13516 MVT T = Op.getSimpleValueType();
13520 switch(T.SimpleTy) {
13521 default: llvm_unreachable("Invalid value type!");
13522 case MVT::i8: Reg = X86::AL; size = 1; break;
13523 case MVT::i16: Reg = X86::AX; size = 2; break;
13524 case MVT::i32: Reg = X86::EAX; size = 4; break;
13526 assert(Subtarget->is64Bit() && "Node not type legal!");
13527 Reg = X86::RAX; size = 8;
13530 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13531 Op.getOperand(2), SDValue());
13532 SDValue Ops[] = { cpIn.getValue(0),
13535 DAG.getTargetConstant(size, MVT::i8),
13536 cpIn.getValue(1) };
13537 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13538 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13539 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13540 Ops, array_lengthof(Ops), T, MMO);
13542 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13546 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13547 SelectionDAG &DAG) {
13548 assert(Subtarget->is64Bit() && "Result not type legalized?");
13549 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13550 SDValue TheChain = Op.getOperand(0);
13552 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13553 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13554 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13556 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13557 DAG.getConstant(32, MVT::i8));
13559 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13562 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13565 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13566 SelectionDAG &DAG) {
13567 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13568 MVT DstVT = Op.getSimpleValueType();
13569 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13570 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13571 assert((DstVT == MVT::i64 ||
13572 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13573 "Unexpected custom BITCAST");
13574 // i64 <=> MMX conversions are Legal.
13575 if (SrcVT==MVT::i64 && DstVT.isVector())
13577 if (DstVT==MVT::i64 && SrcVT.isVector())
13579 // MMX <=> MMX conversions are Legal.
13580 if (SrcVT.isVector() && DstVT.isVector())
13582 // All other conversions need to be expanded.
13586 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13587 SDNode *Node = Op.getNode();
13589 EVT T = Node->getValueType(0);
13590 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13591 DAG.getConstant(0, T), Node->getOperand(2));
13592 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13593 cast<AtomicSDNode>(Node)->getMemoryVT(),
13594 Node->getOperand(0),
13595 Node->getOperand(1), negOp,
13596 cast<AtomicSDNode>(Node)->getSrcValue(),
13597 cast<AtomicSDNode>(Node)->getAlignment(),
13598 cast<AtomicSDNode>(Node)->getOrdering(),
13599 cast<AtomicSDNode>(Node)->getSynchScope());
13602 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13603 SDNode *Node = Op.getNode();
13605 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13607 // Convert seq_cst store -> xchg
13608 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13609 // FIXME: On 32-bit, store -> fist or movq would be more efficient
13610 // (The only way to get a 16-byte store is cmpxchg16b)
13611 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13612 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13613 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13614 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13615 cast<AtomicSDNode>(Node)->getMemoryVT(),
13616 Node->getOperand(0),
13617 Node->getOperand(1), Node->getOperand(2),
13618 cast<AtomicSDNode>(Node)->getMemOperand(),
13619 cast<AtomicSDNode>(Node)->getOrdering(),
13620 cast<AtomicSDNode>(Node)->getSynchScope());
13621 return Swap.getValue(1);
13623 // Other atomic stores have a simple pattern.
13627 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13628 EVT VT = Op.getNode()->getSimpleValueType(0);
13630 // Let legalize expand this if it isn't a legal type yet.
13631 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13634 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13637 bool ExtraOp = false;
13638 switch (Op.getOpcode()) {
13639 default: llvm_unreachable("Invalid code");
13640 case ISD::ADDC: Opc = X86ISD::ADD; break;
13641 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13642 case ISD::SUBC: Opc = X86ISD::SUB; break;
13643 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13647 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13649 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13650 Op.getOperand(1), Op.getOperand(2));
13653 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13654 SelectionDAG &DAG) {
13655 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13657 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13658 // which returns the values as { float, float } (in XMM0) or
13659 // { double, double } (which is returned in XMM0, XMM1).
13661 SDValue Arg = Op.getOperand(0);
13662 EVT ArgVT = Arg.getValueType();
13663 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13665 TargetLowering::ArgListTy Args;
13666 TargetLowering::ArgListEntry Entry;
13670 Entry.isSExt = false;
13671 Entry.isZExt = false;
13672 Args.push_back(Entry);
13674 bool isF64 = ArgVT == MVT::f64;
13675 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13676 // the small struct {f32, f32} is returned in (eax, edx). For f64,
13677 // the results are returned via SRet in memory.
13678 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
13679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13680 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13682 Type *RetTy = isF64
13683 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13684 : (Type*)VectorType::get(ArgTy, 4);
13686 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13687 false, false, false, false, 0,
13688 CallingConv::C, /*isTaillCall=*/false,
13689 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13690 Callee, Args, DAG, dl);
13691 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13694 // Returned in xmm0 and xmm1.
13695 return CallResult.first;
13697 // Returned in bits 0:31 and 32:64 xmm0.
13698 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13699 CallResult.first, DAG.getIntPtrConstant(0));
13700 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13701 CallResult.first, DAG.getIntPtrConstant(1));
13702 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13703 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13706 /// LowerOperation - Provide custom lowering hooks for some operations.
13708 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13709 switch (Op.getOpcode()) {
13710 default: llvm_unreachable("Should not custom lower this!");
13711 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
13712 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13713 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
13714 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
13715 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
13716 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
13717 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
13718 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
13719 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13720 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
13721 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13722 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13723 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
13724 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
13725 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
13726 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
13727 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
13728 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
13729 case ISD::SHL_PARTS:
13730 case ISD::SRA_PARTS:
13731 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
13732 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
13733 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
13734 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
13735 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
13736 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13737 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
13738 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
13739 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
13740 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
13741 case ISD::FABS: return LowerFABS(Op, DAG);
13742 case ISD::FNEG: return LowerFNEG(Op, DAG);
13743 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
13744 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
13745 case ISD::SETCC: return LowerSETCC(Op, DAG);
13746 case ISD::SELECT: return LowerSELECT(Op, DAG);
13747 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
13748 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
13749 case ISD::VASTART: return LowerVASTART(Op, DAG);
13750 case ISD::VAARG: return LowerVAARG(Op, DAG);
13751 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
13752 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13753 case ISD::INTRINSIC_VOID:
13754 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13755 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
13756 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
13757 case ISD::FRAME_TO_ARGS_OFFSET:
13758 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13759 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13760 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
13761 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
13762 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
13763 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
13764 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
13765 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
13766 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
13767 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13768 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
13769 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
13772 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
13778 case ISD::UMULO: return LowerXALUO(Op, DAG);
13779 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13780 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
13784 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13785 case ISD::ADD: return LowerADD(Op, DAG);
13786 case ISD::SUB: return LowerSUB(Op, DAG);
13787 case ISD::SDIV: return LowerSDIV(Op, DAG);
13788 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
13792 static void ReplaceATOMIC_LOAD(SDNode *Node,
13793 SmallVectorImpl<SDValue> &Results,
13794 SelectionDAG &DAG) {
13796 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13798 // Convert wide load -> cmpxchg8b/cmpxchg16b
13799 // FIXME: On 32-bit, load -> fild or movq would be more efficient
13800 // (The only way to get a 16-byte load is cmpxchg16b)
13801 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13802 SDValue Zero = DAG.getConstant(0, VT);
13803 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13804 Node->getOperand(0),
13805 Node->getOperand(1), Zero, Zero,
13806 cast<AtomicSDNode>(Node)->getMemOperand(),
13807 cast<AtomicSDNode>(Node)->getOrdering(),
13808 cast<AtomicSDNode>(Node)->getOrdering(),
13809 cast<AtomicSDNode>(Node)->getSynchScope());
13810 Results.push_back(Swap.getValue(0));
13811 Results.push_back(Swap.getValue(1));
13815 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13816 SelectionDAG &DAG, unsigned NewOp) {
13818 assert (Node->getValueType(0) == MVT::i64 &&
13819 "Only know how to expand i64 atomics");
13821 SDValue Chain = Node->getOperand(0);
13822 SDValue In1 = Node->getOperand(1);
13823 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13824 Node->getOperand(2), DAG.getIntPtrConstant(0));
13825 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13826 Node->getOperand(2), DAG.getIntPtrConstant(1));
13827 SDValue Ops[] = { Chain, In1, In2L, In2H };
13828 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13830 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13831 cast<MemSDNode>(Node)->getMemOperand());
13832 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13833 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13834 Results.push_back(Result.getValue(2));
13837 /// ReplaceNodeResults - Replace a node with an illegal result type
13838 /// with a new node built out of custom code.
13839 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13840 SmallVectorImpl<SDValue>&Results,
13841 SelectionDAG &DAG) const {
13843 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13844 switch (N->getOpcode()) {
13846 llvm_unreachable("Do not know how to custom type legalize this operation!");
13847 case ISD::SIGN_EXTEND_INREG:
13852 // We don't want to expand or promote these.
13854 case ISD::FP_TO_SINT:
13855 case ISD::FP_TO_UINT: {
13856 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13858 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13861 std::pair<SDValue,SDValue> Vals =
13862 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13863 SDValue FIST = Vals.first, StackSlot = Vals.second;
13864 if (FIST.getNode() != 0) {
13865 EVT VT = N->getValueType(0);
13866 // Return a load from the stack slot.
13867 if (StackSlot.getNode() != 0)
13868 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13869 MachinePointerInfo(),
13870 false, false, false, 0));
13872 Results.push_back(FIST);
13876 case ISD::UINT_TO_FP: {
13877 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13878 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13879 N->getValueType(0) != MVT::v2f32)
13881 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13883 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13885 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13886 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13887 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13888 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13889 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13890 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13893 case ISD::FP_ROUND: {
13894 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13896 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13897 Results.push_back(V);
13900 case ISD::READCYCLECOUNTER: {
13901 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13902 SDValue TheChain = N->getOperand(0);
13903 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13904 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13906 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13908 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13909 SDValue Ops[] = { eax, edx };
13910 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13911 array_lengthof(Ops)));
13912 Results.push_back(edx.getValue(1));
13915 case ISD::ATOMIC_CMP_SWAP: {
13916 EVT T = N->getValueType(0);
13917 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13918 bool Regs64bit = T == MVT::i128;
13919 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13920 SDValue cpInL, cpInH;
13921 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13922 DAG.getConstant(0, HalfT));
13923 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13924 DAG.getConstant(1, HalfT));
13925 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13926 Regs64bit ? X86::RAX : X86::EAX,
13928 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13929 Regs64bit ? X86::RDX : X86::EDX,
13930 cpInH, cpInL.getValue(1));
13931 SDValue swapInL, swapInH;
13932 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13933 DAG.getConstant(0, HalfT));
13934 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13935 DAG.getConstant(1, HalfT));
13936 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13937 Regs64bit ? X86::RBX : X86::EBX,
13938 swapInL, cpInH.getValue(1));
13939 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13940 Regs64bit ? X86::RCX : X86::ECX,
13941 swapInH, swapInL.getValue(1));
13942 SDValue Ops[] = { swapInH.getValue(0),
13944 swapInH.getValue(1) };
13945 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13946 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13947 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13948 X86ISD::LCMPXCHG8_DAG;
13949 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13950 Ops, array_lengthof(Ops), T, MMO);
13951 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13952 Regs64bit ? X86::RAX : X86::EAX,
13953 HalfT, Result.getValue(1));
13954 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13955 Regs64bit ? X86::RDX : X86::EDX,
13956 HalfT, cpOutL.getValue(2));
13957 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13958 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13959 Results.push_back(cpOutH.getValue(1));
13962 case ISD::ATOMIC_LOAD_ADD:
13963 case ISD::ATOMIC_LOAD_AND:
13964 case ISD::ATOMIC_LOAD_NAND:
13965 case ISD::ATOMIC_LOAD_OR:
13966 case ISD::ATOMIC_LOAD_SUB:
13967 case ISD::ATOMIC_LOAD_XOR:
13968 case ISD::ATOMIC_LOAD_MAX:
13969 case ISD::ATOMIC_LOAD_MIN:
13970 case ISD::ATOMIC_LOAD_UMAX:
13971 case ISD::ATOMIC_LOAD_UMIN:
13972 case ISD::ATOMIC_SWAP: {
13974 switch (N->getOpcode()) {
13975 default: llvm_unreachable("Unexpected opcode");
13976 case ISD::ATOMIC_LOAD_ADD:
13977 Opc = X86ISD::ATOMADD64_DAG;
13979 case ISD::ATOMIC_LOAD_AND:
13980 Opc = X86ISD::ATOMAND64_DAG;
13982 case ISD::ATOMIC_LOAD_NAND:
13983 Opc = X86ISD::ATOMNAND64_DAG;
13985 case ISD::ATOMIC_LOAD_OR:
13986 Opc = X86ISD::ATOMOR64_DAG;
13988 case ISD::ATOMIC_LOAD_SUB:
13989 Opc = X86ISD::ATOMSUB64_DAG;
13991 case ISD::ATOMIC_LOAD_XOR:
13992 Opc = X86ISD::ATOMXOR64_DAG;
13994 case ISD::ATOMIC_LOAD_MAX:
13995 Opc = X86ISD::ATOMMAX64_DAG;
13997 case ISD::ATOMIC_LOAD_MIN:
13998 Opc = X86ISD::ATOMMIN64_DAG;
14000 case ISD::ATOMIC_LOAD_UMAX:
14001 Opc = X86ISD::ATOMUMAX64_DAG;
14003 case ISD::ATOMIC_LOAD_UMIN:
14004 Opc = X86ISD::ATOMUMIN64_DAG;
14006 case ISD::ATOMIC_SWAP:
14007 Opc = X86ISD::ATOMSWAP64_DAG;
14010 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14013 case ISD::ATOMIC_LOAD:
14014 ReplaceATOMIC_LOAD(N, Results, DAG);
14018 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14020 default: return NULL;
14021 case X86ISD::BSF: return "X86ISD::BSF";
14022 case X86ISD::BSR: return "X86ISD::BSR";
14023 case X86ISD::SHLD: return "X86ISD::SHLD";
14024 case X86ISD::SHRD: return "X86ISD::SHRD";
14025 case X86ISD::FAND: return "X86ISD::FAND";
14026 case X86ISD::FANDN: return "X86ISD::FANDN";
14027 case X86ISD::FOR: return "X86ISD::FOR";
14028 case X86ISD::FXOR: return "X86ISD::FXOR";
14029 case X86ISD::FSRL: return "X86ISD::FSRL";
14030 case X86ISD::FILD: return "X86ISD::FILD";
14031 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14032 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14033 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14034 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14035 case X86ISD::FLD: return "X86ISD::FLD";
14036 case X86ISD::FST: return "X86ISD::FST";
14037 case X86ISD::CALL: return "X86ISD::CALL";
14038 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14039 case X86ISD::BT: return "X86ISD::BT";
14040 case X86ISD::CMP: return "X86ISD::CMP";
14041 case X86ISD::COMI: return "X86ISD::COMI";
14042 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14043 case X86ISD::CMPM: return "X86ISD::CMPM";
14044 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14045 case X86ISD::SETCC: return "X86ISD::SETCC";
14046 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14047 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14048 case X86ISD::CMOV: return "X86ISD::CMOV";
14049 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14050 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14051 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14052 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14053 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14054 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14055 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14056 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14057 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14058 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14059 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14060 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14061 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14062 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14063 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14064 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14065 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14066 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14067 case X86ISD::HADD: return "X86ISD::HADD";
14068 case X86ISD::HSUB: return "X86ISD::HSUB";
14069 case X86ISD::FHADD: return "X86ISD::FHADD";
14070 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14071 case X86ISD::UMAX: return "X86ISD::UMAX";
14072 case X86ISD::UMIN: return "X86ISD::UMIN";
14073 case X86ISD::SMAX: return "X86ISD::SMAX";
14074 case X86ISD::SMIN: return "X86ISD::SMIN";
14075 case X86ISD::FMAX: return "X86ISD::FMAX";
14076 case X86ISD::FMIN: return "X86ISD::FMIN";
14077 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14078 case X86ISD::FMINC: return "X86ISD::FMINC";
14079 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14080 case X86ISD::FRCP: return "X86ISD::FRCP";
14081 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14082 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14083 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14084 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14085 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14086 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14087 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14088 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14089 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14090 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14091 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14092 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14093 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14094 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14095 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14096 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14097 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14098 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14099 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14100 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14101 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14102 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14103 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14104 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14105 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14106 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14107 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14108 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14109 case X86ISD::VSHL: return "X86ISD::VSHL";
14110 case X86ISD::VSRL: return "X86ISD::VSRL";
14111 case X86ISD::VSRA: return "X86ISD::VSRA";
14112 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14113 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14114 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14115 case X86ISD::CMPP: return "X86ISD::CMPP";
14116 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14117 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14118 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14119 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14120 case X86ISD::ADD: return "X86ISD::ADD";
14121 case X86ISD::SUB: return "X86ISD::SUB";
14122 case X86ISD::ADC: return "X86ISD::ADC";
14123 case X86ISD::SBB: return "X86ISD::SBB";
14124 case X86ISD::SMUL: return "X86ISD::SMUL";
14125 case X86ISD::UMUL: return "X86ISD::UMUL";
14126 case X86ISD::INC: return "X86ISD::INC";
14127 case X86ISD::DEC: return "X86ISD::DEC";
14128 case X86ISD::OR: return "X86ISD::OR";
14129 case X86ISD::XOR: return "X86ISD::XOR";
14130 case X86ISD::AND: return "X86ISD::AND";
14131 case X86ISD::BZHI: return "X86ISD::BZHI";
14132 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14133 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14134 case X86ISD::PTEST: return "X86ISD::PTEST";
14135 case X86ISD::TESTP: return "X86ISD::TESTP";
14136 case X86ISD::TESTM: return "X86ISD::TESTM";
14137 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14138 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14139 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14140 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14141 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14142 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14143 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14144 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14145 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14146 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14147 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14148 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14149 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14150 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14151 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14152 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14153 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14154 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14155 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14156 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14157 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14158 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14159 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14160 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14161 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14162 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14163 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14164 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14165 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14166 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14167 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14168 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14169 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14170 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14171 case X86ISD::SAHF: return "X86ISD::SAHF";
14172 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14173 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14174 case X86ISD::FMADD: return "X86ISD::FMADD";
14175 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14176 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14177 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14178 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14179 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14180 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14181 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14182 case X86ISD::XTEST: return "X86ISD::XTEST";
14186 // isLegalAddressingMode - Return true if the addressing mode represented
14187 // by AM is legal for this target, for a load/store of the specified type.
14188 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14190 // X86 supports extremely general addressing modes.
14191 CodeModel::Model M = getTargetMachine().getCodeModel();
14192 Reloc::Model R = getTargetMachine().getRelocationModel();
14194 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14195 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14200 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14202 // If a reference to this global requires an extra load, we can't fold it.
14203 if (isGlobalStubReference(GVFlags))
14206 // If BaseGV requires a register for the PIC base, we cannot also have a
14207 // BaseReg specified.
14208 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14211 // If lower 4G is not available, then we must use rip-relative addressing.
14212 if ((M != CodeModel::Small || R != Reloc::Static) &&
14213 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14217 switch (AM.Scale) {
14223 // These scales always work.
14228 // These scales are formed with basereg+scalereg. Only accept if there is
14233 default: // Other stuff never works.
14240 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14241 unsigned Bits = Ty->getScalarSizeInBits();
14243 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14244 // particularly cheaper than those without.
14248 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14249 // variable shifts just as cheap as scalar ones.
14250 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14253 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14254 // fully general vector.
14258 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14259 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14261 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14262 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14263 return NumBits1 > NumBits2;
14266 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14267 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14270 if (!isTypeLegal(EVT::getEVT(Ty1)))
14273 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14275 // Assuming the caller doesn't have a zeroext or signext return parameter,
14276 // truncation all the way down to i1 is valid.
14280 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14281 return isInt<32>(Imm);
14284 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14285 // Can also use sub to handle negated immediates.
14286 return isInt<32>(Imm);
14289 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14290 if (!VT1.isInteger() || !VT2.isInteger())
14292 unsigned NumBits1 = VT1.getSizeInBits();
14293 unsigned NumBits2 = VT2.getSizeInBits();
14294 return NumBits1 > NumBits2;
14297 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14298 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14299 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14302 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14303 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14304 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14307 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14308 EVT VT1 = Val.getValueType();
14309 if (isZExtFree(VT1, VT2))
14312 if (Val.getOpcode() != ISD::LOAD)
14315 if (!VT1.isSimple() || !VT1.isInteger() ||
14316 !VT2.isSimple() || !VT2.isInteger())
14319 switch (VT1.getSimpleVT().SimpleTy) {
14324 // X86 has 8, 16, and 32-bit zero-extending loads.
14332 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14333 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14336 VT = VT.getScalarType();
14338 if (!VT.isSimple())
14341 switch (VT.getSimpleVT().SimpleTy) {
14352 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14353 // i16 instructions are longer (0x66 prefix) and potentially slower.
14354 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14357 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14358 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14359 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14360 /// are assumed to be legal.
14362 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14364 if (!VT.isSimple())
14367 MVT SVT = VT.getSimpleVT();
14369 // Very little shuffling can be done for 64-bit vectors right now.
14370 if (VT.getSizeInBits() == 64)
14373 // FIXME: pshufb, blends, shifts.
14374 return (SVT.getVectorNumElements() == 2 ||
14375 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14376 isMOVLMask(M, SVT) ||
14377 isSHUFPMask(M, SVT) ||
14378 isPSHUFDMask(M, SVT) ||
14379 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14380 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14381 isPALIGNRMask(M, SVT, Subtarget) ||
14382 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14383 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14384 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14385 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14389 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14391 if (!VT.isSimple())
14394 MVT SVT = VT.getSimpleVT();
14395 unsigned NumElts = SVT.getVectorNumElements();
14396 // FIXME: This collection of masks seems suspect.
14399 if (NumElts == 4 && SVT.is128BitVector()) {
14400 return (isMOVLMask(Mask, SVT) ||
14401 isCommutedMOVLMask(Mask, SVT, true) ||
14402 isSHUFPMask(Mask, SVT) ||
14403 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14408 //===----------------------------------------------------------------------===//
14409 // X86 Scheduler Hooks
14410 //===----------------------------------------------------------------------===//
14412 /// Utility function to emit xbegin specifying the start of an RTM region.
14413 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14414 const TargetInstrInfo *TII) {
14415 DebugLoc DL = MI->getDebugLoc();
14417 const BasicBlock *BB = MBB->getBasicBlock();
14418 MachineFunction::iterator I = MBB;
14421 // For the v = xbegin(), we generate
14432 MachineBasicBlock *thisMBB = MBB;
14433 MachineFunction *MF = MBB->getParent();
14434 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14435 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14436 MF->insert(I, mainMBB);
14437 MF->insert(I, sinkMBB);
14439 // Transfer the remainder of BB and its successor edges to sinkMBB.
14440 sinkMBB->splice(sinkMBB->begin(), MBB,
14441 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14442 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14446 // # fallthrough to mainMBB
14447 // # abortion to sinkMBB
14448 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14449 thisMBB->addSuccessor(mainMBB);
14450 thisMBB->addSuccessor(sinkMBB);
14454 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14455 mainMBB->addSuccessor(sinkMBB);
14458 // EAX is live into the sinkMBB
14459 sinkMBB->addLiveIn(X86::EAX);
14460 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14461 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14464 MI->eraseFromParent();
14468 // Get CMPXCHG opcode for the specified data type.
14469 static unsigned getCmpXChgOpcode(EVT VT) {
14470 switch (VT.getSimpleVT().SimpleTy) {
14471 case MVT::i8: return X86::LCMPXCHG8;
14472 case MVT::i16: return X86::LCMPXCHG16;
14473 case MVT::i32: return X86::LCMPXCHG32;
14474 case MVT::i64: return X86::LCMPXCHG64;
14478 llvm_unreachable("Invalid operand size!");
14481 // Get LOAD opcode for the specified data type.
14482 static unsigned getLoadOpcode(EVT VT) {
14483 switch (VT.getSimpleVT().SimpleTy) {
14484 case MVT::i8: return X86::MOV8rm;
14485 case MVT::i16: return X86::MOV16rm;
14486 case MVT::i32: return X86::MOV32rm;
14487 case MVT::i64: return X86::MOV64rm;
14491 llvm_unreachable("Invalid operand size!");
14494 // Get opcode of the non-atomic one from the specified atomic instruction.
14495 static unsigned getNonAtomicOpcode(unsigned Opc) {
14497 case X86::ATOMAND8: return X86::AND8rr;
14498 case X86::ATOMAND16: return X86::AND16rr;
14499 case X86::ATOMAND32: return X86::AND32rr;
14500 case X86::ATOMAND64: return X86::AND64rr;
14501 case X86::ATOMOR8: return X86::OR8rr;
14502 case X86::ATOMOR16: return X86::OR16rr;
14503 case X86::ATOMOR32: return X86::OR32rr;
14504 case X86::ATOMOR64: return X86::OR64rr;
14505 case X86::ATOMXOR8: return X86::XOR8rr;
14506 case X86::ATOMXOR16: return X86::XOR16rr;
14507 case X86::ATOMXOR32: return X86::XOR32rr;
14508 case X86::ATOMXOR64: return X86::XOR64rr;
14510 llvm_unreachable("Unhandled atomic-load-op opcode!");
14513 // Get opcode of the non-atomic one from the specified atomic instruction with
14515 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14516 unsigned &ExtraOpc) {
14518 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14519 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14520 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14521 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14522 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14523 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14524 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14525 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14526 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14527 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14528 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14529 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14530 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14531 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14532 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14533 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14534 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14535 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14536 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14537 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14539 llvm_unreachable("Unhandled atomic-load-op opcode!");
14542 // Get opcode of the non-atomic one from the specified atomic instruction for
14543 // 64-bit data type on 32-bit target.
14544 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14546 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14547 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14548 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14549 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14550 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14551 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14552 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14553 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14554 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14555 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14557 llvm_unreachable("Unhandled atomic-load-op opcode!");
14560 // Get opcode of the non-atomic one from the specified atomic instruction for
14561 // 64-bit data type on 32-bit target with extra opcode.
14562 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14564 unsigned &ExtraOpc) {
14566 case X86::ATOMNAND6432:
14567 ExtraOpc = X86::NOT32r;
14568 HiOpc = X86::AND32rr;
14569 return X86::AND32rr;
14571 llvm_unreachable("Unhandled atomic-load-op opcode!");
14574 // Get pseudo CMOV opcode from the specified data type.
14575 static unsigned getPseudoCMOVOpc(EVT VT) {
14576 switch (VT.getSimpleVT().SimpleTy) {
14577 case MVT::i8: return X86::CMOV_GR8;
14578 case MVT::i16: return X86::CMOV_GR16;
14579 case MVT::i32: return X86::CMOV_GR32;
14583 llvm_unreachable("Unknown CMOV opcode!");
14586 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14587 // They will be translated into a spin-loop or compare-exchange loop from
14590 // dst = atomic-fetch-op MI.addr, MI.val
14596 // t1 = LOAD MI.addr
14598 // t4 = phi(t1, t3 / loop)
14599 // t2 = OP MI.val, t4
14601 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14607 MachineBasicBlock *
14608 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14609 MachineBasicBlock *MBB) const {
14610 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14611 DebugLoc DL = MI->getDebugLoc();
14613 MachineFunction *MF = MBB->getParent();
14614 MachineRegisterInfo &MRI = MF->getRegInfo();
14616 const BasicBlock *BB = MBB->getBasicBlock();
14617 MachineFunction::iterator I = MBB;
14620 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14621 "Unexpected number of operands");
14623 assert(MI->hasOneMemOperand() &&
14624 "Expected atomic-load-op to have one memoperand");
14626 // Memory Reference
14627 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14628 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14630 unsigned DstReg, SrcReg;
14631 unsigned MemOpndSlot;
14633 unsigned CurOp = 0;
14635 DstReg = MI->getOperand(CurOp++).getReg();
14636 MemOpndSlot = CurOp;
14637 CurOp += X86::AddrNumOperands;
14638 SrcReg = MI->getOperand(CurOp++).getReg();
14640 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14641 MVT::SimpleValueType VT = *RC->vt_begin();
14642 unsigned t1 = MRI.createVirtualRegister(RC);
14643 unsigned t2 = MRI.createVirtualRegister(RC);
14644 unsigned t3 = MRI.createVirtualRegister(RC);
14645 unsigned t4 = MRI.createVirtualRegister(RC);
14646 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14648 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14649 unsigned LOADOpc = getLoadOpcode(VT);
14651 // For the atomic load-arith operator, we generate
14654 // t1 = LOAD [MI.addr]
14656 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
14657 // t1 = OP MI.val, EAX
14659 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14665 MachineBasicBlock *thisMBB = MBB;
14666 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14667 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14668 MF->insert(I, mainMBB);
14669 MF->insert(I, sinkMBB);
14671 MachineInstrBuilder MIB;
14673 // Transfer the remainder of BB and its successor edges to sinkMBB.
14674 sinkMBB->splice(sinkMBB->begin(), MBB,
14675 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14676 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14679 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14680 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14681 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14683 NewMO.setIsKill(false);
14684 MIB.addOperand(NewMO);
14686 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14687 unsigned flags = (*MMOI)->getFlags();
14688 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14689 MachineMemOperand *MMO =
14690 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14691 (*MMOI)->getSize(),
14692 (*MMOI)->getBaseAlignment(),
14693 (*MMOI)->getTBAAInfo(),
14694 (*MMOI)->getRanges());
14695 MIB.addMemOperand(MMO);
14698 thisMBB->addSuccessor(mainMBB);
14701 MachineBasicBlock *origMainMBB = mainMBB;
14704 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14705 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14707 unsigned Opc = MI->getOpcode();
14710 llvm_unreachable("Unhandled atomic-load-op opcode!");
14711 case X86::ATOMAND8:
14712 case X86::ATOMAND16:
14713 case X86::ATOMAND32:
14714 case X86::ATOMAND64:
14716 case X86::ATOMOR16:
14717 case X86::ATOMOR32:
14718 case X86::ATOMOR64:
14719 case X86::ATOMXOR8:
14720 case X86::ATOMXOR16:
14721 case X86::ATOMXOR32:
14722 case X86::ATOMXOR64: {
14723 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14724 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14728 case X86::ATOMNAND8:
14729 case X86::ATOMNAND16:
14730 case X86::ATOMNAND32:
14731 case X86::ATOMNAND64: {
14732 unsigned Tmp = MRI.createVirtualRegister(RC);
14734 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14735 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14737 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14740 case X86::ATOMMAX8:
14741 case X86::ATOMMAX16:
14742 case X86::ATOMMAX32:
14743 case X86::ATOMMAX64:
14744 case X86::ATOMMIN8:
14745 case X86::ATOMMIN16:
14746 case X86::ATOMMIN32:
14747 case X86::ATOMMIN64:
14748 case X86::ATOMUMAX8:
14749 case X86::ATOMUMAX16:
14750 case X86::ATOMUMAX32:
14751 case X86::ATOMUMAX64:
14752 case X86::ATOMUMIN8:
14753 case X86::ATOMUMIN16:
14754 case X86::ATOMUMIN32:
14755 case X86::ATOMUMIN64: {
14757 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14759 BuildMI(mainMBB, DL, TII->get(CMPOpc))
14763 if (Subtarget->hasCMov()) {
14764 if (VT != MVT::i8) {
14766 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14770 // Promote i8 to i32 to use CMOV32
14771 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14772 const TargetRegisterClass *RC32 =
14773 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14774 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14775 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14776 unsigned Tmp = MRI.createVirtualRegister(RC32);
14778 unsigned Undef = MRI.createVirtualRegister(RC32);
14779 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14781 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14784 .addImm(X86::sub_8bit);
14785 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14788 .addImm(X86::sub_8bit);
14790 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14794 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14795 .addReg(Tmp, 0, X86::sub_8bit);
14798 // Use pseudo select and lower them.
14799 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14800 "Invalid atomic-load-op transformation!");
14801 unsigned SelOpc = getPseudoCMOVOpc(VT);
14802 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14803 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14804 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14805 .addReg(SrcReg).addReg(t4)
14807 mainMBB = EmitLoweredSelect(MIB, mainMBB);
14808 // Replace the original PHI node as mainMBB is changed after CMOV
14810 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14811 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14812 Phi->eraseFromParent();
14818 // Copy PhyReg back from virtual register.
14819 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14822 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14823 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14824 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14826 NewMO.setIsKill(false);
14827 MIB.addOperand(NewMO);
14830 MIB.setMemRefs(MMOBegin, MMOEnd);
14832 // Copy PhyReg back to virtual register.
14833 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14836 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14838 mainMBB->addSuccessor(origMainMBB);
14839 mainMBB->addSuccessor(sinkMBB);
14842 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14843 TII->get(TargetOpcode::COPY), DstReg)
14846 MI->eraseFromParent();
14850 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14851 // instructions. They will be translated into a spin-loop or compare-exchange
14855 // dst = atomic-fetch-op MI.addr, MI.val
14861 // t1L = LOAD [MI.addr + 0]
14862 // t1H = LOAD [MI.addr + 4]
14864 // t4L = phi(t1L, t3L / loop)
14865 // t4H = phi(t1H, t3H / loop)
14866 // t2L = OP MI.val.lo, t4L
14867 // t2H = OP MI.val.hi, t4H
14872 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14880 MachineBasicBlock *
14881 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14882 MachineBasicBlock *MBB) const {
14883 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14884 DebugLoc DL = MI->getDebugLoc();
14886 MachineFunction *MF = MBB->getParent();
14887 MachineRegisterInfo &MRI = MF->getRegInfo();
14889 const BasicBlock *BB = MBB->getBasicBlock();
14890 MachineFunction::iterator I = MBB;
14893 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14894 "Unexpected number of operands");
14896 assert(MI->hasOneMemOperand() &&
14897 "Expected atomic-load-op32 to have one memoperand");
14899 // Memory Reference
14900 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14901 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14903 unsigned DstLoReg, DstHiReg;
14904 unsigned SrcLoReg, SrcHiReg;
14905 unsigned MemOpndSlot;
14907 unsigned CurOp = 0;
14909 DstLoReg = MI->getOperand(CurOp++).getReg();
14910 DstHiReg = MI->getOperand(CurOp++).getReg();
14911 MemOpndSlot = CurOp;
14912 CurOp += X86::AddrNumOperands;
14913 SrcLoReg = MI->getOperand(CurOp++).getReg();
14914 SrcHiReg = MI->getOperand(CurOp++).getReg();
14916 const TargetRegisterClass *RC = &X86::GR32RegClass;
14917 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14919 unsigned t1L = MRI.createVirtualRegister(RC);
14920 unsigned t1H = MRI.createVirtualRegister(RC);
14921 unsigned t2L = MRI.createVirtualRegister(RC);
14922 unsigned t2H = MRI.createVirtualRegister(RC);
14923 unsigned t3L = MRI.createVirtualRegister(RC);
14924 unsigned t3H = MRI.createVirtualRegister(RC);
14925 unsigned t4L = MRI.createVirtualRegister(RC);
14926 unsigned t4H = MRI.createVirtualRegister(RC);
14928 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14929 unsigned LOADOpc = X86::MOV32rm;
14931 // For the atomic load-arith operator, we generate
14934 // t1L = LOAD [MI.addr + 0]
14935 // t1H = LOAD [MI.addr + 4]
14937 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
14938 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
14939 // t2L = OP MI.val.lo, t4L
14940 // t2H = OP MI.val.hi, t4H
14943 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14951 MachineBasicBlock *thisMBB = MBB;
14952 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14953 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14954 MF->insert(I, mainMBB);
14955 MF->insert(I, sinkMBB);
14957 MachineInstrBuilder MIB;
14959 // Transfer the remainder of BB and its successor edges to sinkMBB.
14960 sinkMBB->splice(sinkMBB->begin(), MBB,
14961 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14962 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14966 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14967 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14968 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14970 NewMO.setIsKill(false);
14971 MIB.addOperand(NewMO);
14973 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14974 unsigned flags = (*MMOI)->getFlags();
14975 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14976 MachineMemOperand *MMO =
14977 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14978 (*MMOI)->getSize(),
14979 (*MMOI)->getBaseAlignment(),
14980 (*MMOI)->getTBAAInfo(),
14981 (*MMOI)->getRanges());
14982 MIB.addMemOperand(MMO);
14984 MachineInstr *LowMI = MIB;
14987 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14988 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14989 if (i == X86::AddrDisp) {
14990 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14992 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14994 NewMO.setIsKill(false);
14995 MIB.addOperand(NewMO);
14998 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15000 thisMBB->addSuccessor(mainMBB);
15003 MachineBasicBlock *origMainMBB = mainMBB;
15006 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15007 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15008 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15009 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15011 unsigned Opc = MI->getOpcode();
15014 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15015 case X86::ATOMAND6432:
15016 case X86::ATOMOR6432:
15017 case X86::ATOMXOR6432:
15018 case X86::ATOMADD6432:
15019 case X86::ATOMSUB6432: {
15021 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15022 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15024 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15028 case X86::ATOMNAND6432: {
15029 unsigned HiOpc, NOTOpc;
15030 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15031 unsigned TmpL = MRI.createVirtualRegister(RC);
15032 unsigned TmpH = MRI.createVirtualRegister(RC);
15033 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15035 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15037 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15038 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15041 case X86::ATOMMAX6432:
15042 case X86::ATOMMIN6432:
15043 case X86::ATOMUMAX6432:
15044 case X86::ATOMUMIN6432: {
15046 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15047 unsigned cL = MRI.createVirtualRegister(RC8);
15048 unsigned cH = MRI.createVirtualRegister(RC8);
15049 unsigned cL32 = MRI.createVirtualRegister(RC);
15050 unsigned cH32 = MRI.createVirtualRegister(RC);
15051 unsigned cc = MRI.createVirtualRegister(RC);
15052 // cl := cmp src_lo, lo
15053 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15054 .addReg(SrcLoReg).addReg(t4L);
15055 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15056 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15057 // ch := cmp src_hi, hi
15058 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15059 .addReg(SrcHiReg).addReg(t4H);
15060 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15061 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15062 // cc := if (src_hi == hi) ? cl : ch;
15063 if (Subtarget->hasCMov()) {
15064 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15065 .addReg(cH32).addReg(cL32);
15067 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15068 .addReg(cH32).addReg(cL32)
15069 .addImm(X86::COND_E);
15070 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15072 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15073 if (Subtarget->hasCMov()) {
15074 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15075 .addReg(SrcLoReg).addReg(t4L);
15076 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15077 .addReg(SrcHiReg).addReg(t4H);
15079 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15080 .addReg(SrcLoReg).addReg(t4L)
15081 .addImm(X86::COND_NE);
15082 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15083 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15084 // 2nd CMOV lowering.
15085 mainMBB->addLiveIn(X86::EFLAGS);
15086 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15087 .addReg(SrcHiReg).addReg(t4H)
15088 .addImm(X86::COND_NE);
15089 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15090 // Replace the original PHI node as mainMBB is changed after CMOV
15092 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15093 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15094 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15095 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15096 PhiL->eraseFromParent();
15097 PhiH->eraseFromParent();
15101 case X86::ATOMSWAP6432: {
15103 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15104 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15105 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15110 // Copy EDX:EAX back from HiReg:LoReg
15111 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15112 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15113 // Copy ECX:EBX from t1H:t1L
15114 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15115 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15117 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15118 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15119 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15121 NewMO.setIsKill(false);
15122 MIB.addOperand(NewMO);
15124 MIB.setMemRefs(MMOBegin, MMOEnd);
15126 // Copy EDX:EAX back to t3H:t3L
15127 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15128 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15130 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15132 mainMBB->addSuccessor(origMainMBB);
15133 mainMBB->addSuccessor(sinkMBB);
15136 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15137 TII->get(TargetOpcode::COPY), DstLoReg)
15139 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15140 TII->get(TargetOpcode::COPY), DstHiReg)
15143 MI->eraseFromParent();
15147 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15148 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15149 // in the .td file.
15150 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15151 const TargetInstrInfo *TII) {
15153 switch (MI->getOpcode()) {
15154 default: llvm_unreachable("illegal opcode!");
15155 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15156 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15157 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15158 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15159 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15160 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15161 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15162 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15165 DebugLoc dl = MI->getDebugLoc();
15166 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15168 unsigned NumArgs = MI->getNumOperands();
15169 for (unsigned i = 1; i < NumArgs; ++i) {
15170 MachineOperand &Op = MI->getOperand(i);
15171 if (!(Op.isReg() && Op.isImplicit()))
15172 MIB.addOperand(Op);
15174 if (MI->hasOneMemOperand())
15175 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15177 BuildMI(*BB, MI, dl,
15178 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15179 .addReg(X86::XMM0);
15181 MI->eraseFromParent();
15185 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15186 // defs in an instruction pattern
15187 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15188 const TargetInstrInfo *TII) {
15190 switch (MI->getOpcode()) {
15191 default: llvm_unreachable("illegal opcode!");
15192 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15193 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15194 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15195 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15196 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15197 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15198 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15199 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15202 DebugLoc dl = MI->getDebugLoc();
15203 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15205 unsigned NumArgs = MI->getNumOperands(); // remove the results
15206 for (unsigned i = 1; i < NumArgs; ++i) {
15207 MachineOperand &Op = MI->getOperand(i);
15208 if (!(Op.isReg() && Op.isImplicit()))
15209 MIB.addOperand(Op);
15211 if (MI->hasOneMemOperand())
15212 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15214 BuildMI(*BB, MI, dl,
15215 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15218 MI->eraseFromParent();
15222 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15223 const TargetInstrInfo *TII,
15224 const X86Subtarget* Subtarget) {
15225 DebugLoc dl = MI->getDebugLoc();
15227 // Address into RAX/EAX, other two args into ECX, EDX.
15228 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15229 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15230 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15231 for (int i = 0; i < X86::AddrNumOperands; ++i)
15232 MIB.addOperand(MI->getOperand(i));
15234 unsigned ValOps = X86::AddrNumOperands;
15235 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15236 .addReg(MI->getOperand(ValOps).getReg());
15237 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15238 .addReg(MI->getOperand(ValOps+1).getReg());
15240 // The instruction doesn't actually take any operands though.
15241 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15243 MI->eraseFromParent(); // The pseudo is gone now.
15247 MachineBasicBlock *
15248 X86TargetLowering::EmitVAARG64WithCustomInserter(
15250 MachineBasicBlock *MBB) const {
15251 // Emit va_arg instruction on X86-64.
15253 // Operands to this pseudo-instruction:
15254 // 0 ) Output : destination address (reg)
15255 // 1-5) Input : va_list address (addr, i64mem)
15256 // 6 ) ArgSize : Size (in bytes) of vararg type
15257 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15258 // 8 ) Align : Alignment of type
15259 // 9 ) EFLAGS (implicit-def)
15261 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15262 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15264 unsigned DestReg = MI->getOperand(0).getReg();
15265 MachineOperand &Base = MI->getOperand(1);
15266 MachineOperand &Scale = MI->getOperand(2);
15267 MachineOperand &Index = MI->getOperand(3);
15268 MachineOperand &Disp = MI->getOperand(4);
15269 MachineOperand &Segment = MI->getOperand(5);
15270 unsigned ArgSize = MI->getOperand(6).getImm();
15271 unsigned ArgMode = MI->getOperand(7).getImm();
15272 unsigned Align = MI->getOperand(8).getImm();
15274 // Memory Reference
15275 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15276 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15277 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15279 // Machine Information
15280 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15281 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15282 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15283 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15284 DebugLoc DL = MI->getDebugLoc();
15286 // struct va_list {
15289 // i64 overflow_area (address)
15290 // i64 reg_save_area (address)
15292 // sizeof(va_list) = 24
15293 // alignment(va_list) = 8
15295 unsigned TotalNumIntRegs = 6;
15296 unsigned TotalNumXMMRegs = 8;
15297 bool UseGPOffset = (ArgMode == 1);
15298 bool UseFPOffset = (ArgMode == 2);
15299 unsigned MaxOffset = TotalNumIntRegs * 8 +
15300 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15302 /* Align ArgSize to a multiple of 8 */
15303 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15304 bool NeedsAlign = (Align > 8);
15306 MachineBasicBlock *thisMBB = MBB;
15307 MachineBasicBlock *overflowMBB;
15308 MachineBasicBlock *offsetMBB;
15309 MachineBasicBlock *endMBB;
15311 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15312 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15313 unsigned OffsetReg = 0;
15315 if (!UseGPOffset && !UseFPOffset) {
15316 // If we only pull from the overflow region, we don't create a branch.
15317 // We don't need to alter control flow.
15318 OffsetDestReg = 0; // unused
15319 OverflowDestReg = DestReg;
15322 overflowMBB = thisMBB;
15325 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15326 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15327 // If not, pull from overflow_area. (branch to overflowMBB)
15332 // offsetMBB overflowMBB
15337 // Registers for the PHI in endMBB
15338 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15339 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15341 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15342 MachineFunction *MF = MBB->getParent();
15343 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15344 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15345 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15347 MachineFunction::iterator MBBIter = MBB;
15350 // Insert the new basic blocks
15351 MF->insert(MBBIter, offsetMBB);
15352 MF->insert(MBBIter, overflowMBB);
15353 MF->insert(MBBIter, endMBB);
15355 // Transfer the remainder of MBB and its successor edges to endMBB.
15356 endMBB->splice(endMBB->begin(), thisMBB,
15357 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15358 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15360 // Make offsetMBB and overflowMBB successors of thisMBB
15361 thisMBB->addSuccessor(offsetMBB);
15362 thisMBB->addSuccessor(overflowMBB);
15364 // endMBB is a successor of both offsetMBB and overflowMBB
15365 offsetMBB->addSuccessor(endMBB);
15366 overflowMBB->addSuccessor(endMBB);
15368 // Load the offset value into a register
15369 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15370 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15374 .addDisp(Disp, UseFPOffset ? 4 : 0)
15375 .addOperand(Segment)
15376 .setMemRefs(MMOBegin, MMOEnd);
15378 // Check if there is enough room left to pull this argument.
15379 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15381 .addImm(MaxOffset + 8 - ArgSizeA8);
15383 // Branch to "overflowMBB" if offset >= max
15384 // Fall through to "offsetMBB" otherwise
15385 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15386 .addMBB(overflowMBB);
15389 // In offsetMBB, emit code to use the reg_save_area.
15391 assert(OffsetReg != 0);
15393 // Read the reg_save_area address.
15394 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15395 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15400 .addOperand(Segment)
15401 .setMemRefs(MMOBegin, MMOEnd);
15403 // Zero-extend the offset
15404 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15405 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15408 .addImm(X86::sub_32bit);
15410 // Add the offset to the reg_save_area to get the final address.
15411 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15412 .addReg(OffsetReg64)
15413 .addReg(RegSaveReg);
15415 // Compute the offset for the next argument
15416 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15417 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15419 .addImm(UseFPOffset ? 16 : 8);
15421 // Store it back into the va_list.
15422 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15426 .addDisp(Disp, UseFPOffset ? 4 : 0)
15427 .addOperand(Segment)
15428 .addReg(NextOffsetReg)
15429 .setMemRefs(MMOBegin, MMOEnd);
15432 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15437 // Emit code to use overflow area
15440 // Load the overflow_area address into a register.
15441 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15442 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15447 .addOperand(Segment)
15448 .setMemRefs(MMOBegin, MMOEnd);
15450 // If we need to align it, do so. Otherwise, just copy the address
15451 // to OverflowDestReg.
15453 // Align the overflow address
15454 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15455 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15457 // aligned_addr = (addr + (align-1)) & ~(align-1)
15458 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15459 .addReg(OverflowAddrReg)
15462 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15464 .addImm(~(uint64_t)(Align-1));
15466 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15467 .addReg(OverflowAddrReg);
15470 // Compute the next overflow address after this argument.
15471 // (the overflow address should be kept 8-byte aligned)
15472 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15473 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15474 .addReg(OverflowDestReg)
15475 .addImm(ArgSizeA8);
15477 // Store the new overflow address.
15478 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15483 .addOperand(Segment)
15484 .addReg(NextAddrReg)
15485 .setMemRefs(MMOBegin, MMOEnd);
15487 // If we branched, emit the PHI to the front of endMBB.
15489 BuildMI(*endMBB, endMBB->begin(), DL,
15490 TII->get(X86::PHI), DestReg)
15491 .addReg(OffsetDestReg).addMBB(offsetMBB)
15492 .addReg(OverflowDestReg).addMBB(overflowMBB);
15495 // Erase the pseudo instruction
15496 MI->eraseFromParent();
15501 MachineBasicBlock *
15502 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15504 MachineBasicBlock *MBB) const {
15505 // Emit code to save XMM registers to the stack. The ABI says that the
15506 // number of registers to save is given in %al, so it's theoretically
15507 // possible to do an indirect jump trick to avoid saving all of them,
15508 // however this code takes a simpler approach and just executes all
15509 // of the stores if %al is non-zero. It's less code, and it's probably
15510 // easier on the hardware branch predictor, and stores aren't all that
15511 // expensive anyway.
15513 // Create the new basic blocks. One block contains all the XMM stores,
15514 // and one block is the final destination regardless of whether any
15515 // stores were performed.
15516 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15517 MachineFunction *F = MBB->getParent();
15518 MachineFunction::iterator MBBIter = MBB;
15520 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15521 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15522 F->insert(MBBIter, XMMSaveMBB);
15523 F->insert(MBBIter, EndMBB);
15525 // Transfer the remainder of MBB and its successor edges to EndMBB.
15526 EndMBB->splice(EndMBB->begin(), MBB,
15527 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15528 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15530 // The original block will now fall through to the XMM save block.
15531 MBB->addSuccessor(XMMSaveMBB);
15532 // The XMMSaveMBB will fall through to the end block.
15533 XMMSaveMBB->addSuccessor(EndMBB);
15535 // Now add the instructions.
15536 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15537 DebugLoc DL = MI->getDebugLoc();
15539 unsigned CountReg = MI->getOperand(0).getReg();
15540 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15541 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15543 if (!Subtarget->isTargetWin64()) {
15544 // If %al is 0, branch around the XMM save block.
15545 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15546 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15547 MBB->addSuccessor(EndMBB);
15550 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15551 // that was just emitted, but clearly shouldn't be "saved".
15552 assert((MI->getNumOperands() <= 3 ||
15553 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15554 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15555 && "Expected last argument to be EFLAGS");
15556 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15557 // In the XMM save block, save all the XMM argument registers.
15558 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15559 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15560 MachineMemOperand *MMO =
15561 F->getMachineMemOperand(
15562 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15563 MachineMemOperand::MOStore,
15564 /*Size=*/16, /*Align=*/16);
15565 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15566 .addFrameIndex(RegSaveFrameIndex)
15567 .addImm(/*Scale=*/1)
15568 .addReg(/*IndexReg=*/0)
15569 .addImm(/*Disp=*/Offset)
15570 .addReg(/*Segment=*/0)
15571 .addReg(MI->getOperand(i).getReg())
15572 .addMemOperand(MMO);
15575 MI->eraseFromParent(); // The pseudo instruction is gone now.
15580 // The EFLAGS operand of SelectItr might be missing a kill marker
15581 // because there were multiple uses of EFLAGS, and ISel didn't know
15582 // which to mark. Figure out whether SelectItr should have had a
15583 // kill marker, and set it if it should. Returns the correct kill
15585 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15586 MachineBasicBlock* BB,
15587 const TargetRegisterInfo* TRI) {
15588 // Scan forward through BB for a use/def of EFLAGS.
15589 MachineBasicBlock::iterator miI(std::next(SelectItr));
15590 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15591 const MachineInstr& mi = *miI;
15592 if (mi.readsRegister(X86::EFLAGS))
15594 if (mi.definesRegister(X86::EFLAGS))
15595 break; // Should have kill-flag - update below.
15598 // If we hit the end of the block, check whether EFLAGS is live into a
15600 if (miI == BB->end()) {
15601 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15602 sEnd = BB->succ_end();
15603 sItr != sEnd; ++sItr) {
15604 MachineBasicBlock* succ = *sItr;
15605 if (succ->isLiveIn(X86::EFLAGS))
15610 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15611 // out. SelectMI should have a kill flag on EFLAGS.
15612 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15616 MachineBasicBlock *
15617 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15618 MachineBasicBlock *BB) const {
15619 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15620 DebugLoc DL = MI->getDebugLoc();
15622 // To "insert" a SELECT_CC instruction, we actually have to insert the
15623 // diamond control-flow pattern. The incoming instruction knows the
15624 // destination vreg to set, the condition code register to branch on, the
15625 // true/false values to select between, and a branch opcode to use.
15626 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15627 MachineFunction::iterator It = BB;
15633 // cmpTY ccX, r1, r2
15635 // fallthrough --> copy0MBB
15636 MachineBasicBlock *thisMBB = BB;
15637 MachineFunction *F = BB->getParent();
15638 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15639 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15640 F->insert(It, copy0MBB);
15641 F->insert(It, sinkMBB);
15643 // If the EFLAGS register isn't dead in the terminator, then claim that it's
15644 // live into the sink and copy blocks.
15645 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15646 if (!MI->killsRegister(X86::EFLAGS) &&
15647 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15648 copy0MBB->addLiveIn(X86::EFLAGS);
15649 sinkMBB->addLiveIn(X86::EFLAGS);
15652 // Transfer the remainder of BB and its successor edges to sinkMBB.
15653 sinkMBB->splice(sinkMBB->begin(), BB,
15654 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15655 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15657 // Add the true and fallthrough blocks as its successors.
15658 BB->addSuccessor(copy0MBB);
15659 BB->addSuccessor(sinkMBB);
15661 // Create the conditional branch instruction.
15663 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15664 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15667 // %FalseValue = ...
15668 // # fallthrough to sinkMBB
15669 copy0MBB->addSuccessor(sinkMBB);
15672 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15674 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15675 TII->get(X86::PHI), MI->getOperand(0).getReg())
15676 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15677 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15679 MI->eraseFromParent(); // The pseudo instruction is gone now.
15683 MachineBasicBlock *
15684 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15685 bool Is64Bit) const {
15686 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15687 DebugLoc DL = MI->getDebugLoc();
15688 MachineFunction *MF = BB->getParent();
15689 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15691 assert(getTargetMachine().Options.EnableSegmentedStacks);
15693 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15694 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15697 // ... [Till the alloca]
15698 // If stacklet is not large enough, jump to mallocMBB
15701 // Allocate by subtracting from RSP
15702 // Jump to continueMBB
15705 // Allocate by call to runtime
15709 // [rest of original BB]
15712 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15713 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15714 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15716 MachineRegisterInfo &MRI = MF->getRegInfo();
15717 const TargetRegisterClass *AddrRegClass =
15718 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15720 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15721 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15722 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15723 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15724 sizeVReg = MI->getOperand(1).getReg(),
15725 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15727 MachineFunction::iterator MBBIter = BB;
15730 MF->insert(MBBIter, bumpMBB);
15731 MF->insert(MBBIter, mallocMBB);
15732 MF->insert(MBBIter, continueMBB);
15734 continueMBB->splice(continueMBB->begin(), BB,
15735 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15736 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15738 // Add code to the main basic block to check if the stack limit has been hit,
15739 // and if so, jump to mallocMBB otherwise to bumpMBB.
15740 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15741 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15742 .addReg(tmpSPVReg).addReg(sizeVReg);
15743 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15744 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15745 .addReg(SPLimitVReg);
15746 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15748 // bumpMBB simply decreases the stack pointer, since we know the current
15749 // stacklet has enough space.
15750 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15751 .addReg(SPLimitVReg);
15752 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15753 .addReg(SPLimitVReg);
15754 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15756 // Calls into a routine in libgcc to allocate more space from the heap.
15757 const uint32_t *RegMask =
15758 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15760 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15762 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15763 .addExternalSymbol("__morestack_allocate_stack_space")
15764 .addRegMask(RegMask)
15765 .addReg(X86::RDI, RegState::Implicit)
15766 .addReg(X86::RAX, RegState::ImplicitDefine);
15768 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15770 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15771 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15772 .addExternalSymbol("__morestack_allocate_stack_space")
15773 .addRegMask(RegMask)
15774 .addReg(X86::EAX, RegState::ImplicitDefine);
15778 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15781 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15782 .addReg(Is64Bit ? X86::RAX : X86::EAX);
15783 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15785 // Set up the CFG correctly.
15786 BB->addSuccessor(bumpMBB);
15787 BB->addSuccessor(mallocMBB);
15788 mallocMBB->addSuccessor(continueMBB);
15789 bumpMBB->addSuccessor(continueMBB);
15791 // Take care of the PHI nodes.
15792 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15793 MI->getOperand(0).getReg())
15794 .addReg(mallocPtrVReg).addMBB(mallocMBB)
15795 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15797 // Delete the original pseudo instruction.
15798 MI->eraseFromParent();
15801 return continueMBB;
15804 MachineBasicBlock *
15805 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15806 MachineBasicBlock *BB) const {
15807 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15808 DebugLoc DL = MI->getDebugLoc();
15810 assert(!Subtarget->isTargetMacho());
15812 // The lowering is pretty easy: we're just emitting the call to _alloca. The
15813 // non-trivial part is impdef of ESP.
15815 if (Subtarget->isTargetWin64()) {
15816 if (Subtarget->isTargetCygMing()) {
15817 // ___chkstk(Mingw64):
15818 // Clobbers R10, R11, RAX and EFLAGS.
15820 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15821 .addExternalSymbol("___chkstk")
15822 .addReg(X86::RAX, RegState::Implicit)
15823 .addReg(X86::RSP, RegState::Implicit)
15824 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15825 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15826 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15828 // __chkstk(MSVCRT): does not update stack pointer.
15829 // Clobbers R10, R11 and EFLAGS.
15830 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15831 .addExternalSymbol("__chkstk")
15832 .addReg(X86::RAX, RegState::Implicit)
15833 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15834 // RAX has the offset to be subtracted from RSP.
15835 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15840 const char *StackProbeSymbol =
15841 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15843 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15844 .addExternalSymbol(StackProbeSymbol)
15845 .addReg(X86::EAX, RegState::Implicit)
15846 .addReg(X86::ESP, RegState::Implicit)
15847 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15848 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15849 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15852 MI->eraseFromParent(); // The pseudo instruction is gone now.
15856 MachineBasicBlock *
15857 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15858 MachineBasicBlock *BB) const {
15859 // This is pretty easy. We're taking the value that we received from
15860 // our load from the relocation, sticking it in either RDI (x86-64)
15861 // or EAX and doing an indirect call. The return value will then
15862 // be in the normal return register.
15863 const X86InstrInfo *TII
15864 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15865 DebugLoc DL = MI->getDebugLoc();
15866 MachineFunction *F = BB->getParent();
15868 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15869 assert(MI->getOperand(3).isGlobal() && "This should be a global");
15871 // Get a register mask for the lowered call.
15872 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15873 // proper register mask.
15874 const uint32_t *RegMask =
15875 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15876 if (Subtarget->is64Bit()) {
15877 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15878 TII->get(X86::MOV64rm), X86::RDI)
15880 .addImm(0).addReg(0)
15881 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15882 MI->getOperand(3).getTargetFlags())
15884 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15885 addDirectMem(MIB, X86::RDI);
15886 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15887 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15888 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15889 TII->get(X86::MOV32rm), X86::EAX)
15891 .addImm(0).addReg(0)
15892 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15893 MI->getOperand(3).getTargetFlags())
15895 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15896 addDirectMem(MIB, X86::EAX);
15897 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15899 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15900 TII->get(X86::MOV32rm), X86::EAX)
15901 .addReg(TII->getGlobalBaseReg(F))
15902 .addImm(0).addReg(0)
15903 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15904 MI->getOperand(3).getTargetFlags())
15906 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15907 addDirectMem(MIB, X86::EAX);
15908 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15911 MI->eraseFromParent(); // The pseudo instruction is gone now.
15915 MachineBasicBlock *
15916 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15917 MachineBasicBlock *MBB) const {
15918 DebugLoc DL = MI->getDebugLoc();
15919 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15921 MachineFunction *MF = MBB->getParent();
15922 MachineRegisterInfo &MRI = MF->getRegInfo();
15924 const BasicBlock *BB = MBB->getBasicBlock();
15925 MachineFunction::iterator I = MBB;
15928 // Memory Reference
15929 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15930 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15933 unsigned MemOpndSlot = 0;
15935 unsigned CurOp = 0;
15937 DstReg = MI->getOperand(CurOp++).getReg();
15938 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15939 assert(RC->hasType(MVT::i32) && "Invalid destination!");
15940 unsigned mainDstReg = MRI.createVirtualRegister(RC);
15941 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15943 MemOpndSlot = CurOp;
15945 MVT PVT = getPointerTy();
15946 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15947 "Invalid Pointer Size!");
15949 // For v = setjmp(buf), we generate
15952 // buf[LabelOffset] = restoreMBB
15953 // SjLjSetup restoreMBB
15959 // v = phi(main, restore)
15964 MachineBasicBlock *thisMBB = MBB;
15965 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15966 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15967 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15968 MF->insert(I, mainMBB);
15969 MF->insert(I, sinkMBB);
15970 MF->push_back(restoreMBB);
15972 MachineInstrBuilder MIB;
15974 // Transfer the remainder of BB and its successor edges to sinkMBB.
15975 sinkMBB->splice(sinkMBB->begin(), MBB,
15976 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15977 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15980 unsigned PtrStoreOpc = 0;
15981 unsigned LabelReg = 0;
15982 const int64_t LabelOffset = 1 * PVT.getStoreSize();
15983 Reloc::Model RM = getTargetMachine().getRelocationModel();
15984 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15985 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15987 // Prepare IP either in reg or imm.
15988 if (!UseImmLabel) {
15989 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15990 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15991 LabelReg = MRI.createVirtualRegister(PtrRC);
15992 if (Subtarget->is64Bit()) {
15993 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15997 .addMBB(restoreMBB)
16000 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16001 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16002 .addReg(XII->getGlobalBaseReg(MF))
16005 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16009 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16011 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16012 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16013 if (i == X86::AddrDisp)
16014 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16016 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16019 MIB.addReg(LabelReg);
16021 MIB.addMBB(restoreMBB);
16022 MIB.setMemRefs(MMOBegin, MMOEnd);
16024 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16025 .addMBB(restoreMBB);
16027 const X86RegisterInfo *RegInfo =
16028 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16029 MIB.addRegMask(RegInfo->getNoPreservedMask());
16030 thisMBB->addSuccessor(mainMBB);
16031 thisMBB->addSuccessor(restoreMBB);
16035 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16036 mainMBB->addSuccessor(sinkMBB);
16039 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16040 TII->get(X86::PHI), DstReg)
16041 .addReg(mainDstReg).addMBB(mainMBB)
16042 .addReg(restoreDstReg).addMBB(restoreMBB);
16045 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16046 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16047 restoreMBB->addSuccessor(sinkMBB);
16049 MI->eraseFromParent();
16053 MachineBasicBlock *
16054 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16055 MachineBasicBlock *MBB) const {
16056 DebugLoc DL = MI->getDebugLoc();
16057 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16059 MachineFunction *MF = MBB->getParent();
16060 MachineRegisterInfo &MRI = MF->getRegInfo();
16062 // Memory Reference
16063 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16064 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16066 MVT PVT = getPointerTy();
16067 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16068 "Invalid Pointer Size!");
16070 const TargetRegisterClass *RC =
16071 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16072 unsigned Tmp = MRI.createVirtualRegister(RC);
16073 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16074 const X86RegisterInfo *RegInfo =
16075 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16076 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16077 unsigned SP = RegInfo->getStackRegister();
16079 MachineInstrBuilder MIB;
16081 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16082 const int64_t SPOffset = 2 * PVT.getStoreSize();
16084 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16085 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16088 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16089 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16090 MIB.addOperand(MI->getOperand(i));
16091 MIB.setMemRefs(MMOBegin, MMOEnd);
16093 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16094 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16095 if (i == X86::AddrDisp)
16096 MIB.addDisp(MI->getOperand(i), LabelOffset);
16098 MIB.addOperand(MI->getOperand(i));
16100 MIB.setMemRefs(MMOBegin, MMOEnd);
16102 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16103 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16104 if (i == X86::AddrDisp)
16105 MIB.addDisp(MI->getOperand(i), SPOffset);
16107 MIB.addOperand(MI->getOperand(i));
16109 MIB.setMemRefs(MMOBegin, MMOEnd);
16111 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16113 MI->eraseFromParent();
16117 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16118 // accumulator loops. Writing back to the accumulator allows the coalescer
16119 // to remove extra copies in the loop.
16120 MachineBasicBlock *
16121 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16122 MachineBasicBlock *MBB) const {
16123 MachineOperand &AddendOp = MI->getOperand(3);
16125 // Bail out early if the addend isn't a register - we can't switch these.
16126 if (!AddendOp.isReg())
16129 MachineFunction &MF = *MBB->getParent();
16130 MachineRegisterInfo &MRI = MF.getRegInfo();
16132 // Check whether the addend is defined by a PHI:
16133 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16134 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16135 if (!AddendDef.isPHI())
16138 // Look for the following pattern:
16140 // %addend = phi [%entry, 0], [%loop, %result]
16142 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16146 // %addend = phi [%entry, 0], [%loop, %result]
16148 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16150 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16151 assert(AddendDef.getOperand(i).isReg());
16152 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16153 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16154 if (&PHISrcInst == MI) {
16155 // Found a matching instruction.
16156 unsigned NewFMAOpc = 0;
16157 switch (MI->getOpcode()) {
16158 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16159 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16160 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16161 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16162 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16163 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16164 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16165 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16166 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16167 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16168 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16169 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16170 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16171 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16172 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16173 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16174 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16175 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16176 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16177 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16178 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16179 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16180 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16181 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16182 default: llvm_unreachable("Unrecognized FMA variant.");
16185 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16186 MachineInstrBuilder MIB =
16187 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16188 .addOperand(MI->getOperand(0))
16189 .addOperand(MI->getOperand(3))
16190 .addOperand(MI->getOperand(2))
16191 .addOperand(MI->getOperand(1));
16192 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16193 MI->eraseFromParent();
16200 MachineBasicBlock *
16201 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16202 MachineBasicBlock *BB) const {
16203 switch (MI->getOpcode()) {
16204 default: llvm_unreachable("Unexpected instr type to insert");
16205 case X86::TAILJMPd64:
16206 case X86::TAILJMPr64:
16207 case X86::TAILJMPm64:
16208 llvm_unreachable("TAILJMP64 would not be touched here.");
16209 case X86::TCRETURNdi64:
16210 case X86::TCRETURNri64:
16211 case X86::TCRETURNmi64:
16213 case X86::WIN_ALLOCA:
16214 return EmitLoweredWinAlloca(MI, BB);
16215 case X86::SEG_ALLOCA_32:
16216 return EmitLoweredSegAlloca(MI, BB, false);
16217 case X86::SEG_ALLOCA_64:
16218 return EmitLoweredSegAlloca(MI, BB, true);
16219 case X86::TLSCall_32:
16220 case X86::TLSCall_64:
16221 return EmitLoweredTLSCall(MI, BB);
16222 case X86::CMOV_GR8:
16223 case X86::CMOV_FR32:
16224 case X86::CMOV_FR64:
16225 case X86::CMOV_V4F32:
16226 case X86::CMOV_V2F64:
16227 case X86::CMOV_V2I64:
16228 case X86::CMOV_V8F32:
16229 case X86::CMOV_V4F64:
16230 case X86::CMOV_V4I64:
16231 case X86::CMOV_V16F32:
16232 case X86::CMOV_V8F64:
16233 case X86::CMOV_V8I64:
16234 case X86::CMOV_GR16:
16235 case X86::CMOV_GR32:
16236 case X86::CMOV_RFP32:
16237 case X86::CMOV_RFP64:
16238 case X86::CMOV_RFP80:
16239 return EmitLoweredSelect(MI, BB);
16241 case X86::FP32_TO_INT16_IN_MEM:
16242 case X86::FP32_TO_INT32_IN_MEM:
16243 case X86::FP32_TO_INT64_IN_MEM:
16244 case X86::FP64_TO_INT16_IN_MEM:
16245 case X86::FP64_TO_INT32_IN_MEM:
16246 case X86::FP64_TO_INT64_IN_MEM:
16247 case X86::FP80_TO_INT16_IN_MEM:
16248 case X86::FP80_TO_INT32_IN_MEM:
16249 case X86::FP80_TO_INT64_IN_MEM: {
16250 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16251 DebugLoc DL = MI->getDebugLoc();
16253 // Change the floating point control register to use "round towards zero"
16254 // mode when truncating to an integer value.
16255 MachineFunction *F = BB->getParent();
16256 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16257 addFrameReference(BuildMI(*BB, MI, DL,
16258 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16260 // Load the old value of the high byte of the control word...
16262 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16263 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16266 // Set the high part to be round to zero...
16267 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16270 // Reload the modified control word now...
16271 addFrameReference(BuildMI(*BB, MI, DL,
16272 TII->get(X86::FLDCW16m)), CWFrameIdx);
16274 // Restore the memory image of control word to original value
16275 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16278 // Get the X86 opcode to use.
16280 switch (MI->getOpcode()) {
16281 default: llvm_unreachable("illegal opcode!");
16282 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16283 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16284 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16285 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16286 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16287 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16288 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16289 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16290 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16294 MachineOperand &Op = MI->getOperand(0);
16296 AM.BaseType = X86AddressMode::RegBase;
16297 AM.Base.Reg = Op.getReg();
16299 AM.BaseType = X86AddressMode::FrameIndexBase;
16300 AM.Base.FrameIndex = Op.getIndex();
16302 Op = MI->getOperand(1);
16304 AM.Scale = Op.getImm();
16305 Op = MI->getOperand(2);
16307 AM.IndexReg = Op.getImm();
16308 Op = MI->getOperand(3);
16309 if (Op.isGlobal()) {
16310 AM.GV = Op.getGlobal();
16312 AM.Disp = Op.getImm();
16314 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16315 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16317 // Reload the original control word now.
16318 addFrameReference(BuildMI(*BB, MI, DL,
16319 TII->get(X86::FLDCW16m)), CWFrameIdx);
16321 MI->eraseFromParent(); // The pseudo instruction is gone now.
16324 // String/text processing lowering.
16325 case X86::PCMPISTRM128REG:
16326 case X86::VPCMPISTRM128REG:
16327 case X86::PCMPISTRM128MEM:
16328 case X86::VPCMPISTRM128MEM:
16329 case X86::PCMPESTRM128REG:
16330 case X86::VPCMPESTRM128REG:
16331 case X86::PCMPESTRM128MEM:
16332 case X86::VPCMPESTRM128MEM:
16333 assert(Subtarget->hasSSE42() &&
16334 "Target must have SSE4.2 or AVX features enabled");
16335 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16337 // String/text processing lowering.
16338 case X86::PCMPISTRIREG:
16339 case X86::VPCMPISTRIREG:
16340 case X86::PCMPISTRIMEM:
16341 case X86::VPCMPISTRIMEM:
16342 case X86::PCMPESTRIREG:
16343 case X86::VPCMPESTRIREG:
16344 case X86::PCMPESTRIMEM:
16345 case X86::VPCMPESTRIMEM:
16346 assert(Subtarget->hasSSE42() &&
16347 "Target must have SSE4.2 or AVX features enabled");
16348 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16350 // Thread synchronization.
16352 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16356 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16358 // Atomic Lowering.
16359 case X86::ATOMAND8:
16360 case X86::ATOMAND16:
16361 case X86::ATOMAND32:
16362 case X86::ATOMAND64:
16365 case X86::ATOMOR16:
16366 case X86::ATOMOR32:
16367 case X86::ATOMOR64:
16369 case X86::ATOMXOR16:
16370 case X86::ATOMXOR8:
16371 case X86::ATOMXOR32:
16372 case X86::ATOMXOR64:
16374 case X86::ATOMNAND8:
16375 case X86::ATOMNAND16:
16376 case X86::ATOMNAND32:
16377 case X86::ATOMNAND64:
16379 case X86::ATOMMAX8:
16380 case X86::ATOMMAX16:
16381 case X86::ATOMMAX32:
16382 case X86::ATOMMAX64:
16384 case X86::ATOMMIN8:
16385 case X86::ATOMMIN16:
16386 case X86::ATOMMIN32:
16387 case X86::ATOMMIN64:
16389 case X86::ATOMUMAX8:
16390 case X86::ATOMUMAX16:
16391 case X86::ATOMUMAX32:
16392 case X86::ATOMUMAX64:
16394 case X86::ATOMUMIN8:
16395 case X86::ATOMUMIN16:
16396 case X86::ATOMUMIN32:
16397 case X86::ATOMUMIN64:
16398 return EmitAtomicLoadArith(MI, BB);
16400 // This group does 64-bit operations on a 32-bit host.
16401 case X86::ATOMAND6432:
16402 case X86::ATOMOR6432:
16403 case X86::ATOMXOR6432:
16404 case X86::ATOMNAND6432:
16405 case X86::ATOMADD6432:
16406 case X86::ATOMSUB6432:
16407 case X86::ATOMMAX6432:
16408 case X86::ATOMMIN6432:
16409 case X86::ATOMUMAX6432:
16410 case X86::ATOMUMIN6432:
16411 case X86::ATOMSWAP6432:
16412 return EmitAtomicLoadArith6432(MI, BB);
16414 case X86::VASTART_SAVE_XMM_REGS:
16415 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16417 case X86::VAARG_64:
16418 return EmitVAARG64WithCustomInserter(MI, BB);
16420 case X86::EH_SjLj_SetJmp32:
16421 case X86::EH_SjLj_SetJmp64:
16422 return emitEHSjLjSetJmp(MI, BB);
16424 case X86::EH_SjLj_LongJmp32:
16425 case X86::EH_SjLj_LongJmp64:
16426 return emitEHSjLjLongJmp(MI, BB);
16428 case TargetOpcode::STACKMAP:
16429 case TargetOpcode::PATCHPOINT:
16430 return emitPatchPoint(MI, BB);
16432 case X86::VFMADDPDr213r:
16433 case X86::VFMADDPSr213r:
16434 case X86::VFMADDSDr213r:
16435 case X86::VFMADDSSr213r:
16436 case X86::VFMSUBPDr213r:
16437 case X86::VFMSUBPSr213r:
16438 case X86::VFMSUBSDr213r:
16439 case X86::VFMSUBSSr213r:
16440 case X86::VFNMADDPDr213r:
16441 case X86::VFNMADDPSr213r:
16442 case X86::VFNMADDSDr213r:
16443 case X86::VFNMADDSSr213r:
16444 case X86::VFNMSUBPDr213r:
16445 case X86::VFNMSUBPSr213r:
16446 case X86::VFNMSUBSDr213r:
16447 case X86::VFNMSUBSSr213r:
16448 case X86::VFMADDPDr213rY:
16449 case X86::VFMADDPSr213rY:
16450 case X86::VFMSUBPDr213rY:
16451 case X86::VFMSUBPSr213rY:
16452 case X86::VFNMADDPDr213rY:
16453 case X86::VFNMADDPSr213rY:
16454 case X86::VFNMSUBPDr213rY:
16455 case X86::VFNMSUBPSr213rY:
16456 return emitFMA3Instr(MI, BB);
16460 //===----------------------------------------------------------------------===//
16461 // X86 Optimization Hooks
16462 //===----------------------------------------------------------------------===//
16464 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16467 const SelectionDAG &DAG,
16468 unsigned Depth) const {
16469 unsigned BitWidth = KnownZero.getBitWidth();
16470 unsigned Opc = Op.getOpcode();
16471 assert((Opc >= ISD::BUILTIN_OP_END ||
16472 Opc == ISD::INTRINSIC_WO_CHAIN ||
16473 Opc == ISD::INTRINSIC_W_CHAIN ||
16474 Opc == ISD::INTRINSIC_VOID) &&
16475 "Should use MaskedValueIsZero if you don't know whether Op"
16476 " is a target node!");
16478 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16492 // These nodes' second result is a boolean.
16493 if (Op.getResNo() == 0)
16496 case X86ISD::SETCC:
16497 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16499 case ISD::INTRINSIC_WO_CHAIN: {
16500 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16501 unsigned NumLoBits = 0;
16504 case Intrinsic::x86_sse_movmsk_ps:
16505 case Intrinsic::x86_avx_movmsk_ps_256:
16506 case Intrinsic::x86_sse2_movmsk_pd:
16507 case Intrinsic::x86_avx_movmsk_pd_256:
16508 case Intrinsic::x86_mmx_pmovmskb:
16509 case Intrinsic::x86_sse2_pmovmskb_128:
16510 case Intrinsic::x86_avx2_pmovmskb: {
16511 // High bits of movmskp{s|d}, pmovmskb are known zero.
16513 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16514 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16515 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16516 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16517 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16518 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16519 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16520 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16522 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16531 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16532 unsigned Depth) const {
16533 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16534 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16535 return Op.getValueType().getScalarType().getSizeInBits();
16541 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16542 /// node is a GlobalAddress + offset.
16543 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16544 const GlobalValue* &GA,
16545 int64_t &Offset) const {
16546 if (N->getOpcode() == X86ISD::Wrapper) {
16547 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16548 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16549 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16553 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16556 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16557 /// same as extracting the high 128-bit part of 256-bit vector and then
16558 /// inserting the result into the low part of a new 256-bit vector
16559 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16560 EVT VT = SVOp->getValueType(0);
16561 unsigned NumElems = VT.getVectorNumElements();
16563 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16564 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16565 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16566 SVOp->getMaskElt(j) >= 0)
16572 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16573 /// same as extracting the low 128-bit part of 256-bit vector and then
16574 /// inserting the result into the high part of a new 256-bit vector
16575 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16576 EVT VT = SVOp->getValueType(0);
16577 unsigned NumElems = VT.getVectorNumElements();
16579 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16580 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16581 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16582 SVOp->getMaskElt(j) >= 0)
16588 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16589 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16590 TargetLowering::DAGCombinerInfo &DCI,
16591 const X86Subtarget* Subtarget) {
16593 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16594 SDValue V1 = SVOp->getOperand(0);
16595 SDValue V2 = SVOp->getOperand(1);
16596 EVT VT = SVOp->getValueType(0);
16597 unsigned NumElems = VT.getVectorNumElements();
16599 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16600 V2.getOpcode() == ISD::CONCAT_VECTORS) {
16604 // V UNDEF BUILD_VECTOR UNDEF
16606 // CONCAT_VECTOR CONCAT_VECTOR
16609 // RESULT: V + zero extended
16611 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16612 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16613 V1.getOperand(1).getOpcode() != ISD::UNDEF)
16616 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16619 // To match the shuffle mask, the first half of the mask should
16620 // be exactly the first vector, and all the rest a splat with the
16621 // first element of the second one.
16622 for (unsigned i = 0; i != NumElems/2; ++i)
16623 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16624 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16627 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16628 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16629 if (Ld->hasNUsesOfValue(1, 0)) {
16630 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16631 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16633 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16634 array_lengthof(Ops),
16636 Ld->getPointerInfo(),
16637 Ld->getAlignment(),
16638 false/*isVolatile*/, true/*ReadMem*/,
16639 false/*WriteMem*/);
16641 // Make sure the newly-created LOAD is in the same position as Ld in
16642 // terms of dependency. We create a TokenFactor for Ld and ResNode,
16643 // and update uses of Ld's output chain to use the TokenFactor.
16644 if (Ld->hasAnyUseOfValue(1)) {
16645 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16646 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16647 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16648 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16649 SDValue(ResNode.getNode(), 1));
16652 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16656 // Emit a zeroed vector and insert the desired subvector on its
16658 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16659 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16660 return DCI.CombineTo(N, InsV);
16663 //===--------------------------------------------------------------------===//
16664 // Combine some shuffles into subvector extracts and inserts:
16667 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16668 if (isShuffleHigh128VectorInsertLow(SVOp)) {
16669 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16670 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16671 return DCI.CombineTo(N, InsV);
16674 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16675 if (isShuffleLow128VectorInsertHigh(SVOp)) {
16676 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16677 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16678 return DCI.CombineTo(N, InsV);
16684 /// PerformShuffleCombine - Performs several different shuffle combines.
16685 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16686 TargetLowering::DAGCombinerInfo &DCI,
16687 const X86Subtarget *Subtarget) {
16689 EVT VT = N->getValueType(0);
16691 // Don't create instructions with illegal types after legalize types has run.
16692 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16693 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16696 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16697 if (Subtarget->hasFp256() && VT.is256BitVector() &&
16698 N->getOpcode() == ISD::VECTOR_SHUFFLE)
16699 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16701 // Only handle 128 wide vector from here on.
16702 if (!VT.is128BitVector())
16705 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16706 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16707 // consecutive, non-overlapping, and in the right order.
16708 SmallVector<SDValue, 16> Elts;
16709 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16710 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16712 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16715 /// PerformTruncateCombine - Converts truncate operation to
16716 /// a sequence of vector shuffle operations.
16717 /// It is possible when we truncate 256-bit vector to 128-bit vector
16718 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16719 TargetLowering::DAGCombinerInfo &DCI,
16720 const X86Subtarget *Subtarget) {
16724 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16725 /// specific shuffle of a load can be folded into a single element load.
16726 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16727 /// shuffles have been customed lowered so we need to handle those here.
16728 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16729 TargetLowering::DAGCombinerInfo &DCI) {
16730 if (DCI.isBeforeLegalizeOps())
16733 SDValue InVec = N->getOperand(0);
16734 SDValue EltNo = N->getOperand(1);
16736 if (!isa<ConstantSDNode>(EltNo))
16739 EVT VT = InVec.getValueType();
16741 bool HasShuffleIntoBitcast = false;
16742 if (InVec.getOpcode() == ISD::BITCAST) {
16743 // Don't duplicate a load with other uses.
16744 if (!InVec.hasOneUse())
16746 EVT BCVT = InVec.getOperand(0).getValueType();
16747 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16749 InVec = InVec.getOperand(0);
16750 HasShuffleIntoBitcast = true;
16753 if (!isTargetShuffle(InVec.getOpcode()))
16756 // Don't duplicate a load with other uses.
16757 if (!InVec.hasOneUse())
16760 SmallVector<int, 16> ShuffleMask;
16762 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16766 // Select the input vector, guarding against out of range extract vector.
16767 unsigned NumElems = VT.getVectorNumElements();
16768 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16769 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16770 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16771 : InVec.getOperand(1);
16773 // If inputs to shuffle are the same for both ops, then allow 2 uses
16774 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16776 if (LdNode.getOpcode() == ISD::BITCAST) {
16777 // Don't duplicate a load with other uses.
16778 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16781 AllowedUses = 1; // only allow 1 load use if we have a bitcast
16782 LdNode = LdNode.getOperand(0);
16785 if (!ISD::isNormalLoad(LdNode.getNode()))
16788 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16790 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16793 if (HasShuffleIntoBitcast) {
16794 // If there's a bitcast before the shuffle, check if the load type and
16795 // alignment is valid.
16796 unsigned Align = LN0->getAlignment();
16797 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16798 unsigned NewAlign = TLI.getDataLayout()->
16799 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16801 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16805 // All checks match so transform back to vector_shuffle so that DAG combiner
16806 // can finish the job
16809 // Create shuffle node taking into account the case that its a unary shuffle
16810 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16811 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16812 InVec.getOperand(0), Shuffle,
16814 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16815 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16819 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16820 /// generation and convert it from being a bunch of shuffles and extracts
16821 /// to a simple store and scalar loads to extract the elements.
16822 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16823 TargetLowering::DAGCombinerInfo &DCI) {
16824 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16825 if (NewOp.getNode())
16828 SDValue InputVector = N->getOperand(0);
16830 // Detect whether we are trying to convert from mmx to i32 and the bitcast
16831 // from mmx to v2i32 has a single usage.
16832 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16833 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16834 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16835 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16836 N->getValueType(0),
16837 InputVector.getNode()->getOperand(0));
16839 // Only operate on vectors of 4 elements, where the alternative shuffling
16840 // gets to be more expensive.
16841 if (InputVector.getValueType() != MVT::v4i32)
16844 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16845 // single use which is a sign-extend or zero-extend, and all elements are
16847 SmallVector<SDNode *, 4> Uses;
16848 unsigned ExtractedElements = 0;
16849 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16850 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16851 if (UI.getUse().getResNo() != InputVector.getResNo())
16854 SDNode *Extract = *UI;
16855 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16858 if (Extract->getValueType(0) != MVT::i32)
16860 if (!Extract->hasOneUse())
16862 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16863 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16865 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16868 // Record which element was extracted.
16869 ExtractedElements |=
16870 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16872 Uses.push_back(Extract);
16875 // If not all the elements were used, this may not be worthwhile.
16876 if (ExtractedElements != 15)
16879 // Ok, we've now decided to do the transformation.
16880 SDLoc dl(InputVector);
16882 // Store the value to a temporary stack slot.
16883 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16884 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16885 MachinePointerInfo(), false, false, 0);
16887 // Replace each use (extract) with a load of the appropriate element.
16888 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16889 UE = Uses.end(); UI != UE; ++UI) {
16890 SDNode *Extract = *UI;
16892 // cOMpute the element's address.
16893 SDValue Idx = Extract->getOperand(1);
16895 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16896 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16897 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16898 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16900 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16901 StackPtr, OffsetVal);
16903 // Load the scalar.
16904 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16905 ScalarAddr, MachinePointerInfo(),
16906 false, false, false, 0);
16908 // Replace the exact with the load.
16909 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16912 // The replacement was made in place; don't return anything.
16916 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16917 static std::pair<unsigned, bool>
16918 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16919 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16920 if (!VT.isVector())
16921 return std::make_pair(0, false);
16923 bool NeedSplit = false;
16924 switch (VT.getSimpleVT().SimpleTy) {
16925 default: return std::make_pair(0, false);
16929 if (!Subtarget->hasAVX2())
16931 if (!Subtarget->hasAVX())
16932 return std::make_pair(0, false);
16937 if (!Subtarget->hasSSE2())
16938 return std::make_pair(0, false);
16941 // SSE2 has only a small subset of the operations.
16942 bool hasUnsigned = Subtarget->hasSSE41() ||
16943 (Subtarget->hasSSE2() && VT == MVT::v16i8);
16944 bool hasSigned = Subtarget->hasSSE41() ||
16945 (Subtarget->hasSSE2() && VT == MVT::v8i16);
16947 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16950 // Check for x CC y ? x : y.
16951 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16952 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16957 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16960 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16963 Opc = hasSigned ? X86ISD::SMIN : 0; break;
16966 Opc = hasSigned ? X86ISD::SMAX : 0; break;
16968 // Check for x CC y ? y : x -- a min/max with reversed arms.
16969 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16970 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16975 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16978 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16981 Opc = hasSigned ? X86ISD::SMAX : 0; break;
16984 Opc = hasSigned ? X86ISD::SMIN : 0; break;
16988 return std::make_pair(Opc, NeedSplit);
16991 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16993 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16994 TargetLowering::DAGCombinerInfo &DCI,
16995 const X86Subtarget *Subtarget) {
16997 SDValue Cond = N->getOperand(0);
16998 // Get the LHS/RHS of the select.
16999 SDValue LHS = N->getOperand(1);
17000 SDValue RHS = N->getOperand(2);
17001 EVT VT = LHS.getValueType();
17002 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17004 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17005 // instructions match the semantics of the common C idiom x<y?x:y but not
17006 // x<=y?x:y, because of how they handle negative zero (which can be
17007 // ignored in unsafe-math mode).
17008 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17009 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17010 (Subtarget->hasSSE2() ||
17011 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17012 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17014 unsigned Opcode = 0;
17015 // Check for x CC y ? x : y.
17016 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17017 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17021 // Converting this to a min would handle NaNs incorrectly, and swapping
17022 // the operands would cause it to handle comparisons between positive
17023 // and negative zero incorrectly.
17024 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17025 if (!DAG.getTarget().Options.UnsafeFPMath &&
17026 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17028 std::swap(LHS, RHS);
17030 Opcode = X86ISD::FMIN;
17033 // Converting this to a min would handle comparisons between positive
17034 // and negative zero incorrectly.
17035 if (!DAG.getTarget().Options.UnsafeFPMath &&
17036 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17038 Opcode = X86ISD::FMIN;
17041 // Converting this to a min would handle both negative zeros and NaNs
17042 // incorrectly, but we can swap the operands to fix both.
17043 std::swap(LHS, RHS);
17047 Opcode = X86ISD::FMIN;
17051 // Converting this to a max would handle comparisons between positive
17052 // and negative zero incorrectly.
17053 if (!DAG.getTarget().Options.UnsafeFPMath &&
17054 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17056 Opcode = X86ISD::FMAX;
17059 // Converting this to a max would handle NaNs incorrectly, and swapping
17060 // the operands would cause it to handle comparisons between positive
17061 // and negative zero incorrectly.
17062 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17063 if (!DAG.getTarget().Options.UnsafeFPMath &&
17064 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17066 std::swap(LHS, RHS);
17068 Opcode = X86ISD::FMAX;
17071 // Converting this to a max would handle both negative zeros and NaNs
17072 // incorrectly, but we can swap the operands to fix both.
17073 std::swap(LHS, RHS);
17077 Opcode = X86ISD::FMAX;
17080 // Check for x CC y ? y : x -- a min/max with reversed arms.
17081 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17082 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17086 // Converting this to a min would handle comparisons between positive
17087 // and negative zero incorrectly, and swapping the operands would
17088 // cause it to handle NaNs incorrectly.
17089 if (!DAG.getTarget().Options.UnsafeFPMath &&
17090 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17091 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17093 std::swap(LHS, RHS);
17095 Opcode = X86ISD::FMIN;
17098 // Converting this to a min would handle NaNs incorrectly.
17099 if (!DAG.getTarget().Options.UnsafeFPMath &&
17100 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17102 Opcode = X86ISD::FMIN;
17105 // Converting this to a min would handle both negative zeros and NaNs
17106 // incorrectly, but we can swap the operands to fix both.
17107 std::swap(LHS, RHS);
17111 Opcode = X86ISD::FMIN;
17115 // Converting this to a max would handle NaNs incorrectly.
17116 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17118 Opcode = X86ISD::FMAX;
17121 // Converting this to a max would handle comparisons between positive
17122 // and negative zero incorrectly, and swapping the operands would
17123 // cause it to handle NaNs incorrectly.
17124 if (!DAG.getTarget().Options.UnsafeFPMath &&
17125 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17126 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17128 std::swap(LHS, RHS);
17130 Opcode = X86ISD::FMAX;
17133 // Converting this to a max would handle both negative zeros and NaNs
17134 // incorrectly, but we can swap the operands to fix both.
17135 std::swap(LHS, RHS);
17139 Opcode = X86ISD::FMAX;
17145 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17148 EVT CondVT = Cond.getValueType();
17149 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17150 CondVT.getVectorElementType() == MVT::i1) {
17151 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17152 // lowering on AVX-512. In this case we convert it to
17153 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17154 // The same situation for all 128 and 256-bit vectors of i8 and i16
17155 EVT OpVT = LHS.getValueType();
17156 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17157 (OpVT.getVectorElementType() == MVT::i8 ||
17158 OpVT.getVectorElementType() == MVT::i16)) {
17159 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17160 DCI.AddToWorklist(Cond.getNode());
17161 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17164 // If this is a select between two integer constants, try to do some
17166 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17167 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17168 // Don't do this for crazy integer types.
17169 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17170 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17171 // so that TrueC (the true value) is larger than FalseC.
17172 bool NeedsCondInvert = false;
17174 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17175 // Efficiently invertible.
17176 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17177 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17178 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17179 NeedsCondInvert = true;
17180 std::swap(TrueC, FalseC);
17183 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17184 if (FalseC->getAPIntValue() == 0 &&
17185 TrueC->getAPIntValue().isPowerOf2()) {
17186 if (NeedsCondInvert) // Invert the condition if needed.
17187 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17188 DAG.getConstant(1, Cond.getValueType()));
17190 // Zero extend the condition if needed.
17191 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17193 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17194 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17195 DAG.getConstant(ShAmt, MVT::i8));
17198 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17199 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17200 if (NeedsCondInvert) // Invert the condition if needed.
17201 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17202 DAG.getConstant(1, Cond.getValueType()));
17204 // Zero extend the condition if needed.
17205 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17206 FalseC->getValueType(0), Cond);
17207 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17208 SDValue(FalseC, 0));
17211 // Optimize cases that will turn into an LEA instruction. This requires
17212 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17213 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17214 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17215 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17217 bool isFastMultiplier = false;
17219 switch ((unsigned char)Diff) {
17221 case 1: // result = add base, cond
17222 case 2: // result = lea base( , cond*2)
17223 case 3: // result = lea base(cond, cond*2)
17224 case 4: // result = lea base( , cond*4)
17225 case 5: // result = lea base(cond, cond*4)
17226 case 8: // result = lea base( , cond*8)
17227 case 9: // result = lea base(cond, cond*8)
17228 isFastMultiplier = true;
17233 if (isFastMultiplier) {
17234 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17235 if (NeedsCondInvert) // Invert the condition if needed.
17236 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17237 DAG.getConstant(1, Cond.getValueType()));
17239 // Zero extend the condition if needed.
17240 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17242 // Scale the condition by the difference.
17244 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17245 DAG.getConstant(Diff, Cond.getValueType()));
17247 // Add the base if non-zero.
17248 if (FalseC->getAPIntValue() != 0)
17249 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17250 SDValue(FalseC, 0));
17257 // Canonicalize max and min:
17258 // (x > y) ? x : y -> (x >= y) ? x : y
17259 // (x < y) ? x : y -> (x <= y) ? x : y
17260 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17261 // the need for an extra compare
17262 // against zero. e.g.
17263 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17265 // testl %edi, %edi
17267 // cmovgl %edi, %eax
17271 // cmovsl %eax, %edi
17272 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17273 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17274 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17275 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17280 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17281 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17282 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17283 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17288 // Early exit check
17289 if (!TLI.isTypeLegal(VT))
17292 // Match VSELECTs into subs with unsigned saturation.
17293 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17294 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17295 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17296 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17297 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17299 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17300 // left side invert the predicate to simplify logic below.
17302 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17304 CC = ISD::getSetCCInverse(CC, true);
17305 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17309 if (Other.getNode() && Other->getNumOperands() == 2 &&
17310 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17311 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17312 SDValue CondRHS = Cond->getOperand(1);
17314 // Look for a general sub with unsigned saturation first.
17315 // x >= y ? x-y : 0 --> subus x, y
17316 // x > y ? x-y : 0 --> subus x, y
17317 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17318 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17319 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17321 // If the RHS is a constant we have to reverse the const canonicalization.
17322 // x > C-1 ? x+-C : 0 --> subus x, C
17323 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17324 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17325 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17326 if (CondRHS.getConstantOperandVal(0) == -A-1)
17327 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17328 DAG.getConstant(-A, VT));
17331 // Another special case: If C was a sign bit, the sub has been
17332 // canonicalized into a xor.
17333 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17334 // it's safe to decanonicalize the xor?
17335 // x s< 0 ? x^C : 0 --> subus x, C
17336 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17337 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17338 isSplatVector(OpRHS.getNode())) {
17339 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17341 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17346 // Try to match a min/max vector operation.
17347 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17348 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17349 unsigned Opc = ret.first;
17350 bool NeedSplit = ret.second;
17352 if (Opc && NeedSplit) {
17353 unsigned NumElems = VT.getVectorNumElements();
17354 // Extract the LHS vectors
17355 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17356 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17358 // Extract the RHS vectors
17359 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17360 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17362 // Create min/max for each subvector
17363 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17364 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17366 // Merge the result
17367 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17369 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17372 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17373 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17374 // Check if SETCC has already been promoted
17375 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17376 // Check that condition value type matches vselect operand type
17379 assert(Cond.getValueType().isVector() &&
17380 "vector select expects a vector selector!");
17382 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17383 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17385 if (!TValIsAllOnes && !FValIsAllZeros) {
17386 // Try invert the condition if true value is not all 1s and false value
17388 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17389 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17391 if (TValIsAllZeros || FValIsAllOnes) {
17392 SDValue CC = Cond.getOperand(2);
17393 ISD::CondCode NewCC =
17394 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17395 Cond.getOperand(0).getValueType().isInteger());
17396 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17397 std::swap(LHS, RHS);
17398 TValIsAllOnes = FValIsAllOnes;
17399 FValIsAllZeros = TValIsAllZeros;
17403 if (TValIsAllOnes || FValIsAllZeros) {
17406 if (TValIsAllOnes && FValIsAllZeros)
17408 else if (TValIsAllOnes)
17409 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17410 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17411 else if (FValIsAllZeros)
17412 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17413 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17415 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17419 // Try to fold this VSELECT into a MOVSS/MOVSD
17420 if (N->getOpcode() == ISD::VSELECT &&
17421 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17422 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17423 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17424 bool CanFold = false;
17425 unsigned NumElems = Cond.getNumOperands();
17429 if (isZero(Cond.getOperand(0))) {
17432 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17433 // fold (vselect <0,-1> -> (movsd A, B)
17434 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17435 CanFold = isAllOnes(Cond.getOperand(i));
17436 } else if (isAllOnes(Cond.getOperand(0))) {
17440 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17441 // fold (vselect <-1,0> -> (movsd B, A)
17442 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17443 CanFold = isZero(Cond.getOperand(i));
17447 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17448 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17449 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17452 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17453 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17454 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17455 // (v2i64 (bitcast B)))))
17457 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17458 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17459 // (v2f64 (bitcast B)))))
17461 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17462 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17463 // (v2i64 (bitcast A)))))
17465 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17466 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17467 // (v2f64 (bitcast A)))))
17469 CanFold = (isZero(Cond.getOperand(0)) &&
17470 isZero(Cond.getOperand(1)) &&
17471 isAllOnes(Cond.getOperand(2)) &&
17472 isAllOnes(Cond.getOperand(3)));
17474 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17475 isAllOnes(Cond.getOperand(1)) &&
17476 isZero(Cond.getOperand(2)) &&
17477 isZero(Cond.getOperand(3))) {
17479 std::swap(LHS, RHS);
17483 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17484 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17485 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17486 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17488 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17494 // If we know that this node is legal then we know that it is going to be
17495 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17496 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17497 // to simplify previous instructions.
17498 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17499 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17500 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17502 // Don't optimize vector selects that map to mask-registers.
17506 // Check all uses of that condition operand to check whether it will be
17507 // consumed by non-BLEND instructions, which may depend on all bits are set
17509 for (SDNode::use_iterator I = Cond->use_begin(),
17510 E = Cond->use_end(); I != E; ++I)
17511 if (I->getOpcode() != ISD::VSELECT)
17512 // TODO: Add other opcodes eventually lowered into BLEND.
17515 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17516 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17518 APInt KnownZero, KnownOne;
17519 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17520 DCI.isBeforeLegalizeOps());
17521 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17522 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17523 DCI.CommitTargetLoweringOpt(TLO);
17529 // Check whether a boolean test is testing a boolean value generated by
17530 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17533 // Simplify the following patterns:
17534 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17535 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17536 // to (Op EFLAGS Cond)
17538 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17539 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17540 // to (Op EFLAGS !Cond)
17542 // where Op could be BRCOND or CMOV.
17544 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17545 // Quit if not CMP and SUB with its value result used.
17546 if (Cmp.getOpcode() != X86ISD::CMP &&
17547 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17550 // Quit if not used as a boolean value.
17551 if (CC != X86::COND_E && CC != X86::COND_NE)
17554 // Check CMP operands. One of them should be 0 or 1 and the other should be
17555 // an SetCC or extended from it.
17556 SDValue Op1 = Cmp.getOperand(0);
17557 SDValue Op2 = Cmp.getOperand(1);
17560 const ConstantSDNode* C = 0;
17561 bool needOppositeCond = (CC == X86::COND_E);
17562 bool checkAgainstTrue = false; // Is it a comparison against 1?
17564 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17566 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17568 else // Quit if all operands are not constants.
17571 if (C->getZExtValue() == 1) {
17572 needOppositeCond = !needOppositeCond;
17573 checkAgainstTrue = true;
17574 } else if (C->getZExtValue() != 0)
17575 // Quit if the constant is neither 0 or 1.
17578 bool truncatedToBoolWithAnd = false;
17579 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17580 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17581 SetCC.getOpcode() == ISD::TRUNCATE ||
17582 SetCC.getOpcode() == ISD::AND) {
17583 if (SetCC.getOpcode() == ISD::AND) {
17585 ConstantSDNode *CS;
17586 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17587 CS->getZExtValue() == 1)
17589 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17590 CS->getZExtValue() == 1)
17594 SetCC = SetCC.getOperand(OpIdx);
17595 truncatedToBoolWithAnd = true;
17597 SetCC = SetCC.getOperand(0);
17600 switch (SetCC.getOpcode()) {
17601 case X86ISD::SETCC_CARRY:
17602 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17603 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17604 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17605 // truncated to i1 using 'and'.
17606 if (checkAgainstTrue && !truncatedToBoolWithAnd)
17608 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17609 "Invalid use of SETCC_CARRY!");
17611 case X86ISD::SETCC:
17612 // Set the condition code or opposite one if necessary.
17613 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17614 if (needOppositeCond)
17615 CC = X86::GetOppositeBranchCondition(CC);
17616 return SetCC.getOperand(1);
17617 case X86ISD::CMOV: {
17618 // Check whether false/true value has canonical one, i.e. 0 or 1.
17619 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17620 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17621 // Quit if true value is not a constant.
17624 // Quit if false value is not a constant.
17626 SDValue Op = SetCC.getOperand(0);
17627 // Skip 'zext' or 'trunc' node.
17628 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17629 Op.getOpcode() == ISD::TRUNCATE)
17630 Op = Op.getOperand(0);
17631 // A special case for rdrand/rdseed, where 0 is set if false cond is
17633 if ((Op.getOpcode() != X86ISD::RDRAND &&
17634 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17637 // Quit if false value is not the constant 0 or 1.
17638 bool FValIsFalse = true;
17639 if (FVal && FVal->getZExtValue() != 0) {
17640 if (FVal->getZExtValue() != 1)
17642 // If FVal is 1, opposite cond is needed.
17643 needOppositeCond = !needOppositeCond;
17644 FValIsFalse = false;
17646 // Quit if TVal is not the constant opposite of FVal.
17647 if (FValIsFalse && TVal->getZExtValue() != 1)
17649 if (!FValIsFalse && TVal->getZExtValue() != 0)
17651 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17652 if (needOppositeCond)
17653 CC = X86::GetOppositeBranchCondition(CC);
17654 return SetCC.getOperand(3);
17661 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17662 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17663 TargetLowering::DAGCombinerInfo &DCI,
17664 const X86Subtarget *Subtarget) {
17667 // If the flag operand isn't dead, don't touch this CMOV.
17668 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17671 SDValue FalseOp = N->getOperand(0);
17672 SDValue TrueOp = N->getOperand(1);
17673 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17674 SDValue Cond = N->getOperand(3);
17676 if (CC == X86::COND_E || CC == X86::COND_NE) {
17677 switch (Cond.getOpcode()) {
17681 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17682 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17683 return (CC == X86::COND_E) ? FalseOp : TrueOp;
17689 Flags = checkBoolTestSetCCCombine(Cond, CC);
17690 if (Flags.getNode() &&
17691 // Extra check as FCMOV only supports a subset of X86 cond.
17692 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17693 SDValue Ops[] = { FalseOp, TrueOp,
17694 DAG.getConstant(CC, MVT::i8), Flags };
17695 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17696 Ops, array_lengthof(Ops));
17699 // If this is a select between two integer constants, try to do some
17700 // optimizations. Note that the operands are ordered the opposite of SELECT
17702 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17703 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17704 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17705 // larger than FalseC (the false value).
17706 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17707 CC = X86::GetOppositeBranchCondition(CC);
17708 std::swap(TrueC, FalseC);
17709 std::swap(TrueOp, FalseOp);
17712 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
17713 // This is efficient for any integer data type (including i8/i16) and
17715 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17716 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17717 DAG.getConstant(CC, MVT::i8), Cond);
17719 // Zero extend the condition if needed.
17720 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17722 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17723 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17724 DAG.getConstant(ShAmt, MVT::i8));
17725 if (N->getNumValues() == 2) // Dead flag value?
17726 return DCI.CombineTo(N, Cond, SDValue());
17730 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
17731 // for any integer data type, including i8/i16.
17732 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17733 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17734 DAG.getConstant(CC, MVT::i8), Cond);
17736 // Zero extend the condition if needed.
17737 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17738 FalseC->getValueType(0), Cond);
17739 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17740 SDValue(FalseC, 0));
17742 if (N->getNumValues() == 2) // Dead flag value?
17743 return DCI.CombineTo(N, Cond, SDValue());
17747 // Optimize cases that will turn into an LEA instruction. This requires
17748 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17749 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17750 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17751 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17753 bool isFastMultiplier = false;
17755 switch ((unsigned char)Diff) {
17757 case 1: // result = add base, cond
17758 case 2: // result = lea base( , cond*2)
17759 case 3: // result = lea base(cond, cond*2)
17760 case 4: // result = lea base( , cond*4)
17761 case 5: // result = lea base(cond, cond*4)
17762 case 8: // result = lea base( , cond*8)
17763 case 9: // result = lea base(cond, cond*8)
17764 isFastMultiplier = true;
17769 if (isFastMultiplier) {
17770 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17771 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17772 DAG.getConstant(CC, MVT::i8), Cond);
17773 // Zero extend the condition if needed.
17774 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17776 // Scale the condition by the difference.
17778 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17779 DAG.getConstant(Diff, Cond.getValueType()));
17781 // Add the base if non-zero.
17782 if (FalseC->getAPIntValue() != 0)
17783 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17784 SDValue(FalseC, 0));
17785 if (N->getNumValues() == 2) // Dead flag value?
17786 return DCI.CombineTo(N, Cond, SDValue());
17793 // Handle these cases:
17794 // (select (x != c), e, c) -> select (x != c), e, x),
17795 // (select (x == c), c, e) -> select (x == c), x, e)
17796 // where the c is an integer constant, and the "select" is the combination
17797 // of CMOV and CMP.
17799 // The rationale for this change is that the conditional-move from a constant
17800 // needs two instructions, however, conditional-move from a register needs
17801 // only one instruction.
17803 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17804 // some instruction-combining opportunities. This opt needs to be
17805 // postponed as late as possible.
17807 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17808 // the DCI.xxxx conditions are provided to postpone the optimization as
17809 // late as possible.
17811 ConstantSDNode *CmpAgainst = 0;
17812 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17813 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17814 !isa<ConstantSDNode>(Cond.getOperand(0))) {
17816 if (CC == X86::COND_NE &&
17817 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17818 CC = X86::GetOppositeBranchCondition(CC);
17819 std::swap(TrueOp, FalseOp);
17822 if (CC == X86::COND_E &&
17823 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17824 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17825 DAG.getConstant(CC, MVT::i8), Cond };
17826 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17827 array_lengthof(Ops));
17835 /// PerformMulCombine - Optimize a single multiply with constant into two
17836 /// in order to implement it with two cheaper instructions, e.g.
17837 /// LEA + SHL, LEA + LEA.
17838 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17839 TargetLowering::DAGCombinerInfo &DCI) {
17840 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17843 EVT VT = N->getValueType(0);
17844 if (VT != MVT::i64)
17847 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17850 uint64_t MulAmt = C->getZExtValue();
17851 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17854 uint64_t MulAmt1 = 0;
17855 uint64_t MulAmt2 = 0;
17856 if ((MulAmt % 9) == 0) {
17858 MulAmt2 = MulAmt / 9;
17859 } else if ((MulAmt % 5) == 0) {
17861 MulAmt2 = MulAmt / 5;
17862 } else if ((MulAmt % 3) == 0) {
17864 MulAmt2 = MulAmt / 3;
17867 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17870 if (isPowerOf2_64(MulAmt2) &&
17871 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17872 // If second multiplifer is pow2, issue it first. We want the multiply by
17873 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17875 std::swap(MulAmt1, MulAmt2);
17878 if (isPowerOf2_64(MulAmt1))
17879 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17880 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17882 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17883 DAG.getConstant(MulAmt1, VT));
17885 if (isPowerOf2_64(MulAmt2))
17886 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17887 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17889 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17890 DAG.getConstant(MulAmt2, VT));
17892 // Do not add new nodes to DAG combiner worklist.
17893 DCI.CombineTo(N, NewMul, false);
17898 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17899 SDValue N0 = N->getOperand(0);
17900 SDValue N1 = N->getOperand(1);
17901 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17902 EVT VT = N0.getValueType();
17904 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17905 // since the result of setcc_c is all zero's or all ones.
17906 if (VT.isInteger() && !VT.isVector() &&
17907 N1C && N0.getOpcode() == ISD::AND &&
17908 N0.getOperand(1).getOpcode() == ISD::Constant) {
17909 SDValue N00 = N0.getOperand(0);
17910 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17911 ((N00.getOpcode() == ISD::ANY_EXTEND ||
17912 N00.getOpcode() == ISD::ZERO_EXTEND) &&
17913 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17914 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17915 APInt ShAmt = N1C->getAPIntValue();
17916 Mask = Mask.shl(ShAmt);
17918 return DAG.getNode(ISD::AND, SDLoc(N), VT,
17919 N00, DAG.getConstant(Mask, VT));
17923 // Hardware support for vector shifts is sparse which makes us scalarize the
17924 // vector operations in many cases. Also, on sandybridge ADD is faster than
17926 // (shl V, 1) -> add V,V
17927 if (isSplatVector(N1.getNode())) {
17928 assert(N0.getValueType().isVector() && "Invalid vector shift type");
17929 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17930 // We shift all of the values by one. In many cases we do not have
17931 // hardware support for this operation. This is better expressed as an ADD
17933 if (N1C && (1 == N1C->getZExtValue())) {
17934 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17941 /// \brief Returns a vector of 0s if the node in input is a vector logical
17942 /// shift by a constant amount which is known to be bigger than or equal
17943 /// to the vector element size in bits.
17944 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17945 const X86Subtarget *Subtarget) {
17946 EVT VT = N->getValueType(0);
17948 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17949 (!Subtarget->hasInt256() ||
17950 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17953 SDValue Amt = N->getOperand(1);
17955 if (isSplatVector(Amt.getNode())) {
17956 SDValue SclrAmt = Amt->getOperand(0);
17957 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17958 APInt ShiftAmt = C->getAPIntValue();
17959 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17961 // SSE2/AVX2 logical shifts always return a vector of 0s
17962 // if the shift amount is bigger than or equal to
17963 // the element size. The constant shift amount will be
17964 // encoded as a 8-bit immediate.
17965 if (ShiftAmt.trunc(8).uge(MaxAmount))
17966 return getZeroVector(VT, Subtarget, DAG, DL);
17973 /// PerformShiftCombine - Combine shifts.
17974 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17975 TargetLowering::DAGCombinerInfo &DCI,
17976 const X86Subtarget *Subtarget) {
17977 if (N->getOpcode() == ISD::SHL) {
17978 SDValue V = PerformSHLCombine(N, DAG);
17979 if (V.getNode()) return V;
17982 if (N->getOpcode() != ISD::SRA) {
17983 // Try to fold this logical shift into a zero vector.
17984 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17985 if (V.getNode()) return V;
17991 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
17992 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17993 // and friends. Likewise for OR -> CMPNEQSS.
17994 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17995 TargetLowering::DAGCombinerInfo &DCI,
17996 const X86Subtarget *Subtarget) {
17999 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18000 // we're requiring SSE2 for both.
18001 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18002 SDValue N0 = N->getOperand(0);
18003 SDValue N1 = N->getOperand(1);
18004 SDValue CMP0 = N0->getOperand(1);
18005 SDValue CMP1 = N1->getOperand(1);
18008 // The SETCCs should both refer to the same CMP.
18009 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18012 SDValue CMP00 = CMP0->getOperand(0);
18013 SDValue CMP01 = CMP0->getOperand(1);
18014 EVT VT = CMP00.getValueType();
18016 if (VT == MVT::f32 || VT == MVT::f64) {
18017 bool ExpectingFlags = false;
18018 // Check for any users that want flags:
18019 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18020 !ExpectingFlags && UI != UE; ++UI)
18021 switch (UI->getOpcode()) {
18026 ExpectingFlags = true;
18028 case ISD::CopyToReg:
18029 case ISD::SIGN_EXTEND:
18030 case ISD::ZERO_EXTEND:
18031 case ISD::ANY_EXTEND:
18035 if (!ExpectingFlags) {
18036 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18037 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18039 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18040 X86::CondCode tmp = cc0;
18045 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18046 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18047 // FIXME: need symbolic constants for these magic numbers.
18048 // See X86ATTInstPrinter.cpp:printSSECC().
18049 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18050 if (Subtarget->hasAVX512()) {
18051 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18052 CMP01, DAG.getConstant(x86cc, MVT::i8));
18053 if (N->getValueType(0) != MVT::i1)
18054 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18058 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18059 CMP00.getValueType(), CMP00, CMP01,
18060 DAG.getConstant(x86cc, MVT::i8));
18062 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18063 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18065 if (is64BitFP && !Subtarget->is64Bit()) {
18066 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18067 // 64-bit integer, since that's not a legal type. Since
18068 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18069 // bits, but can do this little dance to extract the lowest 32 bits
18070 // and work with those going forward.
18071 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18073 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18075 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18076 Vector32, DAG.getIntPtrConstant(0));
18080 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18081 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18082 DAG.getConstant(1, IntVT));
18083 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18084 return OneBitOfTruth;
18092 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18093 /// so it can be folded inside ANDNP.
18094 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18095 EVT VT = N->getValueType(0);
18097 // Match direct AllOnes for 128 and 256-bit vectors
18098 if (ISD::isBuildVectorAllOnes(N))
18101 // Look through a bit convert.
18102 if (N->getOpcode() == ISD::BITCAST)
18103 N = N->getOperand(0).getNode();
18105 // Sometimes the operand may come from a insert_subvector building a 256-bit
18107 if (VT.is256BitVector() &&
18108 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18109 SDValue V1 = N->getOperand(0);
18110 SDValue V2 = N->getOperand(1);
18112 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18113 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18114 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18115 ISD::isBuildVectorAllOnes(V2.getNode()))
18122 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18123 // register. In most cases we actually compare or select YMM-sized registers
18124 // and mixing the two types creates horrible code. This method optimizes
18125 // some of the transition sequences.
18126 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18127 TargetLowering::DAGCombinerInfo &DCI,
18128 const X86Subtarget *Subtarget) {
18129 EVT VT = N->getValueType(0);
18130 if (!VT.is256BitVector())
18133 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18134 N->getOpcode() == ISD::ZERO_EXTEND ||
18135 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18137 SDValue Narrow = N->getOperand(0);
18138 EVT NarrowVT = Narrow->getValueType(0);
18139 if (!NarrowVT.is128BitVector())
18142 if (Narrow->getOpcode() != ISD::XOR &&
18143 Narrow->getOpcode() != ISD::AND &&
18144 Narrow->getOpcode() != ISD::OR)
18147 SDValue N0 = Narrow->getOperand(0);
18148 SDValue N1 = Narrow->getOperand(1);
18151 // The Left side has to be a trunc.
18152 if (N0.getOpcode() != ISD::TRUNCATE)
18155 // The type of the truncated inputs.
18156 EVT WideVT = N0->getOperand(0)->getValueType(0);
18160 // The right side has to be a 'trunc' or a constant vector.
18161 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18162 bool RHSConst = (isSplatVector(N1.getNode()) &&
18163 isa<ConstantSDNode>(N1->getOperand(0)));
18164 if (!RHSTrunc && !RHSConst)
18167 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18169 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18172 // Set N0 and N1 to hold the inputs to the new wide operation.
18173 N0 = N0->getOperand(0);
18175 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18176 N1->getOperand(0));
18177 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18178 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18179 } else if (RHSTrunc) {
18180 N1 = N1->getOperand(0);
18183 // Generate the wide operation.
18184 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18185 unsigned Opcode = N->getOpcode();
18187 case ISD::ANY_EXTEND:
18189 case ISD::ZERO_EXTEND: {
18190 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18191 APInt Mask = APInt::getAllOnesValue(InBits);
18192 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18193 return DAG.getNode(ISD::AND, DL, VT,
18194 Op, DAG.getConstant(Mask, VT));
18196 case ISD::SIGN_EXTEND:
18197 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18198 Op, DAG.getValueType(NarrowVT));
18200 llvm_unreachable("Unexpected opcode");
18204 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18205 TargetLowering::DAGCombinerInfo &DCI,
18206 const X86Subtarget *Subtarget) {
18207 EVT VT = N->getValueType(0);
18208 if (DCI.isBeforeLegalizeOps())
18211 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18215 // Create BEXTR and BZHI instructions
18216 // BZHI is X & ((1 << Y) - 1)
18217 // BEXTR is ((X >> imm) & (2**size-1))
18218 if (VT == MVT::i32 || VT == MVT::i64) {
18219 SDValue N0 = N->getOperand(0);
18220 SDValue N1 = N->getOperand(1);
18223 if (Subtarget->hasBMI2()) {
18224 // Check for (and (add (shl 1, Y), -1), X)
18225 if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
18226 SDValue N00 = N0.getOperand(0);
18227 if (N00.getOpcode() == ISD::SHL) {
18228 SDValue N001 = N00.getOperand(1);
18229 assert(N001.getValueType() == MVT::i8 && "unexpected type");
18230 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
18231 if (C && C->getZExtValue() == 1)
18232 return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
18236 // Check for (and X, (add (shl 1, Y), -1))
18237 if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
18238 SDValue N10 = N1.getOperand(0);
18239 if (N10.getOpcode() == ISD::SHL) {
18240 SDValue N101 = N10.getOperand(1);
18241 assert(N101.getValueType() == MVT::i8 && "unexpected type");
18242 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
18243 if (C && C->getZExtValue() == 1)
18244 return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
18249 // Check for BEXTR.
18250 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18251 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18252 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18253 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18254 if (MaskNode && ShiftNode) {
18255 uint64_t Mask = MaskNode->getZExtValue();
18256 uint64_t Shift = ShiftNode->getZExtValue();
18257 if (isMask_64(Mask)) {
18258 uint64_t MaskSize = CountPopulation_64(Mask);
18259 if (Shift + MaskSize <= VT.getSizeInBits())
18260 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18261 DAG.getConstant(Shift | (MaskSize << 8), VT));
18269 // Want to form ANDNP nodes:
18270 // 1) In the hopes of then easily combining them with OR and AND nodes
18271 // to form PBLEND/PSIGN.
18272 // 2) To match ANDN packed intrinsics
18273 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18276 SDValue N0 = N->getOperand(0);
18277 SDValue N1 = N->getOperand(1);
18280 // Check LHS for vnot
18281 if (N0.getOpcode() == ISD::XOR &&
18282 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18283 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18284 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18286 // Check RHS for vnot
18287 if (N1.getOpcode() == ISD::XOR &&
18288 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18289 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18290 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18295 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18296 TargetLowering::DAGCombinerInfo &DCI,
18297 const X86Subtarget *Subtarget) {
18298 if (DCI.isBeforeLegalizeOps())
18301 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18305 SDValue N0 = N->getOperand(0);
18306 SDValue N1 = N->getOperand(1);
18307 EVT VT = N->getValueType(0);
18309 // look for psign/blend
18310 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18311 if (!Subtarget->hasSSSE3() ||
18312 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18315 // Canonicalize pandn to RHS
18316 if (N0.getOpcode() == X86ISD::ANDNP)
18318 // or (and (m, y), (pandn m, x))
18319 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18320 SDValue Mask = N1.getOperand(0);
18321 SDValue X = N1.getOperand(1);
18323 if (N0.getOperand(0) == Mask)
18324 Y = N0.getOperand(1);
18325 if (N0.getOperand(1) == Mask)
18326 Y = N0.getOperand(0);
18328 // Check to see if the mask appeared in both the AND and ANDNP and
18332 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18333 // Look through mask bitcast.
18334 if (Mask.getOpcode() == ISD::BITCAST)
18335 Mask = Mask.getOperand(0);
18336 if (X.getOpcode() == ISD::BITCAST)
18337 X = X.getOperand(0);
18338 if (Y.getOpcode() == ISD::BITCAST)
18339 Y = Y.getOperand(0);
18341 EVT MaskVT = Mask.getValueType();
18343 // Validate that the Mask operand is a vector sra node.
18344 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18345 // there is no psrai.b
18346 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18347 unsigned SraAmt = ~0;
18348 if (Mask.getOpcode() == ISD::SRA) {
18349 SDValue Amt = Mask.getOperand(1);
18350 if (isSplatVector(Amt.getNode())) {
18351 SDValue SclrAmt = Amt->getOperand(0);
18352 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18353 SraAmt = C->getZExtValue();
18355 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18356 SDValue SraC = Mask.getOperand(1);
18357 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18359 if ((SraAmt + 1) != EltBits)
18364 // Now we know we at least have a plendvb with the mask val. See if
18365 // we can form a psignb/w/d.
18366 // psign = x.type == y.type == mask.type && y = sub(0, x);
18367 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18368 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18369 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18370 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18371 "Unsupported VT for PSIGN");
18372 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18373 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18375 // PBLENDVB only available on SSE 4.1
18376 if (!Subtarget->hasSSE41())
18379 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18381 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18382 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18383 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18384 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18385 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18389 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18392 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18393 MachineFunction &MF = DAG.getMachineFunction();
18394 bool OptForSize = MF.getFunction()->getAttributes().
18395 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18397 // SHLD/SHRD instructions have lower register pressure, but on some
18398 // platforms they have higher latency than the equivalent
18399 // series of shifts/or that would otherwise be generated.
18400 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18401 // have higher latencies and we are not optimizing for size.
18402 if (!OptForSize && Subtarget->isSHLDSlow())
18405 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18407 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18409 if (!N0.hasOneUse() || !N1.hasOneUse())
18412 SDValue ShAmt0 = N0.getOperand(1);
18413 if (ShAmt0.getValueType() != MVT::i8)
18415 SDValue ShAmt1 = N1.getOperand(1);
18416 if (ShAmt1.getValueType() != MVT::i8)
18418 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18419 ShAmt0 = ShAmt0.getOperand(0);
18420 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18421 ShAmt1 = ShAmt1.getOperand(0);
18424 unsigned Opc = X86ISD::SHLD;
18425 SDValue Op0 = N0.getOperand(0);
18426 SDValue Op1 = N1.getOperand(0);
18427 if (ShAmt0.getOpcode() == ISD::SUB) {
18428 Opc = X86ISD::SHRD;
18429 std::swap(Op0, Op1);
18430 std::swap(ShAmt0, ShAmt1);
18433 unsigned Bits = VT.getSizeInBits();
18434 if (ShAmt1.getOpcode() == ISD::SUB) {
18435 SDValue Sum = ShAmt1.getOperand(0);
18436 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18437 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18438 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18439 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18440 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18441 return DAG.getNode(Opc, DL, VT,
18443 DAG.getNode(ISD::TRUNCATE, DL,
18446 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18447 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18449 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18450 return DAG.getNode(Opc, DL, VT,
18451 N0.getOperand(0), N1.getOperand(0),
18452 DAG.getNode(ISD::TRUNCATE, DL,
18459 // Generate NEG and CMOV for integer abs.
18460 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18461 EVT VT = N->getValueType(0);
18463 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18464 // 8-bit integer abs to NEG and CMOV.
18465 if (VT.isInteger() && VT.getSizeInBits() == 8)
18468 SDValue N0 = N->getOperand(0);
18469 SDValue N1 = N->getOperand(1);
18472 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18473 // and change it to SUB and CMOV.
18474 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18475 N0.getOpcode() == ISD::ADD &&
18476 N0.getOperand(1) == N1 &&
18477 N1.getOpcode() == ISD::SRA &&
18478 N1.getOperand(0) == N0.getOperand(0))
18479 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18480 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18481 // Generate SUB & CMOV.
18482 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18483 DAG.getConstant(0, VT), N0.getOperand(0));
18485 SDValue Ops[] = { N0.getOperand(0), Neg,
18486 DAG.getConstant(X86::COND_GE, MVT::i8),
18487 SDValue(Neg.getNode(), 1) };
18488 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18489 Ops, array_lengthof(Ops));
18494 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18495 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18496 TargetLowering::DAGCombinerInfo &DCI,
18497 const X86Subtarget *Subtarget) {
18498 if (DCI.isBeforeLegalizeOps())
18501 if (Subtarget->hasCMov()) {
18502 SDValue RV = performIntegerAbsCombine(N, DAG);
18510 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18511 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18512 TargetLowering::DAGCombinerInfo &DCI,
18513 const X86Subtarget *Subtarget) {
18514 LoadSDNode *Ld = cast<LoadSDNode>(N);
18515 EVT RegVT = Ld->getValueType(0);
18516 EVT MemVT = Ld->getMemoryVT();
18518 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18519 unsigned RegSz = RegVT.getSizeInBits();
18521 // On Sandybridge unaligned 256bit loads are inefficient.
18522 ISD::LoadExtType Ext = Ld->getExtensionType();
18523 unsigned Alignment = Ld->getAlignment();
18524 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18525 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18526 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18527 unsigned NumElems = RegVT.getVectorNumElements();
18531 SDValue Ptr = Ld->getBasePtr();
18532 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18534 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18536 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18537 Ld->getPointerInfo(), Ld->isVolatile(),
18538 Ld->isNonTemporal(), Ld->isInvariant(),
18540 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18541 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18542 Ld->getPointerInfo(), Ld->isVolatile(),
18543 Ld->isNonTemporal(), Ld->isInvariant(),
18544 std::min(16U, Alignment));
18545 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18547 Load2.getValue(1));
18549 SDValue NewVec = DAG.getUNDEF(RegVT);
18550 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18551 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18552 return DCI.CombineTo(N, NewVec, TF, true);
18555 // If this is a vector EXT Load then attempt to optimize it using a
18556 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18557 // expansion is still better than scalar code.
18558 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18559 // emit a shuffle and a arithmetic shift.
18560 // TODO: It is possible to support ZExt by zeroing the undef values
18561 // during the shuffle phase or after the shuffle.
18562 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18563 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18564 assert(MemVT != RegVT && "Cannot extend to the same type");
18565 assert(MemVT.isVector() && "Must load a vector from memory");
18567 unsigned NumElems = RegVT.getVectorNumElements();
18568 unsigned MemSz = MemVT.getSizeInBits();
18569 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18571 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18574 // All sizes must be a power of two.
18575 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18578 // Attempt to load the original value using scalar loads.
18579 // Find the largest scalar type that divides the total loaded size.
18580 MVT SclrLoadTy = MVT::i8;
18581 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18582 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18583 MVT Tp = (MVT::SimpleValueType)tp;
18584 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18589 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18590 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18592 SclrLoadTy = MVT::f64;
18594 // Calculate the number of scalar loads that we need to perform
18595 // in order to load our vector from memory.
18596 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18597 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18600 unsigned loadRegZize = RegSz;
18601 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18604 // Represent our vector as a sequence of elements which are the
18605 // largest scalar that we can load.
18606 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18607 loadRegZize/SclrLoadTy.getSizeInBits());
18609 // Represent the data using the same element type that is stored in
18610 // memory. In practice, we ''widen'' MemVT.
18612 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18613 loadRegZize/MemVT.getScalarType().getSizeInBits());
18615 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18616 "Invalid vector type");
18618 // We can't shuffle using an illegal type.
18619 if (!TLI.isTypeLegal(WideVecVT))
18622 SmallVector<SDValue, 8> Chains;
18623 SDValue Ptr = Ld->getBasePtr();
18624 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18625 TLI.getPointerTy());
18626 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18628 for (unsigned i = 0; i < NumLoads; ++i) {
18629 // Perform a single load.
18630 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18631 Ptr, Ld->getPointerInfo(),
18632 Ld->isVolatile(), Ld->isNonTemporal(),
18633 Ld->isInvariant(), Ld->getAlignment());
18634 Chains.push_back(ScalarLoad.getValue(1));
18635 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18636 // another round of DAGCombining.
18638 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18640 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18641 ScalarLoad, DAG.getIntPtrConstant(i));
18643 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18646 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18649 // Bitcast the loaded value to a vector of the original element type, in
18650 // the size of the target vector type.
18651 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18652 unsigned SizeRatio = RegSz/MemSz;
18654 if (Ext == ISD::SEXTLOAD) {
18655 // If we have SSE4.1 we can directly emit a VSEXT node.
18656 if (Subtarget->hasSSE41()) {
18657 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18658 return DCI.CombineTo(N, Sext, TF, true);
18661 // Otherwise we'll shuffle the small elements in the high bits of the
18662 // larger type and perform an arithmetic shift. If the shift is not legal
18663 // it's better to scalarize.
18664 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18667 // Redistribute the loaded elements into the different locations.
18668 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18669 for (unsigned i = 0; i != NumElems; ++i)
18670 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18672 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18673 DAG.getUNDEF(WideVecVT),
18676 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18678 // Build the arithmetic shift.
18679 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18680 MemVT.getVectorElementType().getSizeInBits();
18681 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18682 DAG.getConstant(Amt, RegVT));
18684 return DCI.CombineTo(N, Shuff, TF, true);
18687 // Redistribute the loaded elements into the different locations.
18688 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18689 for (unsigned i = 0; i != NumElems; ++i)
18690 ShuffleVec[i*SizeRatio] = i;
18692 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18693 DAG.getUNDEF(WideVecVT),
18696 // Bitcast to the requested type.
18697 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18698 // Replace the original load with the new sequence
18699 // and return the new chain.
18700 return DCI.CombineTo(N, Shuff, TF, true);
18706 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18707 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18708 const X86Subtarget *Subtarget) {
18709 StoreSDNode *St = cast<StoreSDNode>(N);
18710 EVT VT = St->getValue().getValueType();
18711 EVT StVT = St->getMemoryVT();
18713 SDValue StoredVal = St->getOperand(1);
18714 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18716 // If we are saving a concatenation of two XMM registers, perform two stores.
18717 // On Sandy Bridge, 256-bit memory operations are executed by two
18718 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18719 // memory operation.
18720 unsigned Alignment = St->getAlignment();
18721 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18722 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18723 StVT == VT && !IsAligned) {
18724 unsigned NumElems = VT.getVectorNumElements();
18728 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18729 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18731 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18732 SDValue Ptr0 = St->getBasePtr();
18733 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18735 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18736 St->getPointerInfo(), St->isVolatile(),
18737 St->isNonTemporal(), Alignment);
18738 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18739 St->getPointerInfo(), St->isVolatile(),
18740 St->isNonTemporal(),
18741 std::min(16U, Alignment));
18742 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18745 // Optimize trunc store (of multiple scalars) to shuffle and store.
18746 // First, pack all of the elements in one place. Next, store to memory
18747 // in fewer chunks.
18748 if (St->isTruncatingStore() && VT.isVector()) {
18749 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18750 unsigned NumElems = VT.getVectorNumElements();
18751 assert(StVT != VT && "Cannot truncate to the same type");
18752 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18753 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18755 // From, To sizes and ElemCount must be pow of two
18756 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18757 // We are going to use the original vector elt for storing.
18758 // Accumulated smaller vector elements must be a multiple of the store size.
18759 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18761 unsigned SizeRatio = FromSz / ToSz;
18763 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18765 // Create a type on which we perform the shuffle
18766 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18767 StVT.getScalarType(), NumElems*SizeRatio);
18769 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18771 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18772 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18773 for (unsigned i = 0; i != NumElems; ++i)
18774 ShuffleVec[i] = i * SizeRatio;
18776 // Can't shuffle using an illegal type.
18777 if (!TLI.isTypeLegal(WideVecVT))
18780 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18781 DAG.getUNDEF(WideVecVT),
18783 // At this point all of the data is stored at the bottom of the
18784 // register. We now need to save it to mem.
18786 // Find the largest store unit
18787 MVT StoreType = MVT::i8;
18788 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18789 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18790 MVT Tp = (MVT::SimpleValueType)tp;
18791 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18795 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18796 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18797 (64 <= NumElems * ToSz))
18798 StoreType = MVT::f64;
18800 // Bitcast the original vector into a vector of store-size units
18801 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18802 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18803 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18804 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18805 SmallVector<SDValue, 8> Chains;
18806 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18807 TLI.getPointerTy());
18808 SDValue Ptr = St->getBasePtr();
18810 // Perform one or more big stores into memory.
18811 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18812 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18813 StoreType, ShuffWide,
18814 DAG.getIntPtrConstant(i));
18815 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18816 St->getPointerInfo(), St->isVolatile(),
18817 St->isNonTemporal(), St->getAlignment());
18818 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18819 Chains.push_back(Ch);
18822 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18826 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
18827 // the FP state in cases where an emms may be missing.
18828 // A preferable solution to the general problem is to figure out the right
18829 // places to insert EMMS. This qualifies as a quick hack.
18831 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18832 if (VT.getSizeInBits() != 64)
18835 const Function *F = DAG.getMachineFunction().getFunction();
18836 bool NoImplicitFloatOps = F->getAttributes().
18837 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18838 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18839 && Subtarget->hasSSE2();
18840 if ((VT.isVector() ||
18841 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18842 isa<LoadSDNode>(St->getValue()) &&
18843 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18844 St->getChain().hasOneUse() && !St->isVolatile()) {
18845 SDNode* LdVal = St->getValue().getNode();
18846 LoadSDNode *Ld = 0;
18847 int TokenFactorIndex = -1;
18848 SmallVector<SDValue, 8> Ops;
18849 SDNode* ChainVal = St->getChain().getNode();
18850 // Must be a store of a load. We currently handle two cases: the load
18851 // is a direct child, and it's under an intervening TokenFactor. It is
18852 // possible to dig deeper under nested TokenFactors.
18853 if (ChainVal == LdVal)
18854 Ld = cast<LoadSDNode>(St->getChain());
18855 else if (St->getValue().hasOneUse() &&
18856 ChainVal->getOpcode() == ISD::TokenFactor) {
18857 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18858 if (ChainVal->getOperand(i).getNode() == LdVal) {
18859 TokenFactorIndex = i;
18860 Ld = cast<LoadSDNode>(St->getValue());
18862 Ops.push_back(ChainVal->getOperand(i));
18866 if (!Ld || !ISD::isNormalLoad(Ld))
18869 // If this is not the MMX case, i.e. we are just turning i64 load/store
18870 // into f64 load/store, avoid the transformation if there are multiple
18871 // uses of the loaded value.
18872 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18877 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18878 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18880 if (Subtarget->is64Bit() || F64IsLegal) {
18881 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18882 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18883 Ld->getPointerInfo(), Ld->isVolatile(),
18884 Ld->isNonTemporal(), Ld->isInvariant(),
18885 Ld->getAlignment());
18886 SDValue NewChain = NewLd.getValue(1);
18887 if (TokenFactorIndex != -1) {
18888 Ops.push_back(NewChain);
18889 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18892 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18893 St->getPointerInfo(),
18894 St->isVolatile(), St->isNonTemporal(),
18895 St->getAlignment());
18898 // Otherwise, lower to two pairs of 32-bit loads / stores.
18899 SDValue LoAddr = Ld->getBasePtr();
18900 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18901 DAG.getConstant(4, MVT::i32));
18903 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18904 Ld->getPointerInfo(),
18905 Ld->isVolatile(), Ld->isNonTemporal(),
18906 Ld->isInvariant(), Ld->getAlignment());
18907 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18908 Ld->getPointerInfo().getWithOffset(4),
18909 Ld->isVolatile(), Ld->isNonTemporal(),
18911 MinAlign(Ld->getAlignment(), 4));
18913 SDValue NewChain = LoLd.getValue(1);
18914 if (TokenFactorIndex != -1) {
18915 Ops.push_back(LoLd);
18916 Ops.push_back(HiLd);
18917 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18921 LoAddr = St->getBasePtr();
18922 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18923 DAG.getConstant(4, MVT::i32));
18925 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18926 St->getPointerInfo(),
18927 St->isVolatile(), St->isNonTemporal(),
18928 St->getAlignment());
18929 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18930 St->getPointerInfo().getWithOffset(4),
18932 St->isNonTemporal(),
18933 MinAlign(St->getAlignment(), 4));
18934 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18939 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18940 /// and return the operands for the horizontal operation in LHS and RHS. A
18941 /// horizontal operation performs the binary operation on successive elements
18942 /// of its first operand, then on successive elements of its second operand,
18943 /// returning the resulting values in a vector. For example, if
18944 /// A = < float a0, float a1, float a2, float a3 >
18946 /// B = < float b0, float b1, float b2, float b3 >
18947 /// then the result of doing a horizontal operation on A and B is
18948 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18949 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18950 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18951 /// set to A, RHS to B, and the routine returns 'true'.
18952 /// Note that the binary operation should have the property that if one of the
18953 /// operands is UNDEF then the result is UNDEF.
18954 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18955 // Look for the following pattern: if
18956 // A = < float a0, float a1, float a2, float a3 >
18957 // B = < float b0, float b1, float b2, float b3 >
18959 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18960 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18961 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18962 // which is A horizontal-op B.
18964 // At least one of the operands should be a vector shuffle.
18965 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18966 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18969 MVT VT = LHS.getSimpleValueType();
18971 assert((VT.is128BitVector() || VT.is256BitVector()) &&
18972 "Unsupported vector type for horizontal add/sub");
18974 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18975 // operate independently on 128-bit lanes.
18976 unsigned NumElts = VT.getVectorNumElements();
18977 unsigned NumLanes = VT.getSizeInBits()/128;
18978 unsigned NumLaneElts = NumElts / NumLanes;
18979 assert((NumLaneElts % 2 == 0) &&
18980 "Vector type should have an even number of elements in each lane");
18981 unsigned HalfLaneElts = NumLaneElts/2;
18983 // View LHS in the form
18984 // LHS = VECTOR_SHUFFLE A, B, LMask
18985 // If LHS is not a shuffle then pretend it is the shuffle
18986 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18987 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18990 SmallVector<int, 16> LMask(NumElts);
18991 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18992 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18993 A = LHS.getOperand(0);
18994 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18995 B = LHS.getOperand(1);
18996 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18997 std::copy(Mask.begin(), Mask.end(), LMask.begin());
18999 if (LHS.getOpcode() != ISD::UNDEF)
19001 for (unsigned i = 0; i != NumElts; ++i)
19005 // Likewise, view RHS in the form
19006 // RHS = VECTOR_SHUFFLE C, D, RMask
19008 SmallVector<int, 16> RMask(NumElts);
19009 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19010 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19011 C = RHS.getOperand(0);
19012 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19013 D = RHS.getOperand(1);
19014 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19015 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19017 if (RHS.getOpcode() != ISD::UNDEF)
19019 for (unsigned i = 0; i != NumElts; ++i)
19023 // Check that the shuffles are both shuffling the same vectors.
19024 if (!(A == C && B == D) && !(A == D && B == C))
19027 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19028 if (!A.getNode() && !B.getNode())
19031 // If A and B occur in reverse order in RHS, then "swap" them (which means
19032 // rewriting the mask).
19034 CommuteVectorShuffleMask(RMask, NumElts);
19036 // At this point LHS and RHS are equivalent to
19037 // LHS = VECTOR_SHUFFLE A, B, LMask
19038 // RHS = VECTOR_SHUFFLE A, B, RMask
19039 // Check that the masks correspond to performing a horizontal operation.
19040 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19041 for (unsigned i = 0; i != NumLaneElts; ++i) {
19042 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19044 // Ignore any UNDEF components.
19045 if (LIdx < 0 || RIdx < 0 ||
19046 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19047 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19050 // Check that successive elements are being operated on. If not, this is
19051 // not a horizontal operation.
19052 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19053 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19054 if (!(LIdx == Index && RIdx == Index + 1) &&
19055 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19060 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19061 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19065 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19066 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19067 const X86Subtarget *Subtarget) {
19068 EVT VT = N->getValueType(0);
19069 SDValue LHS = N->getOperand(0);
19070 SDValue RHS = N->getOperand(1);
19072 // Try to synthesize horizontal adds from adds of shuffles.
19073 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19074 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19075 isHorizontalBinOp(LHS, RHS, true))
19076 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19080 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19081 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19082 const X86Subtarget *Subtarget) {
19083 EVT VT = N->getValueType(0);
19084 SDValue LHS = N->getOperand(0);
19085 SDValue RHS = N->getOperand(1);
19087 // Try to synthesize horizontal subs from subs of shuffles.
19088 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19089 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19090 isHorizontalBinOp(LHS, RHS, false))
19091 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19095 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19096 /// X86ISD::FXOR nodes.
19097 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19098 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19099 // F[X]OR(0.0, x) -> x
19100 // F[X]OR(x, 0.0) -> x
19101 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19102 if (C->getValueAPF().isPosZero())
19103 return N->getOperand(1);
19104 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19105 if (C->getValueAPF().isPosZero())
19106 return N->getOperand(0);
19110 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19111 /// X86ISD::FMAX nodes.
19112 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19113 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19115 // Only perform optimizations if UnsafeMath is used.
19116 if (!DAG.getTarget().Options.UnsafeFPMath)
19119 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19120 // into FMINC and FMAXC, which are Commutative operations.
19121 unsigned NewOp = 0;
19122 switch (N->getOpcode()) {
19123 default: llvm_unreachable("unknown opcode");
19124 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19125 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19128 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19129 N->getOperand(0), N->getOperand(1));
19132 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19133 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19134 // FAND(0.0, x) -> 0.0
19135 // FAND(x, 0.0) -> 0.0
19136 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19137 if (C->getValueAPF().isPosZero())
19138 return N->getOperand(0);
19139 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19140 if (C->getValueAPF().isPosZero())
19141 return N->getOperand(1);
19145 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19146 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19147 // FANDN(x, 0.0) -> 0.0
19148 // FANDN(0.0, x) -> x
19149 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19150 if (C->getValueAPF().isPosZero())
19151 return N->getOperand(1);
19152 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19153 if (C->getValueAPF().isPosZero())
19154 return N->getOperand(1);
19158 static SDValue PerformBTCombine(SDNode *N,
19160 TargetLowering::DAGCombinerInfo &DCI) {
19161 // BT ignores high bits in the bit index operand.
19162 SDValue Op1 = N->getOperand(1);
19163 if (Op1.hasOneUse()) {
19164 unsigned BitWidth = Op1.getValueSizeInBits();
19165 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19166 APInt KnownZero, KnownOne;
19167 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19168 !DCI.isBeforeLegalizeOps());
19169 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19170 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19171 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19172 DCI.CommitTargetLoweringOpt(TLO);
19177 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19178 SDValue Op = N->getOperand(0);
19179 if (Op.getOpcode() == ISD::BITCAST)
19180 Op = Op.getOperand(0);
19181 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19182 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19183 VT.getVectorElementType().getSizeInBits() ==
19184 OpVT.getVectorElementType().getSizeInBits()) {
19185 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19190 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19191 const X86Subtarget *Subtarget) {
19192 EVT VT = N->getValueType(0);
19193 if (!VT.isVector())
19196 SDValue N0 = N->getOperand(0);
19197 SDValue N1 = N->getOperand(1);
19198 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19201 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19202 // both SSE and AVX2 since there is no sign-extended shift right
19203 // operation on a vector with 64-bit elements.
19204 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19205 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19206 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19207 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19208 SDValue N00 = N0.getOperand(0);
19210 // EXTLOAD has a better solution on AVX2,
19211 // it may be replaced with X86ISD::VSEXT node.
19212 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19213 if (!ISD::isNormalLoad(N00.getNode()))
19216 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19217 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19219 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19225 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19226 TargetLowering::DAGCombinerInfo &DCI,
19227 const X86Subtarget *Subtarget) {
19228 if (!DCI.isBeforeLegalizeOps())
19231 if (!Subtarget->hasFp256())
19234 EVT VT = N->getValueType(0);
19235 if (VT.isVector() && VT.getSizeInBits() == 256) {
19236 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19244 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19245 const X86Subtarget* Subtarget) {
19247 EVT VT = N->getValueType(0);
19249 // Let legalize expand this if it isn't a legal type yet.
19250 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19253 EVT ScalarVT = VT.getScalarType();
19254 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19255 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19258 SDValue A = N->getOperand(0);
19259 SDValue B = N->getOperand(1);
19260 SDValue C = N->getOperand(2);
19262 bool NegA = (A.getOpcode() == ISD::FNEG);
19263 bool NegB = (B.getOpcode() == ISD::FNEG);
19264 bool NegC = (C.getOpcode() == ISD::FNEG);
19266 // Negative multiplication when NegA xor NegB
19267 bool NegMul = (NegA != NegB);
19269 A = A.getOperand(0);
19271 B = B.getOperand(0);
19273 C = C.getOperand(0);
19277 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19279 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19281 return DAG.getNode(Opcode, dl, VT, A, B, C);
19284 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19285 TargetLowering::DAGCombinerInfo &DCI,
19286 const X86Subtarget *Subtarget) {
19287 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19288 // (and (i32 x86isd::setcc_carry), 1)
19289 // This eliminates the zext. This transformation is necessary because
19290 // ISD::SETCC is always legalized to i8.
19292 SDValue N0 = N->getOperand(0);
19293 EVT VT = N->getValueType(0);
19295 if (N0.getOpcode() == ISD::AND &&
19297 N0.getOperand(0).hasOneUse()) {
19298 SDValue N00 = N0.getOperand(0);
19299 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19300 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19301 if (!C || C->getZExtValue() != 1)
19303 return DAG.getNode(ISD::AND, dl, VT,
19304 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19305 N00.getOperand(0), N00.getOperand(1)),
19306 DAG.getConstant(1, VT));
19310 if (N0.getOpcode() == ISD::TRUNCATE &&
19312 N0.getOperand(0).hasOneUse()) {
19313 SDValue N00 = N0.getOperand(0);
19314 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19315 return DAG.getNode(ISD::AND, dl, VT,
19316 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19317 N00.getOperand(0), N00.getOperand(1)),
19318 DAG.getConstant(1, VT));
19321 if (VT.is256BitVector()) {
19322 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19330 // Optimize x == -y --> x+y == 0
19331 // x != -y --> x+y != 0
19332 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19333 const X86Subtarget* Subtarget) {
19334 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19335 SDValue LHS = N->getOperand(0);
19336 SDValue RHS = N->getOperand(1);
19337 EVT VT = N->getValueType(0);
19340 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19341 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19342 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19343 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19344 LHS.getValueType(), RHS, LHS.getOperand(1));
19345 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19346 addV, DAG.getConstant(0, addV.getValueType()), CC);
19348 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19349 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19350 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19351 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19352 RHS.getValueType(), LHS, RHS.getOperand(1));
19353 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19354 addV, DAG.getConstant(0, addV.getValueType()), CC);
19357 if (VT.getScalarType() == MVT::i1) {
19358 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19359 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19360 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19361 if (!IsSEXT0 && !IsVZero0)
19363 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19364 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19365 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19367 if (!IsSEXT1 && !IsVZero1)
19370 if (IsSEXT0 && IsVZero1) {
19371 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19372 if (CC == ISD::SETEQ)
19373 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19374 return LHS.getOperand(0);
19376 if (IsSEXT1 && IsVZero0) {
19377 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19378 if (CC == ISD::SETEQ)
19379 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19380 return RHS.getOperand(0);
19387 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19388 // as "sbb reg,reg", since it can be extended without zext and produces
19389 // an all-ones bit which is more useful than 0/1 in some cases.
19390 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19393 return DAG.getNode(ISD::AND, DL, VT,
19394 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19395 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19396 DAG.getConstant(1, VT));
19397 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19398 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19399 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19400 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19403 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19404 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19405 TargetLowering::DAGCombinerInfo &DCI,
19406 const X86Subtarget *Subtarget) {
19408 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19409 SDValue EFLAGS = N->getOperand(1);
19411 if (CC == X86::COND_A) {
19412 // Try to convert COND_A into COND_B in an attempt to facilitate
19413 // materializing "setb reg".
19415 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19416 // cannot take an immediate as its first operand.
19418 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19419 EFLAGS.getValueType().isInteger() &&
19420 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19421 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19422 EFLAGS.getNode()->getVTList(),
19423 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19424 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19425 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19429 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19430 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19432 if (CC == X86::COND_B)
19433 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19437 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19438 if (Flags.getNode()) {
19439 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19440 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19446 // Optimize branch condition evaluation.
19448 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19449 TargetLowering::DAGCombinerInfo &DCI,
19450 const X86Subtarget *Subtarget) {
19452 SDValue Chain = N->getOperand(0);
19453 SDValue Dest = N->getOperand(1);
19454 SDValue EFLAGS = N->getOperand(3);
19455 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19459 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19460 if (Flags.getNode()) {
19461 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19462 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19469 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19470 const X86TargetLowering *XTLI) {
19471 SDValue Op0 = N->getOperand(0);
19472 EVT InVT = Op0->getValueType(0);
19474 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19475 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19477 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19478 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19479 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19482 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19483 // a 32-bit target where SSE doesn't support i64->FP operations.
19484 if (Op0.getOpcode() == ISD::LOAD) {
19485 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19486 EVT VT = Ld->getValueType(0);
19487 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19488 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19489 !XTLI->getSubtarget()->is64Bit() &&
19491 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19492 Ld->getChain(), Op0, DAG);
19493 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19500 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19501 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19502 X86TargetLowering::DAGCombinerInfo &DCI) {
19503 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19504 // the result is either zero or one (depending on the input carry bit).
19505 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19506 if (X86::isZeroNode(N->getOperand(0)) &&
19507 X86::isZeroNode(N->getOperand(1)) &&
19508 // We don't have a good way to replace an EFLAGS use, so only do this when
19510 SDValue(N, 1).use_empty()) {
19512 EVT VT = N->getValueType(0);
19513 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19514 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19515 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19516 DAG.getConstant(X86::COND_B,MVT::i8),
19518 DAG.getConstant(1, VT));
19519 return DCI.CombineTo(N, Res1, CarryOut);
19525 // fold (add Y, (sete X, 0)) -> adc 0, Y
19526 // (add Y, (setne X, 0)) -> sbb -1, Y
19527 // (sub (sete X, 0), Y) -> sbb 0, Y
19528 // (sub (setne X, 0), Y) -> adc -1, Y
19529 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19532 // Look through ZExts.
19533 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19534 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19537 SDValue SetCC = Ext.getOperand(0);
19538 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19541 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19542 if (CC != X86::COND_E && CC != X86::COND_NE)
19545 SDValue Cmp = SetCC.getOperand(1);
19546 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19547 !X86::isZeroNode(Cmp.getOperand(1)) ||
19548 !Cmp.getOperand(0).getValueType().isInteger())
19551 SDValue CmpOp0 = Cmp.getOperand(0);
19552 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19553 DAG.getConstant(1, CmpOp0.getValueType()));
19555 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19556 if (CC == X86::COND_NE)
19557 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19558 DL, OtherVal.getValueType(), OtherVal,
19559 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19560 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19561 DL, OtherVal.getValueType(), OtherVal,
19562 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19565 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19566 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19567 const X86Subtarget *Subtarget) {
19568 EVT VT = N->getValueType(0);
19569 SDValue Op0 = N->getOperand(0);
19570 SDValue Op1 = N->getOperand(1);
19572 // Try to synthesize horizontal adds from adds of shuffles.
19573 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19574 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19575 isHorizontalBinOp(Op0, Op1, true))
19576 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19578 return OptimizeConditionalInDecrement(N, DAG);
19581 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19582 const X86Subtarget *Subtarget) {
19583 SDValue Op0 = N->getOperand(0);
19584 SDValue Op1 = N->getOperand(1);
19586 // X86 can't encode an immediate LHS of a sub. See if we can push the
19587 // negation into a preceding instruction.
19588 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19589 // If the RHS of the sub is a XOR with one use and a constant, invert the
19590 // immediate. Then add one to the LHS of the sub so we can turn
19591 // X-Y -> X+~Y+1, saving one register.
19592 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19593 isa<ConstantSDNode>(Op1.getOperand(1))) {
19594 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19595 EVT VT = Op0.getValueType();
19596 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19598 DAG.getConstant(~XorC, VT));
19599 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19600 DAG.getConstant(C->getAPIntValue()+1, VT));
19604 // Try to synthesize horizontal adds from adds of shuffles.
19605 EVT VT = N->getValueType(0);
19606 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19607 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19608 isHorizontalBinOp(Op0, Op1, true))
19609 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19611 return OptimizeConditionalInDecrement(N, DAG);
19614 /// performVZEXTCombine - Performs build vector combines
19615 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19616 TargetLowering::DAGCombinerInfo &DCI,
19617 const X86Subtarget *Subtarget) {
19618 // (vzext (bitcast (vzext (x)) -> (vzext x)
19619 SDValue In = N->getOperand(0);
19620 while (In.getOpcode() == ISD::BITCAST)
19621 In = In.getOperand(0);
19623 if (In.getOpcode() != X86ISD::VZEXT)
19626 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19630 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19631 DAGCombinerInfo &DCI) const {
19632 SelectionDAG &DAG = DCI.DAG;
19633 switch (N->getOpcode()) {
19635 case ISD::EXTRACT_VECTOR_ELT:
19636 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19638 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19639 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19640 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
19641 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
19642 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
19643 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
19646 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
19647 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
19648 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
19649 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
19650 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
19651 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
19652 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
19653 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
19654 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
19656 case X86ISD::FOR: return PerformFORCombine(N, DAG);
19658 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
19659 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
19660 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
19661 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
19662 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
19663 case ISD::ANY_EXTEND:
19664 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
19665 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
19666 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19667 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19668 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
19669 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19670 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19671 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
19672 case X86ISD::SHUFP: // Handle all target specific shuffles
19673 case X86ISD::PALIGNR:
19674 case X86ISD::UNPCKH:
19675 case X86ISD::UNPCKL:
19676 case X86ISD::MOVHLPS:
19677 case X86ISD::MOVLHPS:
19678 case X86ISD::PSHUFD:
19679 case X86ISD::PSHUFHW:
19680 case X86ISD::PSHUFLW:
19681 case X86ISD::MOVSS:
19682 case X86ISD::MOVSD:
19683 case X86ISD::VPERMILP:
19684 case X86ISD::VPERM2X128:
19685 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19686 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
19692 /// isTypeDesirableForOp - Return true if the target has native support for
19693 /// the specified value type and it is 'desirable' to use the type for the
19694 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19695 /// instruction encodings are longer and some i16 instructions are slow.
19696 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19697 if (!isTypeLegal(VT))
19699 if (VT != MVT::i16)
19706 case ISD::SIGN_EXTEND:
19707 case ISD::ZERO_EXTEND:
19708 case ISD::ANY_EXTEND:
19721 /// IsDesirableToPromoteOp - This method query the target whether it is
19722 /// beneficial for dag combiner to promote the specified node. If true, it
19723 /// should return the desired promotion type by reference.
19724 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19725 EVT VT = Op.getValueType();
19726 if (VT != MVT::i16)
19729 bool Promote = false;
19730 bool Commute = false;
19731 switch (Op.getOpcode()) {
19734 LoadSDNode *LD = cast<LoadSDNode>(Op);
19735 // If the non-extending load has a single use and it's not live out, then it
19736 // might be folded.
19737 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19738 Op.hasOneUse()*/) {
19739 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19740 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19741 // The only case where we'd want to promote LOAD (rather then it being
19742 // promoted as an operand is when it's only use is liveout.
19743 if (UI->getOpcode() != ISD::CopyToReg)
19750 case ISD::SIGN_EXTEND:
19751 case ISD::ZERO_EXTEND:
19752 case ISD::ANY_EXTEND:
19757 SDValue N0 = Op.getOperand(0);
19758 // Look out for (store (shl (load), x)).
19759 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19772 SDValue N0 = Op.getOperand(0);
19773 SDValue N1 = Op.getOperand(1);
19774 if (!Commute && MayFoldLoad(N1))
19776 // Avoid disabling potential load folding opportunities.
19777 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19779 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19789 //===----------------------------------------------------------------------===//
19790 // X86 Inline Assembly Support
19791 //===----------------------------------------------------------------------===//
19794 // Helper to match a string separated by whitespace.
19795 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19796 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19798 for (unsigned i = 0, e = args.size(); i != e; ++i) {
19799 StringRef piece(*args[i]);
19800 if (!s.startswith(piece)) // Check if the piece matches.
19803 s = s.substr(piece.size());
19804 StringRef::size_type pos = s.find_first_not_of(" \t");
19805 if (pos == 0) // We matched a prefix.
19813 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19816 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19818 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19819 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19820 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19821 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19823 if (AsmPieces.size() == 3)
19825 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19832 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19833 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19835 std::string AsmStr = IA->getAsmString();
19837 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19838 if (!Ty || Ty->getBitWidth() % 16 != 0)
19841 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19842 SmallVector<StringRef, 4> AsmPieces;
19843 SplitString(AsmStr, AsmPieces, ";\n");
19845 switch (AsmPieces.size()) {
19846 default: return false;
19848 // FIXME: this should verify that we are targeting a 486 or better. If not,
19849 // we will turn this bswap into something that will be lowered to logical
19850 // ops instead of emitting the bswap asm. For now, we don't support 486 or
19851 // lower so don't worry about this.
19853 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19854 matchAsm(AsmPieces[0], "bswapl", "$0") ||
19855 matchAsm(AsmPieces[0], "bswapq", "$0") ||
19856 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19857 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19858 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19859 // No need to check constraints, nothing other than the equivalent of
19860 // "=r,0" would be valid here.
19861 return IntrinsicLowering::LowerToByteSwap(CI);
19864 // rorw $$8, ${0:w} --> llvm.bswap.i16
19865 if (CI->getType()->isIntegerTy(16) &&
19866 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19867 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19868 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19870 const std::string &ConstraintsStr = IA->getConstraintString();
19871 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19872 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19873 if (clobbersFlagRegisters(AsmPieces))
19874 return IntrinsicLowering::LowerToByteSwap(CI);
19878 if (CI->getType()->isIntegerTy(32) &&
19879 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19880 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19881 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19882 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19884 const std::string &ConstraintsStr = IA->getConstraintString();
19885 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19886 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19887 if (clobbersFlagRegisters(AsmPieces))
19888 return IntrinsicLowering::LowerToByteSwap(CI);
19891 if (CI->getType()->isIntegerTy(64)) {
19892 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19893 if (Constraints.size() >= 2 &&
19894 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19895 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19896 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
19897 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19898 matchAsm(AsmPieces[1], "bswap", "%edx") &&
19899 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19900 return IntrinsicLowering::LowerToByteSwap(CI);
19908 /// getConstraintType - Given a constraint letter, return the type of
19909 /// constraint it is for this target.
19910 X86TargetLowering::ConstraintType
19911 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19912 if (Constraint.size() == 1) {
19913 switch (Constraint[0]) {
19924 return C_RegisterClass;
19948 return TargetLowering::getConstraintType(Constraint);
19951 /// Examine constraint type and operand type and determine a weight value.
19952 /// This object must already have been set up with the operand type
19953 /// and the current alternative constraint selected.
19954 TargetLowering::ConstraintWeight
19955 X86TargetLowering::getSingleConstraintMatchWeight(
19956 AsmOperandInfo &info, const char *constraint) const {
19957 ConstraintWeight weight = CW_Invalid;
19958 Value *CallOperandVal = info.CallOperandVal;
19959 // If we don't have a value, we can't do a match,
19960 // but allow it at the lowest weight.
19961 if (CallOperandVal == NULL)
19963 Type *type = CallOperandVal->getType();
19964 // Look at the constraint type.
19965 switch (*constraint) {
19967 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19978 if (CallOperandVal->getType()->isIntegerTy())
19979 weight = CW_SpecificReg;
19984 if (type->isFloatingPointTy())
19985 weight = CW_SpecificReg;
19988 if (type->isX86_MMXTy() && Subtarget->hasMMX())
19989 weight = CW_SpecificReg;
19993 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19994 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19995 weight = CW_Register;
19998 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19999 if (C->getZExtValue() <= 31)
20000 weight = CW_Constant;
20004 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20005 if (C->getZExtValue() <= 63)
20006 weight = CW_Constant;
20010 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20011 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20012 weight = CW_Constant;
20016 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20017 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20018 weight = CW_Constant;
20022 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20023 if (C->getZExtValue() <= 3)
20024 weight = CW_Constant;
20028 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20029 if (C->getZExtValue() <= 0xff)
20030 weight = CW_Constant;
20035 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20036 weight = CW_Constant;
20040 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20041 if ((C->getSExtValue() >= -0x80000000LL) &&
20042 (C->getSExtValue() <= 0x7fffffffLL))
20043 weight = CW_Constant;
20047 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20048 if (C->getZExtValue() <= 0xffffffff)
20049 weight = CW_Constant;
20056 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20057 /// with another that has more specific requirements based on the type of the
20058 /// corresponding operand.
20059 const char *X86TargetLowering::
20060 LowerXConstraint(EVT ConstraintVT) const {
20061 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20062 // 'f' like normal targets.
20063 if (ConstraintVT.isFloatingPoint()) {
20064 if (Subtarget->hasSSE2())
20066 if (Subtarget->hasSSE1())
20070 return TargetLowering::LowerXConstraint(ConstraintVT);
20073 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20074 /// vector. If it is invalid, don't add anything to Ops.
20075 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20076 std::string &Constraint,
20077 std::vector<SDValue>&Ops,
20078 SelectionDAG &DAG) const {
20079 SDValue Result(0, 0);
20081 // Only support length 1 constraints for now.
20082 if (Constraint.length() > 1) return;
20084 char ConstraintLetter = Constraint[0];
20085 switch (ConstraintLetter) {
20088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20089 if (C->getZExtValue() <= 31) {
20090 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20096 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20097 if (C->getZExtValue() <= 63) {
20098 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20104 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20105 if (isInt<8>(C->getSExtValue())) {
20106 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20112 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20113 if (C->getZExtValue() <= 255) {
20114 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20120 // 32-bit signed value
20121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20122 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20123 C->getSExtValue())) {
20124 // Widen to 64 bits here to get it sign extended.
20125 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20128 // FIXME gcc accepts some relocatable values here too, but only in certain
20129 // memory models; it's complicated.
20134 // 32-bit unsigned value
20135 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20136 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20137 C->getZExtValue())) {
20138 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20142 // FIXME gcc accepts some relocatable values here too, but only in certain
20143 // memory models; it's complicated.
20147 // Literal immediates are always ok.
20148 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20149 // Widen to 64 bits here to get it sign extended.
20150 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20154 // In any sort of PIC mode addresses need to be computed at runtime by
20155 // adding in a register or some sort of table lookup. These can't
20156 // be used as immediates.
20157 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20160 // If we are in non-pic codegen mode, we allow the address of a global (with
20161 // an optional displacement) to be used with 'i'.
20162 GlobalAddressSDNode *GA = 0;
20163 int64_t Offset = 0;
20165 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20167 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20168 Offset += GA->getOffset();
20170 } else if (Op.getOpcode() == ISD::ADD) {
20171 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20172 Offset += C->getZExtValue();
20173 Op = Op.getOperand(0);
20176 } else if (Op.getOpcode() == ISD::SUB) {
20177 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20178 Offset += -C->getZExtValue();
20179 Op = Op.getOperand(0);
20184 // Otherwise, this isn't something we can handle, reject it.
20188 const GlobalValue *GV = GA->getGlobal();
20189 // If we require an extra load to get this address, as in PIC mode, we
20190 // can't accept it.
20191 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20192 getTargetMachine())))
20195 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20196 GA->getValueType(0), Offset);
20201 if (Result.getNode()) {
20202 Ops.push_back(Result);
20205 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20208 std::pair<unsigned, const TargetRegisterClass*>
20209 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20211 // First, see if this is a constraint that directly corresponds to an LLVM
20213 if (Constraint.size() == 1) {
20214 // GCC Constraint Letters
20215 switch (Constraint[0]) {
20217 // TODO: Slight differences here in allocation order and leaving
20218 // RIP in the class. Do they matter any more here than they do
20219 // in the normal allocation?
20220 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20221 if (Subtarget->is64Bit()) {
20222 if (VT == MVT::i32 || VT == MVT::f32)
20223 return std::make_pair(0U, &X86::GR32RegClass);
20224 if (VT == MVT::i16)
20225 return std::make_pair(0U, &X86::GR16RegClass);
20226 if (VT == MVT::i8 || VT == MVT::i1)
20227 return std::make_pair(0U, &X86::GR8RegClass);
20228 if (VT == MVT::i64 || VT == MVT::f64)
20229 return std::make_pair(0U, &X86::GR64RegClass);
20232 // 32-bit fallthrough
20233 case 'Q': // Q_REGS
20234 if (VT == MVT::i32 || VT == MVT::f32)
20235 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20236 if (VT == MVT::i16)
20237 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20238 if (VT == MVT::i8 || VT == MVT::i1)
20239 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20240 if (VT == MVT::i64)
20241 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20243 case 'r': // GENERAL_REGS
20244 case 'l': // INDEX_REGS
20245 if (VT == MVT::i8 || VT == MVT::i1)
20246 return std::make_pair(0U, &X86::GR8RegClass);
20247 if (VT == MVT::i16)
20248 return std::make_pair(0U, &X86::GR16RegClass);
20249 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20250 return std::make_pair(0U, &X86::GR32RegClass);
20251 return std::make_pair(0U, &X86::GR64RegClass);
20252 case 'R': // LEGACY_REGS
20253 if (VT == MVT::i8 || VT == MVT::i1)
20254 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20255 if (VT == MVT::i16)
20256 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20257 if (VT == MVT::i32 || !Subtarget->is64Bit())
20258 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20259 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20260 case 'f': // FP Stack registers.
20261 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20262 // value to the correct fpstack register class.
20263 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20264 return std::make_pair(0U, &X86::RFP32RegClass);
20265 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20266 return std::make_pair(0U, &X86::RFP64RegClass);
20267 return std::make_pair(0U, &X86::RFP80RegClass);
20268 case 'y': // MMX_REGS if MMX allowed.
20269 if (!Subtarget->hasMMX()) break;
20270 return std::make_pair(0U, &X86::VR64RegClass);
20271 case 'Y': // SSE_REGS if SSE2 allowed
20272 if (!Subtarget->hasSSE2()) break;
20274 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20275 if (!Subtarget->hasSSE1()) break;
20277 switch (VT.SimpleTy) {
20279 // Scalar SSE types.
20282 return std::make_pair(0U, &X86::FR32RegClass);
20285 return std::make_pair(0U, &X86::FR64RegClass);
20293 return std::make_pair(0U, &X86::VR128RegClass);
20301 return std::make_pair(0U, &X86::VR256RegClass);
20306 return std::make_pair(0U, &X86::VR512RegClass);
20312 // Use the default implementation in TargetLowering to convert the register
20313 // constraint into a member of a register class.
20314 std::pair<unsigned, const TargetRegisterClass*> Res;
20315 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20317 // Not found as a standard register?
20318 if (Res.second == 0) {
20319 // Map st(0) -> st(7) -> ST0
20320 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20321 tolower(Constraint[1]) == 's' &&
20322 tolower(Constraint[2]) == 't' &&
20323 Constraint[3] == '(' &&
20324 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20325 Constraint[5] == ')' &&
20326 Constraint[6] == '}') {
20328 Res.first = X86::ST0+Constraint[4]-'0';
20329 Res.second = &X86::RFP80RegClass;
20333 // GCC allows "st(0)" to be called just plain "st".
20334 if (StringRef("{st}").equals_lower(Constraint)) {
20335 Res.first = X86::ST0;
20336 Res.second = &X86::RFP80RegClass;
20341 if (StringRef("{flags}").equals_lower(Constraint)) {
20342 Res.first = X86::EFLAGS;
20343 Res.second = &X86::CCRRegClass;
20347 // 'A' means EAX + EDX.
20348 if (Constraint == "A") {
20349 Res.first = X86::EAX;
20350 Res.second = &X86::GR32_ADRegClass;
20356 // Otherwise, check to see if this is a register class of the wrong value
20357 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20358 // turn into {ax},{dx}.
20359 if (Res.second->hasType(VT))
20360 return Res; // Correct type already, nothing to do.
20362 // All of the single-register GCC register classes map their values onto
20363 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20364 // really want an 8-bit or 32-bit register, map to the appropriate register
20365 // class and return the appropriate register.
20366 if (Res.second == &X86::GR16RegClass) {
20367 if (VT == MVT::i8 || VT == MVT::i1) {
20368 unsigned DestReg = 0;
20369 switch (Res.first) {
20371 case X86::AX: DestReg = X86::AL; break;
20372 case X86::DX: DestReg = X86::DL; break;
20373 case X86::CX: DestReg = X86::CL; break;
20374 case X86::BX: DestReg = X86::BL; break;
20377 Res.first = DestReg;
20378 Res.second = &X86::GR8RegClass;
20380 } else if (VT == MVT::i32 || VT == MVT::f32) {
20381 unsigned DestReg = 0;
20382 switch (Res.first) {
20384 case X86::AX: DestReg = X86::EAX; break;
20385 case X86::DX: DestReg = X86::EDX; break;
20386 case X86::CX: DestReg = X86::ECX; break;
20387 case X86::BX: DestReg = X86::EBX; break;
20388 case X86::SI: DestReg = X86::ESI; break;
20389 case X86::DI: DestReg = X86::EDI; break;
20390 case X86::BP: DestReg = X86::EBP; break;
20391 case X86::SP: DestReg = X86::ESP; break;
20394 Res.first = DestReg;
20395 Res.second = &X86::GR32RegClass;
20397 } else if (VT == MVT::i64 || VT == MVT::f64) {
20398 unsigned DestReg = 0;
20399 switch (Res.first) {
20401 case X86::AX: DestReg = X86::RAX; break;
20402 case X86::DX: DestReg = X86::RDX; break;
20403 case X86::CX: DestReg = X86::RCX; break;
20404 case X86::BX: DestReg = X86::RBX; break;
20405 case X86::SI: DestReg = X86::RSI; break;
20406 case X86::DI: DestReg = X86::RDI; break;
20407 case X86::BP: DestReg = X86::RBP; break;
20408 case X86::SP: DestReg = X86::RSP; break;
20411 Res.first = DestReg;
20412 Res.second = &X86::GR64RegClass;
20415 } else if (Res.second == &X86::FR32RegClass ||
20416 Res.second == &X86::FR64RegClass ||
20417 Res.second == &X86::VR128RegClass ||
20418 Res.second == &X86::VR256RegClass ||
20419 Res.second == &X86::FR32XRegClass ||
20420 Res.second == &X86::FR64XRegClass ||
20421 Res.second == &X86::VR128XRegClass ||
20422 Res.second == &X86::VR256XRegClass ||
20423 Res.second == &X86::VR512RegClass) {
20424 // Handle references to XMM physical registers that got mapped into the
20425 // wrong class. This can happen with constraints like {xmm0} where the
20426 // target independent register mapper will just pick the first match it can
20427 // find, ignoring the required type.
20429 if (VT == MVT::f32 || VT == MVT::i32)
20430 Res.second = &X86::FR32RegClass;
20431 else if (VT == MVT::f64 || VT == MVT::i64)
20432 Res.second = &X86::FR64RegClass;
20433 else if (X86::VR128RegClass.hasType(VT))
20434 Res.second = &X86::VR128RegClass;
20435 else if (X86::VR256RegClass.hasType(VT))
20436 Res.second = &X86::VR256RegClass;
20437 else if (X86::VR512RegClass.hasType(VT))
20438 Res.second = &X86::VR512RegClass;