1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "x86-isel"
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63 SelectionDAG &DAG, SDLoc dl,
64 unsigned vectorWidth) {
65 assert((vectorWidth == 128 || vectorWidth == 256) &&
66 "Unsupported vector width");
67 EVT VT = Vec.getValueType();
68 EVT ElVT = VT.getVectorElementType();
69 unsigned Factor = VT.getSizeInBits()/vectorWidth;
70 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71 VT.getVectorNumElements()/Factor);
73 // Extract from UNDEF is UNDEF.
74 if (Vec.getOpcode() == ISD::UNDEF)
75 return DAG.getUNDEF(ResultVT);
77 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
78 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80 // This is the index of the first element of the vectorWidth-bit chunk
82 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
85 // If the input is a buildvector just emit a smaller one.
86 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
90 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104 SelectionDAG &DAG, SDLoc dl) {
105 assert((Vec.getValueType().is256BitVector() ||
106 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112 SelectionDAG &DAG, SDLoc dl) {
113 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118 unsigned IdxVal, SelectionDAG &DAG,
119 SDLoc dl, unsigned vectorWidth) {
120 assert((vectorWidth == 128 || vectorWidth == 256) &&
121 "Unsupported vector width");
122 // Inserting UNDEF is Result
123 if (Vec.getOpcode() == ISD::UNDEF)
125 EVT VT = Vec.getValueType();
126 EVT ElVT = VT.getVectorElementType();
127 EVT ResultVT = Result.getValueType();
129 // Insert the relevant vectorWidth bits.
130 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
132 // This is the index of the first element of the vectorWidth-bit chunk
134 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference. Idx is an index in the 128 bits
145 /// we want. It need not be aligned to a 128-bit bounday. That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148 unsigned IdxVal, SelectionDAG &DAG,
150 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155 unsigned IdxVal, SelectionDAG &DAG,
157 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166 unsigned NumElems, SelectionDAG &DAG,
168 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173 unsigned NumElems, SelectionDAG &DAG,
175 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181 bool is64Bit = Subtarget->is64Bit();
183 if (Subtarget->isTargetMacho()) {
185 return new X86_64MachoTargetObjectFile();
186 return new TargetLoweringObjectFileMachO();
189 if (Subtarget->isTargetLinux())
190 return new X86LinuxTargetObjectFile();
191 if (Subtarget->isTargetELF())
192 return new TargetLoweringObjectFileELF();
193 if (Subtarget->isTargetKnownWindowsMSVC())
194 return new X86WindowsTargetObjectFile();
195 if (Subtarget->isTargetCOFF())
196 return new TargetLoweringObjectFileCOFF();
197 llvm_unreachable("unknown subtarget type");
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201 : TargetLowering(TM, createTLOF(TM)) {
202 Subtarget = &TM.getSubtarget<X86Subtarget>();
203 X86ScalarSSEf64 = Subtarget->hasSSE2();
204 X86ScalarSSEf32 = Subtarget->hasSSE1();
205 TD = getDataLayout();
207 resetOperationActions();
210 void X86TargetLowering::resetOperationActions() {
211 const TargetMachine &TM = getTargetMachine();
212 static bool FirstTimeThrough = true;
214 // If none of the target options have changed, then we don't need to reset the
215 // operation actions.
216 if (!FirstTimeThrough && TO == TM.Options) return;
218 if (!FirstTimeThrough) {
219 // Reinitialize the actions.
221 FirstTimeThrough = false;
226 // Set up the TargetLowering object.
227 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
229 // X86 is weird, it always uses i8 for shift amounts and setcc results.
230 setBooleanContents(ZeroOrOneBooleanContent);
231 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
234 // For 64-bit since we have so many registers use the ILP scheduler, for
235 // 32-bit code use the register pressure specific scheduling.
236 // For Atom, always use ILP scheduling.
237 if (Subtarget->isAtom())
238 setSchedulingPreference(Sched::ILP);
239 else if (Subtarget->is64Bit())
240 setSchedulingPreference(Sched::ILP);
242 setSchedulingPreference(Sched::RegPressure);
243 const X86RegisterInfo *RegInfo =
244 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
247 // Bypass expensive divides on Atom when compiling with O2
248 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249 addBypassSlowDiv(32, 8);
250 if (Subtarget->is64Bit())
251 addBypassSlowDiv(64, 16);
254 if (Subtarget->isTargetKnownWindowsMSVC()) {
255 // Setup Windows compiler runtime calls.
256 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258 setLibcallName(RTLIB::SREM_I64, "_allrem");
259 setLibcallName(RTLIB::UREM_I64, "_aullrem");
260 setLibcallName(RTLIB::MUL_I64, "_allmul");
261 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
267 // The _ftol2 runtime function has an unusual calling conv, which
268 // is modeled by a special pseudo-instruction.
269 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
270 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
271 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
272 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
275 if (Subtarget->isTargetDarwin()) {
276 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277 setUseUnderscoreSetJmp(false);
278 setUseUnderscoreLongJmp(false);
279 } else if (Subtarget->isTargetWindowsGNU()) {
280 // MS runtime is weird: it exports _setjmp, but longjmp!
281 setUseUnderscoreSetJmp(true);
282 setUseUnderscoreLongJmp(false);
284 setUseUnderscoreSetJmp(true);
285 setUseUnderscoreLongJmp(true);
288 // Set up the register classes.
289 addRegisterClass(MVT::i8, &X86::GR8RegClass);
290 addRegisterClass(MVT::i16, &X86::GR16RegClass);
291 addRegisterClass(MVT::i32, &X86::GR32RegClass);
292 if (Subtarget->is64Bit())
293 addRegisterClass(MVT::i64, &X86::GR64RegClass);
295 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
297 // We don't accept any truncstore of integer registers.
298 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
305 // SETOEQ and SETUNE require checking two conditions.
306 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
313 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
315 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
316 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
317 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
319 if (Subtarget->is64Bit()) {
320 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
321 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
322 } else if (!TM.Options.UseSoftFloat) {
323 // We have an algorithm for SSE2->double, and we turn this into a
324 // 64-bit FILD followed by conditional FADD for other targets.
325 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
326 // We have an algorithm for SSE2, and we turn this into a 64-bit
327 // FILD for other targets.
328 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
331 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
333 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
334 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
336 if (!TM.Options.UseSoftFloat) {
337 // SSE has no i16 to fp conversion, only i32
338 if (X86ScalarSSEf32) {
339 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
340 // f32 and f64 cases are Legal, f80 case is not
341 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
343 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
344 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
347 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
351 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
352 // are Legal, f80 is custom lowered.
353 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
354 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
356 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
358 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
359 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
361 if (X86ScalarSSEf32) {
362 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
363 // f32 and f64 cases are Legal, f80 case is not
364 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
366 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
370 // Handle FP_TO_UINT by promoting the destination to a larger signed
372 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
374 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
376 if (Subtarget->is64Bit()) {
377 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
378 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
379 } else if (!TM.Options.UseSoftFloat) {
380 // Since AVX is a superset of SSE3, only check for SSE here.
381 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382 // Expand FP_TO_UINT into a select.
383 // FIXME: We would like to use a Custom expander here eventually to do
384 // the optimal thing for SSE vs. the default expansion in the legalizer.
385 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
387 // With SSE3 we can use fisttpll to convert to a signed i64; without
388 // SSE, we're stuck with a fistpll.
389 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
392 if (isTargetFTOL()) {
393 // Use the _ftol2 runtime function, which has a pseudo-instruction
394 // to handle its weird calling convention.
395 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
398 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399 if (!X86ScalarSSEf64) {
400 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
401 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
402 if (Subtarget->is64Bit()) {
403 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
404 // Without SSE, i64->f64 goes through memory.
405 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
409 // Scalar integer divide and remainder are lowered to use operations that
410 // produce two results, to match the available instructions. This exposes
411 // the two-result form to trivial CSE, which is able to combine x/y and x%y
412 // into a single instruction.
414 // Scalar integer multiply-high is also lowered to use two-result
415 // operations, to match the available instructions. However, plain multiply
416 // (low) operations are left as Legal, as there are single-result
417 // instructions for this in x86. Using the two-result multiply instructions
418 // when both high and low results are needed must be arranged by dagcombine.
419 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
421 setOperationAction(ISD::MULHS, VT, Expand);
422 setOperationAction(ISD::MULHU, VT, Expand);
423 setOperationAction(ISD::SDIV, VT, Expand);
424 setOperationAction(ISD::UDIV, VT, Expand);
425 setOperationAction(ISD::SREM, VT, Expand);
426 setOperationAction(ISD::UREM, VT, Expand);
428 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429 setOperationAction(ISD::ADDC, VT, Custom);
430 setOperationAction(ISD::ADDE, VT, Custom);
431 setOperationAction(ISD::SUBC, VT, Custom);
432 setOperationAction(ISD::SUBE, VT, Custom);
435 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
436 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
437 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
438 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
439 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
440 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
441 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
442 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
443 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
444 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
445 if (Subtarget->is64Bit())
446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
449 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
450 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
451 setOperationAction(ISD::FREM , MVT::f32 , Expand);
452 setOperationAction(ISD::FREM , MVT::f64 , Expand);
453 setOperationAction(ISD::FREM , MVT::f80 , Expand);
454 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
456 // Promote the i8 variants and force them on up to i32 which has a shorter
458 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
459 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
460 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
462 if (Subtarget->hasBMI()) {
463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
464 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
468 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
469 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
474 if (Subtarget->hasLZCNT()) {
475 // When promoting the i8 variants, force them to i32 for a shorter
477 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
478 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
482 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
483 if (Subtarget->is64Bit())
484 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
486 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
487 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
488 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
489 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
490 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
492 if (Subtarget->is64Bit()) {
493 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
494 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
498 if (Subtarget->hasPOPCNT()) {
499 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
501 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
502 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
503 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
504 if (Subtarget->is64Bit())
505 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
508 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
510 if (!Subtarget->hasMOVBE())
511 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
513 // These should be promoted to a larger select which is supported.
514 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
515 // X86 wants to expand cmov itself.
516 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
517 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
518 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
519 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
520 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
521 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
522 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
523 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
524 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
525 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
526 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
527 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
528 if (Subtarget->is64Bit()) {
529 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
530 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
532 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
533 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535 // support continuation, user-level threading, and etc.. As a result, no
536 // other SjLj exception interfaces are implemented and please don't build
537 // your own exception handling based on them.
538 // LLVM/Clang supports zero-cost DWARF exception handling.
539 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
544 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
545 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
546 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
547 if (Subtarget->is64Bit())
548 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
550 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
551 if (Subtarget->is64Bit()) {
552 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
553 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
554 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
555 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
556 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
558 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
560 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
561 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
562 if (Subtarget->is64Bit()) {
563 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
564 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
565 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
568 if (Subtarget->hasSSE1())
569 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
571 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
573 // Expand certain atomics
574 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
576 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
581 if (!Subtarget->is64Bit()) {
582 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
596 if (Subtarget->hasCmpxchg16b()) {
597 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
600 // FIXME - use subtarget debug flags
601 if (!Subtarget->isTargetDarwin() &&
602 !Subtarget->isTargetELF() &&
603 !Subtarget->isTargetCygMing()) {
604 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
607 if (Subtarget->is64Bit()) {
608 setExceptionPointerRegister(X86::RAX);
609 setExceptionSelectorRegister(X86::RDX);
611 setExceptionPointerRegister(X86::EAX);
612 setExceptionSelectorRegister(X86::EDX);
614 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
617 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
620 setOperationAction(ISD::TRAP, MVT::Other, Legal);
621 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
623 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624 setOperationAction(ISD::VASTART , MVT::Other, Custom);
625 setOperationAction(ISD::VAEND , MVT::Other, Expand);
626 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627 // TargetInfo::X86_64ABIBuiltinVaList
628 setOperationAction(ISD::VAARG , MVT::Other, Custom);
629 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
631 // TargetInfo::CharPtrBuiltinVaList
632 setOperationAction(ISD::VAARG , MVT::Other, Expand);
633 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
636 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
637 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
639 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640 MVT::i64 : MVT::i32, Custom);
642 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643 // f32 and f64 use SSE.
644 // Set up the FP register classes.
645 addRegisterClass(MVT::f32, &X86::FR32RegClass);
646 addRegisterClass(MVT::f64, &X86::FR64RegClass);
648 // Use ANDPD to simulate FABS.
649 setOperationAction(ISD::FABS , MVT::f64, Custom);
650 setOperationAction(ISD::FABS , MVT::f32, Custom);
652 // Use XORP to simulate FNEG.
653 setOperationAction(ISD::FNEG , MVT::f64, Custom);
654 setOperationAction(ISD::FNEG , MVT::f32, Custom);
656 // Use ANDPD and ORPD to simulate FCOPYSIGN.
657 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660 // Lower this to FGETSIGNx86 plus an AND.
661 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
664 // We don't support sin/cos/fmod
665 setOperationAction(ISD::FSIN , MVT::f64, Expand);
666 setOperationAction(ISD::FCOS , MVT::f64, Expand);
667 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668 setOperationAction(ISD::FSIN , MVT::f32, Expand);
669 setOperationAction(ISD::FCOS , MVT::f32, Expand);
670 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672 // Expand FP immediates into loads from the stack, except for the special
674 addLegalFPImmediate(APFloat(+0.0)); // xorpd
675 addLegalFPImmediate(APFloat(+0.0f)); // xorps
676 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677 // Use SSE for f32, x87 for f64.
678 // Set up the FP register classes.
679 addRegisterClass(MVT::f32, &X86::FR32RegClass);
680 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682 // Use ANDPS to simulate FABS.
683 setOperationAction(ISD::FABS , MVT::f32, Custom);
685 // Use XORP to simulate FNEG.
686 setOperationAction(ISD::FNEG , MVT::f32, Custom);
688 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
690 // Use ANDPS and ORPS to simulate FCOPYSIGN.
691 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
694 // We don't support sin/cos/fmod
695 setOperationAction(ISD::FSIN , MVT::f32, Expand);
696 setOperationAction(ISD::FCOS , MVT::f32, Expand);
697 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
699 // Special cases we handle for FP constants.
700 addLegalFPImmediate(APFloat(+0.0f)); // xorps
701 addLegalFPImmediate(APFloat(+0.0)); // FLD0
702 addLegalFPImmediate(APFloat(+1.0)); // FLD1
703 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
706 if (!TM.Options.UnsafeFPMath) {
707 setOperationAction(ISD::FSIN , MVT::f64, Expand);
708 setOperationAction(ISD::FCOS , MVT::f64, Expand);
709 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
711 } else if (!TM.Options.UseSoftFloat) {
712 // f32 and f64 in x87.
713 // Set up the FP register classes.
714 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
717 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
718 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
719 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
722 if (!TM.Options.UnsafeFPMath) {
723 setOperationAction(ISD::FSIN , MVT::f64, Expand);
724 setOperationAction(ISD::FSIN , MVT::f32, Expand);
725 setOperationAction(ISD::FCOS , MVT::f64, Expand);
726 setOperationAction(ISD::FCOS , MVT::f32, Expand);
727 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
730 addLegalFPImmediate(APFloat(+0.0)); // FLD0
731 addLegalFPImmediate(APFloat(+1.0)); // FLD1
732 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740 // We don't support FMA.
741 setOperationAction(ISD::FMA, MVT::f64, Expand);
742 setOperationAction(ISD::FMA, MVT::f32, Expand);
744 // Long double always uses X87.
745 if (!TM.Options.UseSoftFloat) {
746 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
748 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
750 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751 addLegalFPImmediate(TmpFlt); // FLD0
753 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
756 APFloat TmpFlt2(+1.0);
757 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
759 addLegalFPImmediate(TmpFlt2); // FLD1
760 TmpFlt2.changeSign();
761 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
764 if (!TM.Options.UnsafeFPMath) {
765 setOperationAction(ISD::FSIN , MVT::f80, Expand);
766 setOperationAction(ISD::FCOS , MVT::f80, Expand);
767 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
772 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773 setOperationAction(ISD::FRINT, MVT::f80, Expand);
774 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775 setOperationAction(ISD::FMA, MVT::f80, Expand);
778 // Always use a library call for pow.
779 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
780 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
781 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
783 setOperationAction(ISD::FLOG, MVT::f80, Expand);
784 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786 setOperationAction(ISD::FEXP, MVT::f80, Expand);
787 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
789 // First set operation action for all vector types to either promote
790 // (for widening) or expand (for scalarization). Then we will selectively
791 // turn on ones that can be effectively codegen'd.
792 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794 MVT VT = (MVT::SimpleValueType)i;
795 setOperationAction(ISD::ADD , VT, Expand);
796 setOperationAction(ISD::SUB , VT, Expand);
797 setOperationAction(ISD::FADD, VT, Expand);
798 setOperationAction(ISD::FNEG, VT, Expand);
799 setOperationAction(ISD::FSUB, VT, Expand);
800 setOperationAction(ISD::MUL , VT, Expand);
801 setOperationAction(ISD::FMUL, VT, Expand);
802 setOperationAction(ISD::SDIV, VT, Expand);
803 setOperationAction(ISD::UDIV, VT, Expand);
804 setOperationAction(ISD::FDIV, VT, Expand);
805 setOperationAction(ISD::SREM, VT, Expand);
806 setOperationAction(ISD::UREM, VT, Expand);
807 setOperationAction(ISD::LOAD, VT, Expand);
808 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813 setOperationAction(ISD::FABS, VT, Expand);
814 setOperationAction(ISD::FSIN, VT, Expand);
815 setOperationAction(ISD::FSINCOS, VT, Expand);
816 setOperationAction(ISD::FCOS, VT, Expand);
817 setOperationAction(ISD::FSINCOS, VT, Expand);
818 setOperationAction(ISD::FREM, VT, Expand);
819 setOperationAction(ISD::FMA, VT, Expand);
820 setOperationAction(ISD::FPOWI, VT, Expand);
821 setOperationAction(ISD::FSQRT, VT, Expand);
822 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823 setOperationAction(ISD::FFLOOR, VT, Expand);
824 setOperationAction(ISD::FCEIL, VT, Expand);
825 setOperationAction(ISD::FTRUNC, VT, Expand);
826 setOperationAction(ISD::FRINT, VT, Expand);
827 setOperationAction(ISD::FNEARBYINT, VT, Expand);
828 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830 setOperationAction(ISD::SDIVREM, VT, Expand);
831 setOperationAction(ISD::UDIVREM, VT, Expand);
832 setOperationAction(ISD::FPOW, VT, Expand);
833 setOperationAction(ISD::CTPOP, VT, Expand);
834 setOperationAction(ISD::CTTZ, VT, Expand);
835 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
836 setOperationAction(ISD::CTLZ, VT, Expand);
837 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::SHL, VT, Expand);
839 setOperationAction(ISD::SRA, VT, Expand);
840 setOperationAction(ISD::SRL, VT, Expand);
841 setOperationAction(ISD::ROTL, VT, Expand);
842 setOperationAction(ISD::ROTR, VT, Expand);
843 setOperationAction(ISD::BSWAP, VT, Expand);
844 setOperationAction(ISD::SETCC, VT, Expand);
845 setOperationAction(ISD::FLOG, VT, Expand);
846 setOperationAction(ISD::FLOG2, VT, Expand);
847 setOperationAction(ISD::FLOG10, VT, Expand);
848 setOperationAction(ISD::FEXP, VT, Expand);
849 setOperationAction(ISD::FEXP2, VT, Expand);
850 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
851 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
852 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
853 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
854 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
855 setOperationAction(ISD::TRUNCATE, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
857 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
858 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
859 setOperationAction(ISD::VSELECT, VT, Expand);
860 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
861 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
862 setTruncStoreAction(VT,
863 (MVT::SimpleValueType)InnerVT, Expand);
864 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
865 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
866 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
870 // with -msoft-float, disable use of MMX as well.
871 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
872 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
873 // No operations on x86mmx supported, everything uses intrinsics.
876 // MMX-sized vectors (other than x86mmx) are expected to be expanded
877 // into smaller operations.
878 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
879 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
880 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
881 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
882 setOperationAction(ISD::AND, MVT::v8i8, Expand);
883 setOperationAction(ISD::AND, MVT::v4i16, Expand);
884 setOperationAction(ISD::AND, MVT::v2i32, Expand);
885 setOperationAction(ISD::AND, MVT::v1i64, Expand);
886 setOperationAction(ISD::OR, MVT::v8i8, Expand);
887 setOperationAction(ISD::OR, MVT::v4i16, Expand);
888 setOperationAction(ISD::OR, MVT::v2i32, Expand);
889 setOperationAction(ISD::OR, MVT::v1i64, Expand);
890 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
891 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
892 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
893 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
895 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
898 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
899 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
900 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
901 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
902 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
903 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
904 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
908 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
909 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
911 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
912 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
913 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
914 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
915 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
916 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
917 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
918 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
919 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
920 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
921 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
922 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
925 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
926 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
928 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
929 // registers cannot be used even for integer operations.
930 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
931 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
932 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
933 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
935 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
936 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
937 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
938 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
939 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
940 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
941 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
942 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
943 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
944 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
945 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
946 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
947 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
948 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
949 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
950 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
951 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
952 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
954 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
955 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
956 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
957 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
959 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
960 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
961 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
965 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
966 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
967 MVT VT = (MVT::SimpleValueType)i;
968 // Do not attempt to custom lower non-power-of-2 vectors
969 if (!isPowerOf2_32(VT.getVectorNumElements()))
971 // Do not attempt to custom lower non-128-bit vectors
972 if (!VT.is128BitVector())
974 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
975 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
976 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
980 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
981 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
982 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
983 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
984 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
986 if (Subtarget->is64Bit()) {
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
992 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
993 MVT VT = (MVT::SimpleValueType)i;
995 // Do not attempt to promote non-128-bit vectors
996 if (!VT.is128BitVector())
999 setOperationAction(ISD::AND, VT, Promote);
1000 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1001 setOperationAction(ISD::OR, VT, Promote);
1002 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1003 setOperationAction(ISD::XOR, VT, Promote);
1004 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1005 setOperationAction(ISD::LOAD, VT, Promote);
1006 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1007 setOperationAction(ISD::SELECT, VT, Promote);
1008 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1011 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1013 // Custom lower v2i64 and v2f64 selects.
1014 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1015 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1016 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1017 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1019 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1020 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1022 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1023 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1024 // As there is no 64-bit GPR available, we need build a special custom
1025 // sequence to convert from v2i32 to v2f32.
1026 if (!Subtarget->is64Bit())
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1029 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1030 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1032 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1035 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1036 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1037 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1038 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1039 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1040 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1041 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1042 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1043 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1044 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1045 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1047 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1048 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1049 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1050 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1051 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1058 // FIXME: Do we need to handle scalar-to-vector here?
1059 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1061 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1062 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1063 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1064 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1067 // i8 and i16 vectors are custom , because the source register and source
1068 // source memory operand types are not the same width. f32 vectors are
1069 // custom since the immediate controlling the insert encodes additional
1071 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1072 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1073 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1076 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1077 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1078 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1081 // FIXME: these should be Legal but thats only for the case where
1082 // the index is constant. For now custom expand to deal with that.
1083 if (Subtarget->is64Bit()) {
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1089 if (Subtarget->hasSSE2()) {
1090 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1091 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1093 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1094 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1096 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1099 // In the customized shift lowering, the legal cases in AVX2 will be
1101 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1102 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1104 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1105 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1107 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1109 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1110 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1113 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1114 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1115 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1116 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1117 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1121 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1122 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1123 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1125 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1126 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1127 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1128 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1136 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1138 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1139 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1140 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1141 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1149 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1151 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1152 // even though v8i16 is a legal type.
1153 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1154 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1155 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1157 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1158 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1159 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1161 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1162 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1164 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1166 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1167 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1169 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1177 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1182 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1183 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1184 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1186 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1187 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1188 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1189 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1191 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1192 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1193 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1194 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1195 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1197 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1200 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1201 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1202 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1204 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1205 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1206 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1208 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1209 setOperationAction(ISD::FMA, MVT::f32, Legal);
1210 setOperationAction(ISD::FMA, MVT::f64, Legal);
1213 if (Subtarget->hasInt256()) {
1214 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1215 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1216 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1217 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1219 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1220 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1221 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1222 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1224 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1225 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1226 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1227 // Don't lower v32i8 because there is no 128-bit byte mul
1229 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1231 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1233 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1234 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1235 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1236 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1238 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1239 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1240 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1241 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1243 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1244 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1245 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1246 // Don't lower v32i8 because there is no 128-bit byte mul
1249 // In the customized shift lowering, the legal cases in AVX2 will be
1251 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1254 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1255 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1257 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1259 // Custom lower several nodes for 256-bit types.
1260 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1261 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1262 MVT VT = (MVT::SimpleValueType)i;
1264 // Extract subvector is special because the value type
1265 // (result) is 128-bit but the source is 256-bit wide.
1266 if (VT.is128BitVector())
1267 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1269 // Do not attempt to custom lower other non-256-bit vectors
1270 if (!VT.is256BitVector())
1273 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1274 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1275 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1276 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1277 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1278 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1279 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1282 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284 MVT VT = (MVT::SimpleValueType)i;
1286 // Do not attempt to promote non-256-bit vectors
1287 if (!VT.is256BitVector())
1290 setOperationAction(ISD::AND, VT, Promote);
1291 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1292 setOperationAction(ISD::OR, VT, Promote);
1293 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1294 setOperationAction(ISD::XOR, VT, Promote);
1295 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1296 setOperationAction(ISD::LOAD, VT, Promote);
1297 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1298 setOperationAction(ISD::SELECT, VT, Promote);
1299 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1303 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1304 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1307 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1309 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1310 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1311 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1313 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1314 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1315 setOperationAction(ISD::XOR, MVT::i1, Legal);
1316 setOperationAction(ISD::OR, MVT::i1, Legal);
1317 setOperationAction(ISD::AND, MVT::i1, Legal);
1318 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1319 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1320 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1321 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1322 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1323 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1325 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1326 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1327 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1328 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1329 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1330 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1332 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1333 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1334 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1335 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1336 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1338 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1340 setOperationAction(ISD::SDIV, MVT::v16i32, Custom);
1342 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1343 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1344 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1346 if (Subtarget->is64Bit()) {
1347 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1348 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1349 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1350 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1352 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1353 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1354 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1355 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1356 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1357 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1358 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1359 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1360 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1361 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1363 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1364 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1365 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1366 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1369 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1370 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1371 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1372 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1373 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1374 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1377 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1378 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1379 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1380 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1384 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1385 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1387 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1393 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1394 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1395 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1396 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1397 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1399 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1400 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1402 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1403 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1405 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1407 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1408 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1410 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1411 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1413 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1414 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1416 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1417 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1418 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1419 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1420 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1421 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1423 // Custom lower several nodes.
1424 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1425 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1426 MVT VT = (MVT::SimpleValueType)i;
1428 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1429 // Extract subvector is special because the value type
1430 // (result) is 256/128-bit but the source is 512-bit wide.
1431 if (VT.is128BitVector() || VT.is256BitVector())
1432 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1434 if (VT.getVectorElementType() == MVT::i1)
1435 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1437 // Do not attempt to custom lower other non-512-bit vectors
1438 if (!VT.is512BitVector())
1441 if ( EltSize >= 32) {
1442 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1443 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1444 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1445 setOperationAction(ISD::VSELECT, VT, Legal);
1446 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1447 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1448 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1451 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1452 MVT VT = (MVT::SimpleValueType)i;
1454 // Do not attempt to promote non-256-bit vectors
1455 if (!VT.is512BitVector())
1458 setOperationAction(ISD::SELECT, VT, Promote);
1459 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1463 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1464 // of this type with custom code.
1465 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1466 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1467 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1471 // We want to custom lower some of our intrinsics.
1472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1474 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1476 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1477 // handle type legalization for these operations here.
1479 // FIXME: We really should do custom legalization for addition and
1480 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1481 // than generic legalization for 64-bit multiplication-with-overflow, though.
1482 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1483 // Add/Sub/Mul with overflow operations are custom lowered.
1485 setOperationAction(ISD::SADDO, VT, Custom);
1486 setOperationAction(ISD::UADDO, VT, Custom);
1487 setOperationAction(ISD::SSUBO, VT, Custom);
1488 setOperationAction(ISD::USUBO, VT, Custom);
1489 setOperationAction(ISD::SMULO, VT, Custom);
1490 setOperationAction(ISD::UMULO, VT, Custom);
1493 // There are no 8-bit 3-address imul/mul instructions
1494 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1495 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1497 if (!Subtarget->is64Bit()) {
1498 // These libcalls are not available in 32-bit.
1499 setLibcallName(RTLIB::SHL_I128, 0);
1500 setLibcallName(RTLIB::SRL_I128, 0);
1501 setLibcallName(RTLIB::SRA_I128, 0);
1504 // Combine sin / cos into one node or libcall if possible.
1505 if (Subtarget->hasSinCos()) {
1506 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1507 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1508 if (Subtarget->isTargetDarwin()) {
1509 // For MacOSX, we don't want to the normal expansion of a libcall to
1510 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1512 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1513 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1517 // We have target-specific dag combine patterns for the following nodes:
1518 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1519 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1520 setTargetDAGCombine(ISD::VSELECT);
1521 setTargetDAGCombine(ISD::SELECT);
1522 setTargetDAGCombine(ISD::SHL);
1523 setTargetDAGCombine(ISD::SRA);
1524 setTargetDAGCombine(ISD::SRL);
1525 setTargetDAGCombine(ISD::OR);
1526 setTargetDAGCombine(ISD::AND);
1527 setTargetDAGCombine(ISD::ADD);
1528 setTargetDAGCombine(ISD::FADD);
1529 setTargetDAGCombine(ISD::FSUB);
1530 setTargetDAGCombine(ISD::FMA);
1531 setTargetDAGCombine(ISD::SUB);
1532 setTargetDAGCombine(ISD::LOAD);
1533 setTargetDAGCombine(ISD::STORE);
1534 setTargetDAGCombine(ISD::ZERO_EXTEND);
1535 setTargetDAGCombine(ISD::ANY_EXTEND);
1536 setTargetDAGCombine(ISD::SIGN_EXTEND);
1537 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1538 setTargetDAGCombine(ISD::TRUNCATE);
1539 setTargetDAGCombine(ISD::SINT_TO_FP);
1540 setTargetDAGCombine(ISD::SETCC);
1541 if (Subtarget->is64Bit())
1542 setTargetDAGCombine(ISD::MUL);
1543 setTargetDAGCombine(ISD::XOR);
1545 computeRegisterProperties();
1547 // On Darwin, -Os means optimize for size without hurting performance,
1548 // do not reduce the limit.
1549 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1550 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1551 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1552 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1553 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1554 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1555 setPrefLoopAlignment(4); // 2^4 bytes.
1557 // Predictable cmov don't hurt on atom because it's in-order.
1558 PredictableSelectIsExpensive = !Subtarget->isAtom();
1560 setPrefFunctionAlignment(4); // 2^4 bytes.
1563 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1565 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1567 if (Subtarget->hasAVX512())
1568 switch(VT.getVectorNumElements()) {
1569 case 8: return MVT::v8i1;
1570 case 16: return MVT::v16i1;
1573 return VT.changeVectorElementTypeToInteger();
1576 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1577 /// the desired ByVal argument alignment.
1578 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1581 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1582 if (VTy->getBitWidth() == 128)
1584 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1585 unsigned EltAlign = 0;
1586 getMaxByValAlign(ATy->getElementType(), EltAlign);
1587 if (EltAlign > MaxAlign)
1588 MaxAlign = EltAlign;
1589 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1590 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1591 unsigned EltAlign = 0;
1592 getMaxByValAlign(STy->getElementType(i), EltAlign);
1593 if (EltAlign > MaxAlign)
1594 MaxAlign = EltAlign;
1601 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1602 /// function arguments in the caller parameter area. For X86, aggregates
1603 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1604 /// are at 4-byte boundaries.
1605 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1606 if (Subtarget->is64Bit()) {
1607 // Max of 8 and alignment of type.
1608 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1615 if (Subtarget->hasSSE1())
1616 getMaxByValAlign(Ty, Align);
1620 /// getOptimalMemOpType - Returns the target specific optimal type for load
1621 /// and store operations as a result of memset, memcpy, and memmove
1622 /// lowering. If DstAlign is zero that means it's safe to destination
1623 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1624 /// means there isn't a need to check it against alignment requirement,
1625 /// probably because the source does not need to be loaded. If 'IsMemset' is
1626 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1627 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1628 /// source is constant so it does not need to be loaded.
1629 /// It returns EVT::Other if the type should be determined using generic
1630 /// target-independent logic.
1632 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1633 unsigned DstAlign, unsigned SrcAlign,
1634 bool IsMemset, bool ZeroMemset,
1636 MachineFunction &MF) const {
1637 const Function *F = MF.getFunction();
1638 if ((!IsMemset || ZeroMemset) &&
1639 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1640 Attribute::NoImplicitFloat)) {
1642 (Subtarget->isUnalignedMemAccessFast() ||
1643 ((DstAlign == 0 || DstAlign >= 16) &&
1644 (SrcAlign == 0 || SrcAlign >= 16)))) {
1646 if (Subtarget->hasInt256())
1648 if (Subtarget->hasFp256())
1651 if (Subtarget->hasSSE2())
1653 if (Subtarget->hasSSE1())
1655 } else if (!MemcpyStrSrc && Size >= 8 &&
1656 !Subtarget->is64Bit() &&
1657 Subtarget->hasSSE2()) {
1658 // Do not use f64 to lower memcpy if source is string constant. It's
1659 // better to use i32 to avoid the loads.
1663 if (Subtarget->is64Bit() && Size >= 8)
1668 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1670 return X86ScalarSSEf32;
1671 else if (VT == MVT::f64)
1672 return X86ScalarSSEf64;
1677 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1681 *Fast = Subtarget->isUnalignedMemAccessFast();
1685 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1686 /// current function. The returned value is a member of the
1687 /// MachineJumpTableInfo::JTEntryKind enum.
1688 unsigned X86TargetLowering::getJumpTableEncoding() const {
1689 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1691 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1692 Subtarget->isPICStyleGOT())
1693 return MachineJumpTableInfo::EK_Custom32;
1695 // Otherwise, use the normal jump table encoding heuristics.
1696 return TargetLowering::getJumpTableEncoding();
1700 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1701 const MachineBasicBlock *MBB,
1702 unsigned uid,MCContext &Ctx) const{
1703 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1704 Subtarget->isPICStyleGOT());
1705 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1707 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1708 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1711 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1713 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1714 SelectionDAG &DAG) const {
1715 if (!Subtarget->is64Bit())
1716 // This doesn't have SDLoc associated with it, but is not really the
1717 // same as a Register.
1718 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1722 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1723 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1725 const MCExpr *X86TargetLowering::
1726 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1727 MCContext &Ctx) const {
1728 // X86-64 uses RIP relative addressing based on the jump table label.
1729 if (Subtarget->isPICStyleRIPRel())
1730 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1732 // Otherwise, the reference is relative to the PIC base.
1733 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1736 // FIXME: Why this routine is here? Move to RegInfo!
1737 std::pair<const TargetRegisterClass*, uint8_t>
1738 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1739 const TargetRegisterClass *RRC = 0;
1741 switch (VT.SimpleTy) {
1743 return TargetLowering::findRepresentativeClass(VT);
1744 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1745 RRC = Subtarget->is64Bit() ?
1746 (const TargetRegisterClass*)&X86::GR64RegClass :
1747 (const TargetRegisterClass*)&X86::GR32RegClass;
1750 RRC = &X86::VR64RegClass;
1752 case MVT::f32: case MVT::f64:
1753 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1754 case MVT::v4f32: case MVT::v2f64:
1755 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1757 RRC = &X86::VR128RegClass;
1760 return std::make_pair(RRC, Cost);
1763 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1764 unsigned &Offset) const {
1765 if (!Subtarget->isTargetLinux())
1768 if (Subtarget->is64Bit()) {
1769 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1771 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1783 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1784 unsigned DestAS) const {
1785 assert(SrcAS != DestAS && "Expected different address spaces!");
1787 return SrcAS < 256 && DestAS < 256;
1790 //===----------------------------------------------------------------------===//
1791 // Return Value Calling Convention Implementation
1792 //===----------------------------------------------------------------------===//
1794 #include "X86GenCallingConv.inc"
1797 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1798 MachineFunction &MF, bool isVarArg,
1799 const SmallVectorImpl<ISD::OutputArg> &Outs,
1800 LLVMContext &Context) const {
1801 SmallVector<CCValAssign, 16> RVLocs;
1802 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1804 return CCInfo.CheckReturn(Outs, RetCC_X86);
1807 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1808 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1813 X86TargetLowering::LowerReturn(SDValue Chain,
1814 CallingConv::ID CallConv, bool isVarArg,
1815 const SmallVectorImpl<ISD::OutputArg> &Outs,
1816 const SmallVectorImpl<SDValue> &OutVals,
1817 SDLoc dl, SelectionDAG &DAG) const {
1818 MachineFunction &MF = DAG.getMachineFunction();
1819 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1821 SmallVector<CCValAssign, 16> RVLocs;
1822 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1823 RVLocs, *DAG.getContext());
1824 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1827 SmallVector<SDValue, 6> RetOps;
1828 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1829 // Operand #1 = Bytes To Pop
1830 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1833 // Copy the result values into the output registers.
1834 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1835 CCValAssign &VA = RVLocs[i];
1836 assert(VA.isRegLoc() && "Can only return in registers!");
1837 SDValue ValToCopy = OutVals[i];
1838 EVT ValVT = ValToCopy.getValueType();
1840 // Promote values to the appropriate types
1841 if (VA.getLocInfo() == CCValAssign::SExt)
1842 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1843 else if (VA.getLocInfo() == CCValAssign::ZExt)
1844 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1845 else if (VA.getLocInfo() == CCValAssign::AExt)
1846 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1847 else if (VA.getLocInfo() == CCValAssign::BCvt)
1848 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1850 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1851 "Unexpected FP-extend for return value.");
1853 // If this is x86-64, and we disabled SSE, we can't return FP values,
1854 // or SSE or MMX vectors.
1855 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1856 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1857 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1858 report_fatal_error("SSE register return with SSE disabled");
1860 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1861 // llvm-gcc has never done it right and no one has noticed, so this
1862 // should be OK for now.
1863 if (ValVT == MVT::f64 &&
1864 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1865 report_fatal_error("SSE2 register return with SSE2 disabled");
1867 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1868 // the RET instruction and handled by the FP Stackifier.
1869 if (VA.getLocReg() == X86::ST0 ||
1870 VA.getLocReg() == X86::ST1) {
1871 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1872 // change the value to the FP stack register class.
1873 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1874 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1875 RetOps.push_back(ValToCopy);
1876 // Don't emit a copytoreg.
1880 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1881 // which is returned in RAX / RDX.
1882 if (Subtarget->is64Bit()) {
1883 if (ValVT == MVT::x86mmx) {
1884 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1885 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1886 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1888 // If we don't have SSE2 available, convert to v4f32 so the generated
1889 // register is legal.
1890 if (!Subtarget->hasSSE2())
1891 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1896 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1897 Flag = Chain.getValue(1);
1898 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1901 // The x86-64 ABIs require that for returning structs by value we copy
1902 // the sret argument into %rax/%eax (depending on ABI) for the return.
1903 // Win32 requires us to put the sret argument to %eax as well.
1904 // We saved the argument into a virtual register in the entry block,
1905 // so now we copy the value out and into %rax/%eax.
1906 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1907 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1908 MachineFunction &MF = DAG.getMachineFunction();
1909 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1910 unsigned Reg = FuncInfo->getSRetReturnReg();
1912 "SRetReturnReg should have been set in LowerFormalArguments().");
1913 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1916 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1917 X86::RAX : X86::EAX;
1918 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1919 Flag = Chain.getValue(1);
1921 // RAX/EAX now acts like a return value.
1922 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1925 RetOps[0] = Chain; // Update chain.
1927 // Add the flag if we have it.
1929 RetOps.push_back(Flag);
1931 return DAG.getNode(X86ISD::RET_FLAG, dl,
1932 MVT::Other, &RetOps[0], RetOps.size());
1935 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1936 if (N->getNumValues() != 1)
1938 if (!N->hasNUsesOfValue(1, 0))
1941 SDValue TCChain = Chain;
1942 SDNode *Copy = *N->use_begin();
1943 if (Copy->getOpcode() == ISD::CopyToReg) {
1944 // If the copy has a glue operand, we conservatively assume it isn't safe to
1945 // perform a tail call.
1946 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1948 TCChain = Copy->getOperand(0);
1949 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1952 bool HasRet = false;
1953 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1955 if (UI->getOpcode() != X86ISD::RET_FLAG)
1968 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1969 ISD::NodeType ExtendKind) const {
1971 // TODO: Is this also valid on 32-bit?
1972 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1973 ReturnMVT = MVT::i8;
1975 ReturnMVT = MVT::i32;
1977 MVT MinVT = getRegisterType(ReturnMVT);
1978 return VT.bitsLT(MinVT) ? MinVT : VT;
1981 /// LowerCallResult - Lower the result values of a call into the
1982 /// appropriate copies out of appropriate physical registers.
1985 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1986 CallingConv::ID CallConv, bool isVarArg,
1987 const SmallVectorImpl<ISD::InputArg> &Ins,
1988 SDLoc dl, SelectionDAG &DAG,
1989 SmallVectorImpl<SDValue> &InVals) const {
1991 // Assign locations to each value returned by this call.
1992 SmallVector<CCValAssign, 16> RVLocs;
1993 bool Is64Bit = Subtarget->is64Bit();
1994 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1995 getTargetMachine(), RVLocs, *DAG.getContext());
1996 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1998 // Copy all of the result registers out of their specified physreg.
1999 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2000 CCValAssign &VA = RVLocs[i];
2001 EVT CopyVT = VA.getValVT();
2003 // If this is x86-64, and we disabled SSE, we can't return FP values
2004 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2005 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2006 report_fatal_error("SSE register return with SSE disabled");
2011 // If this is a call to a function that returns an fp value on the floating
2012 // point stack, we must guarantee the value is popped from the stack, so
2013 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2014 // if the return value is not used. We use the FpPOP_RETVAL instruction
2016 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2017 // If we prefer to use the value in xmm registers, copy it out as f80 and
2018 // use a truncate to move it from fp stack reg to xmm reg.
2019 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2020 SDValue Ops[] = { Chain, InFlag };
2021 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2022 MVT::Other, MVT::Glue, Ops), 1);
2023 Val = Chain.getValue(0);
2025 // Round the f80 to the right size, which also moves it to the appropriate
2027 if (CopyVT != VA.getValVT())
2028 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2029 // This truncation won't change the value.
2030 DAG.getIntPtrConstant(1));
2032 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2033 CopyVT, InFlag).getValue(1);
2034 Val = Chain.getValue(0);
2036 InFlag = Chain.getValue(2);
2037 InVals.push_back(Val);
2043 //===----------------------------------------------------------------------===//
2044 // C & StdCall & Fast Calling Convention implementation
2045 //===----------------------------------------------------------------------===//
2046 // StdCall calling convention seems to be standard for many Windows' API
2047 // routines and around. It differs from C calling convention just a little:
2048 // callee should clean up the stack, not caller. Symbols should be also
2049 // decorated in some fancy way :) It doesn't support any vector arguments.
2050 // For info on fast calling convention see Fast Calling Convention (tail call)
2051 // implementation LowerX86_32FastCCCallTo.
2053 /// CallIsStructReturn - Determines whether a call uses struct return
2055 enum StructReturnType {
2060 static StructReturnType
2061 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2063 return NotStructReturn;
2065 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2066 if (!Flags.isSRet())
2067 return NotStructReturn;
2068 if (Flags.isInReg())
2069 return RegStructReturn;
2070 return StackStructReturn;
2073 /// ArgsAreStructReturn - Determines whether a function uses struct
2074 /// return semantics.
2075 static StructReturnType
2076 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2078 return NotStructReturn;
2080 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2081 if (!Flags.isSRet())
2082 return NotStructReturn;
2083 if (Flags.isInReg())
2084 return RegStructReturn;
2085 return StackStructReturn;
2088 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2089 /// by "Src" to address "Dst" with size and alignment information specified by
2090 /// the specific parameter attribute. The copy will be passed as a byval
2091 /// function parameter.
2093 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2094 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2096 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2098 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2099 /*isVolatile*/false, /*AlwaysInline=*/true,
2100 MachinePointerInfo(), MachinePointerInfo());
2103 /// IsTailCallConvention - Return true if the calling convention is one that
2104 /// supports tail call optimization.
2105 static bool IsTailCallConvention(CallingConv::ID CC) {
2106 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2107 CC == CallingConv::HiPE);
2110 /// \brief Return true if the calling convention is a C calling convention.
2111 static bool IsCCallConvention(CallingConv::ID CC) {
2112 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2113 CC == CallingConv::X86_64_SysV);
2116 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2117 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2121 CallingConv::ID CalleeCC = CS.getCallingConv();
2122 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2128 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2129 /// a tailcall target by changing its ABI.
2130 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2131 bool GuaranteedTailCallOpt) {
2132 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2136 X86TargetLowering::LowerMemArgument(SDValue Chain,
2137 CallingConv::ID CallConv,
2138 const SmallVectorImpl<ISD::InputArg> &Ins,
2139 SDLoc dl, SelectionDAG &DAG,
2140 const CCValAssign &VA,
2141 MachineFrameInfo *MFI,
2143 // Create the nodes corresponding to a load from this parameter slot.
2144 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2145 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2146 getTargetMachine().Options.GuaranteedTailCallOpt);
2147 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2150 // If value is passed by pointer we have address passed instead of the value
2152 if (VA.getLocInfo() == CCValAssign::Indirect)
2153 ValVT = VA.getLocVT();
2155 ValVT = VA.getValVT();
2157 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2158 // changed with more analysis.
2159 // In case of tail call optimization mark all arguments mutable. Since they
2160 // could be overwritten by lowering of arguments in case of a tail call.
2161 if (Flags.isByVal()) {
2162 unsigned Bytes = Flags.getByValSize();
2163 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2164 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2165 return DAG.getFrameIndex(FI, getPointerTy());
2167 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2168 VA.getLocMemOffset(), isImmutable);
2169 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2170 return DAG.getLoad(ValVT, dl, Chain, FIN,
2171 MachinePointerInfo::getFixedStack(FI),
2172 false, false, false, 0);
2177 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2178 CallingConv::ID CallConv,
2180 const SmallVectorImpl<ISD::InputArg> &Ins,
2183 SmallVectorImpl<SDValue> &InVals)
2185 MachineFunction &MF = DAG.getMachineFunction();
2186 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2188 const Function* Fn = MF.getFunction();
2189 if (Fn->hasExternalLinkage() &&
2190 Subtarget->isTargetCygMing() &&
2191 Fn->getName() == "main")
2192 FuncInfo->setForceFramePointer(true);
2194 MachineFrameInfo *MFI = MF.getFrameInfo();
2195 bool Is64Bit = Subtarget->is64Bit();
2196 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2198 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2199 "Var args not supported with calling convention fastcc, ghc or hipe");
2201 // Assign locations to all of the incoming arguments.
2202 SmallVector<CCValAssign, 16> ArgLocs;
2203 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2204 ArgLocs, *DAG.getContext());
2206 // Allocate shadow area for Win64
2208 CCInfo.AllocateStack(32, 8);
2210 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2212 unsigned LastVal = ~0U;
2214 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2215 CCValAssign &VA = ArgLocs[i];
2216 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2218 assert(VA.getValNo() != LastVal &&
2219 "Don't support value assigned to multiple locs yet");
2221 LastVal = VA.getValNo();
2223 if (VA.isRegLoc()) {
2224 EVT RegVT = VA.getLocVT();
2225 const TargetRegisterClass *RC;
2226 if (RegVT == MVT::i32)
2227 RC = &X86::GR32RegClass;
2228 else if (Is64Bit && RegVT == MVT::i64)
2229 RC = &X86::GR64RegClass;
2230 else if (RegVT == MVT::f32)
2231 RC = &X86::FR32RegClass;
2232 else if (RegVT == MVT::f64)
2233 RC = &X86::FR64RegClass;
2234 else if (RegVT.is512BitVector())
2235 RC = &X86::VR512RegClass;
2236 else if (RegVT.is256BitVector())
2237 RC = &X86::VR256RegClass;
2238 else if (RegVT.is128BitVector())
2239 RC = &X86::VR128RegClass;
2240 else if (RegVT == MVT::x86mmx)
2241 RC = &X86::VR64RegClass;
2242 else if (RegVT == MVT::i1)
2243 RC = &X86::VK1RegClass;
2244 else if (RegVT == MVT::v8i1)
2245 RC = &X86::VK8RegClass;
2246 else if (RegVT == MVT::v16i1)
2247 RC = &X86::VK16RegClass;
2249 llvm_unreachable("Unknown argument type!");
2251 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2252 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2254 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2255 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2257 if (VA.getLocInfo() == CCValAssign::SExt)
2258 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2259 DAG.getValueType(VA.getValVT()));
2260 else if (VA.getLocInfo() == CCValAssign::ZExt)
2261 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2262 DAG.getValueType(VA.getValVT()));
2263 else if (VA.getLocInfo() == CCValAssign::BCvt)
2264 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2266 if (VA.isExtInLoc()) {
2267 // Handle MMX values passed in XMM regs.
2268 if (RegVT.isVector())
2269 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2271 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2274 assert(VA.isMemLoc());
2275 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2278 // If value is passed via pointer - do a load.
2279 if (VA.getLocInfo() == CCValAssign::Indirect)
2280 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2281 MachinePointerInfo(), false, false, false, 0);
2283 InVals.push_back(ArgValue);
2286 // The x86-64 ABIs require that for returning structs by value we copy
2287 // the sret argument into %rax/%eax (depending on ABI) for the return.
2288 // Win32 requires us to put the sret argument to %eax as well.
2289 // Save the argument into a virtual register so that we can access it
2290 // from the return points.
2291 if (MF.getFunction()->hasStructRetAttr() &&
2292 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2293 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2294 unsigned Reg = FuncInfo->getSRetReturnReg();
2296 MVT PtrTy = getPointerTy();
2297 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2298 FuncInfo->setSRetReturnReg(Reg);
2300 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2301 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2304 unsigned StackSize = CCInfo.getNextStackOffset();
2305 // Align stack specially for tail calls.
2306 if (FuncIsMadeTailCallSafe(CallConv,
2307 MF.getTarget().Options.GuaranteedTailCallOpt))
2308 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2310 // If the function takes variable number of arguments, make a frame index for
2311 // the start of the first vararg value... for expansion of llvm.va_start.
2313 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2314 CallConv != CallingConv::X86_ThisCall)) {
2315 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2318 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2320 // FIXME: We should really autogenerate these arrays
2321 static const MCPhysReg GPR64ArgRegsWin64[] = {
2322 X86::RCX, X86::RDX, X86::R8, X86::R9
2324 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2325 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2327 static const MCPhysReg XMMArgRegs64Bit[] = {
2328 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2329 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2331 const MCPhysReg *GPR64ArgRegs;
2332 unsigned NumXMMRegs = 0;
2335 // The XMM registers which might contain var arg parameters are shadowed
2336 // in their paired GPR. So we only need to save the GPR to their home
2338 TotalNumIntRegs = 4;
2339 GPR64ArgRegs = GPR64ArgRegsWin64;
2341 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2342 GPR64ArgRegs = GPR64ArgRegs64Bit;
2344 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2347 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2350 bool NoImplicitFloatOps = Fn->getAttributes().
2351 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2352 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2353 "SSE register cannot be used when SSE is disabled!");
2354 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2355 NoImplicitFloatOps) &&
2356 "SSE register cannot be used when SSE is disabled!");
2357 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2358 !Subtarget->hasSSE1())
2359 // Kernel mode asks for SSE to be disabled, so don't push them
2361 TotalNumXMMRegs = 0;
2364 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2365 // Get to the caller-allocated home save location. Add 8 to account
2366 // for the return address.
2367 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2368 FuncInfo->setRegSaveFrameIndex(
2369 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2370 // Fixup to set vararg frame on shadow area (4 x i64).
2372 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2374 // For X86-64, if there are vararg parameters that are passed via
2375 // registers, then we must store them to their spots on the stack so
2376 // they may be loaded by deferencing the result of va_next.
2377 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2378 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2379 FuncInfo->setRegSaveFrameIndex(
2380 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2384 // Store the integer parameter registers.
2385 SmallVector<SDValue, 8> MemOps;
2386 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2388 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2389 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2390 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2391 DAG.getIntPtrConstant(Offset));
2392 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2393 &X86::GR64RegClass);
2394 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2396 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2397 MachinePointerInfo::getFixedStack(
2398 FuncInfo->getRegSaveFrameIndex(), Offset),
2400 MemOps.push_back(Store);
2404 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2405 // Now store the XMM (fp + vector) parameter registers.
2406 SmallVector<SDValue, 11> SaveXMMOps;
2407 SaveXMMOps.push_back(Chain);
2409 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2410 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2411 SaveXMMOps.push_back(ALVal);
2413 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2414 FuncInfo->getRegSaveFrameIndex()));
2415 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2416 FuncInfo->getVarArgsFPOffset()));
2418 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2419 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2420 &X86::VR128RegClass);
2421 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2422 SaveXMMOps.push_back(Val);
2424 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2426 &SaveXMMOps[0], SaveXMMOps.size()));
2429 if (!MemOps.empty())
2430 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2431 &MemOps[0], MemOps.size());
2435 // Some CCs need callee pop.
2436 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2437 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2438 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2440 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2441 // If this is an sret function, the return should pop the hidden pointer.
2442 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2443 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2444 argsAreStructReturn(Ins) == StackStructReturn)
2445 FuncInfo->setBytesToPopOnReturn(4);
2449 // RegSaveFrameIndex is X86-64 only.
2450 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2451 if (CallConv == CallingConv::X86_FastCall ||
2452 CallConv == CallingConv::X86_ThisCall)
2453 // fastcc functions can't have varargs.
2454 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2457 FuncInfo->setArgumentStackSize(StackSize);
2463 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2464 SDValue StackPtr, SDValue Arg,
2465 SDLoc dl, SelectionDAG &DAG,
2466 const CCValAssign &VA,
2467 ISD::ArgFlagsTy Flags) const {
2468 unsigned LocMemOffset = VA.getLocMemOffset();
2469 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2470 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2471 if (Flags.isByVal())
2472 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2474 return DAG.getStore(Chain, dl, Arg, PtrOff,
2475 MachinePointerInfo::getStack(LocMemOffset),
2479 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2480 /// optimization is performed and it is required.
2482 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2483 SDValue &OutRetAddr, SDValue Chain,
2484 bool IsTailCall, bool Is64Bit,
2485 int FPDiff, SDLoc dl) const {
2486 // Adjust the Return address stack slot.
2487 EVT VT = getPointerTy();
2488 OutRetAddr = getReturnAddressFrameIndex(DAG);
2490 // Load the "old" Return address.
2491 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2492 false, false, false, 0);
2493 return SDValue(OutRetAddr.getNode(), 1);
2496 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2497 /// optimization is performed and it is required (FPDiff!=0).
2499 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2500 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2501 unsigned SlotSize, int FPDiff, SDLoc dl) {
2502 // Store the return address to the appropriate stack slot.
2503 if (!FPDiff) return Chain;
2504 // Calculate the new stack slot for the return address.
2505 int NewReturnAddrFI =
2506 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2508 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2509 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2510 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2516 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2517 SmallVectorImpl<SDValue> &InVals) const {
2518 SelectionDAG &DAG = CLI.DAG;
2520 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2521 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2522 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2523 SDValue Chain = CLI.Chain;
2524 SDValue Callee = CLI.Callee;
2525 CallingConv::ID CallConv = CLI.CallConv;
2526 bool &isTailCall = CLI.IsTailCall;
2527 bool isVarArg = CLI.IsVarArg;
2529 MachineFunction &MF = DAG.getMachineFunction();
2530 bool Is64Bit = Subtarget->is64Bit();
2531 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2532 StructReturnType SR = callIsStructReturn(Outs);
2533 bool IsSibcall = false;
2535 if (MF.getTarget().Options.DisableTailCalls)
2539 // Check if it's really possible to do a tail call.
2540 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2541 isVarArg, SR != NotStructReturn,
2542 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2543 Outs, OutVals, Ins, DAG);
2545 // Sibcalls are automatically detected tailcalls which do not require
2547 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2554 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2555 "Var args not supported with calling convention fastcc, ghc or hipe");
2557 // Analyze operands of the call, assigning locations to each operand.
2558 SmallVector<CCValAssign, 16> ArgLocs;
2559 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2560 ArgLocs, *DAG.getContext());
2562 // Allocate shadow area for Win64
2564 CCInfo.AllocateStack(32, 8);
2566 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2568 // Get a count of how many bytes are to be pushed on the stack.
2569 unsigned NumBytes = CCInfo.getNextStackOffset();
2571 // This is a sibcall. The memory operands are available in caller's
2572 // own caller's stack.
2574 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2575 IsTailCallConvention(CallConv))
2576 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2579 if (isTailCall && !IsSibcall) {
2580 // Lower arguments at fp - stackoffset + fpdiff.
2581 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2582 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2584 FPDiff = NumBytesCallerPushed - NumBytes;
2586 // Set the delta of movement of the returnaddr stackslot.
2587 // But only set if delta is greater than previous delta.
2588 if (FPDiff < X86Info->getTCReturnAddrDelta())
2589 X86Info->setTCReturnAddrDelta(FPDiff);
2592 unsigned NumBytesToPush = NumBytes;
2593 unsigned NumBytesToPop = NumBytes;
2595 // If we have an inalloca argument, all stack space has already been allocated
2596 // for us and be right at the top of the stack. We don't support multiple
2597 // arguments passed in memory when using inalloca.
2598 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2600 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2601 "an inalloca argument must be the only memory argument");
2605 Chain = DAG.getCALLSEQ_START(
2606 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2608 SDValue RetAddrFrIdx;
2609 // Load return address for tail calls.
2610 if (isTailCall && FPDiff)
2611 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2612 Is64Bit, FPDiff, dl);
2614 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2615 SmallVector<SDValue, 8> MemOpChains;
2618 // Walk the register/memloc assignments, inserting copies/loads. In the case
2619 // of tail call optimization arguments are handle later.
2620 const X86RegisterInfo *RegInfo =
2621 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2622 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2623 // Skip inalloca arguments, they have already been written.
2624 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2625 if (Flags.isInAlloca())
2628 CCValAssign &VA = ArgLocs[i];
2629 EVT RegVT = VA.getLocVT();
2630 SDValue Arg = OutVals[i];
2631 bool isByVal = Flags.isByVal();
2633 // Promote the value if needed.
2634 switch (VA.getLocInfo()) {
2635 default: llvm_unreachable("Unknown loc info!");
2636 case CCValAssign::Full: break;
2637 case CCValAssign::SExt:
2638 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2640 case CCValAssign::ZExt:
2641 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2643 case CCValAssign::AExt:
2644 if (RegVT.is128BitVector()) {
2645 // Special case: passing MMX values in XMM registers.
2646 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2647 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2648 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2650 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2652 case CCValAssign::BCvt:
2653 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2655 case CCValAssign::Indirect: {
2656 // Store the argument.
2657 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2658 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2659 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2660 MachinePointerInfo::getFixedStack(FI),
2667 if (VA.isRegLoc()) {
2668 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2669 if (isVarArg && IsWin64) {
2670 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2671 // shadow reg if callee is a varargs function.
2672 unsigned ShadowReg = 0;
2673 switch (VA.getLocReg()) {
2674 case X86::XMM0: ShadowReg = X86::RCX; break;
2675 case X86::XMM1: ShadowReg = X86::RDX; break;
2676 case X86::XMM2: ShadowReg = X86::R8; break;
2677 case X86::XMM3: ShadowReg = X86::R9; break;
2680 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2682 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2683 assert(VA.isMemLoc());
2684 if (StackPtr.getNode() == 0)
2685 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2687 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2688 dl, DAG, VA, Flags));
2692 if (!MemOpChains.empty())
2693 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2694 &MemOpChains[0], MemOpChains.size());
2696 if (Subtarget->isPICStyleGOT()) {
2697 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2700 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2701 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2703 // If we are tail calling and generating PIC/GOT style code load the
2704 // address of the callee into ECX. The value in ecx is used as target of
2705 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2706 // for tail calls on PIC/GOT architectures. Normally we would just put the
2707 // address of GOT into ebx and then call target@PLT. But for tail calls
2708 // ebx would be restored (since ebx is callee saved) before jumping to the
2711 // Note: The actual moving to ECX is done further down.
2712 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2713 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2714 !G->getGlobal()->hasProtectedVisibility())
2715 Callee = LowerGlobalAddress(Callee, DAG);
2716 else if (isa<ExternalSymbolSDNode>(Callee))
2717 Callee = LowerExternalSymbol(Callee, DAG);
2721 if (Is64Bit && isVarArg && !IsWin64) {
2722 // From AMD64 ABI document:
2723 // For calls that may call functions that use varargs or stdargs
2724 // (prototype-less calls or calls to functions containing ellipsis (...) in
2725 // the declaration) %al is used as hidden argument to specify the number
2726 // of SSE registers used. The contents of %al do not need to match exactly
2727 // the number of registers, but must be an ubound on the number of SSE
2728 // registers used and is in the range 0 - 8 inclusive.
2730 // Count the number of XMM registers allocated.
2731 static const MCPhysReg XMMArgRegs[] = {
2732 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2733 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2735 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2736 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2737 && "SSE registers cannot be used when SSE is disabled");
2739 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2740 DAG.getConstant(NumXMMRegs, MVT::i8)));
2743 // For tail calls lower the arguments to the 'real' stack slot.
2745 // Force all the incoming stack arguments to be loaded from the stack
2746 // before any new outgoing arguments are stored to the stack, because the
2747 // outgoing stack slots may alias the incoming argument stack slots, and
2748 // the alias isn't otherwise explicit. This is slightly more conservative
2749 // than necessary, because it means that each store effectively depends
2750 // on every argument instead of just those arguments it would clobber.
2751 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2753 SmallVector<SDValue, 8> MemOpChains2;
2756 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2757 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2758 CCValAssign &VA = ArgLocs[i];
2761 assert(VA.isMemLoc());
2762 SDValue Arg = OutVals[i];
2763 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2764 // Create frame index.
2765 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2766 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2767 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2768 FIN = DAG.getFrameIndex(FI, getPointerTy());
2770 if (Flags.isByVal()) {
2771 // Copy relative to framepointer.
2772 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2773 if (StackPtr.getNode() == 0)
2774 StackPtr = DAG.getCopyFromReg(Chain, dl,
2775 RegInfo->getStackRegister(),
2777 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2779 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2783 // Store relative to framepointer.
2784 MemOpChains2.push_back(
2785 DAG.getStore(ArgChain, dl, Arg, FIN,
2786 MachinePointerInfo::getFixedStack(FI),
2792 if (!MemOpChains2.empty())
2793 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2794 &MemOpChains2[0], MemOpChains2.size());
2796 // Store the return address to the appropriate stack slot.
2797 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2798 getPointerTy(), RegInfo->getSlotSize(),
2802 // Build a sequence of copy-to-reg nodes chained together with token chain
2803 // and flag operands which copy the outgoing args into registers.
2805 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2806 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2807 RegsToPass[i].second, InFlag);
2808 InFlag = Chain.getValue(1);
2811 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2812 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2813 // In the 64-bit large code model, we have to make all calls
2814 // through a register, since the call instruction's 32-bit
2815 // pc-relative offset may not be large enough to hold the whole
2817 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2818 // If the callee is a GlobalAddress node (quite common, every direct call
2819 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2822 // We should use extra load for direct calls to dllimported functions in
2824 const GlobalValue *GV = G->getGlobal();
2825 if (!GV->hasDLLImportStorageClass()) {
2826 unsigned char OpFlags = 0;
2827 bool ExtraLoad = false;
2828 unsigned WrapperKind = ISD::DELETED_NODE;
2830 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2831 // external symbols most go through the PLT in PIC mode. If the symbol
2832 // has hidden or protected visibility, or if it is static or local, then
2833 // we don't need to use the PLT - we can directly call it.
2834 if (Subtarget->isTargetELF() &&
2835 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2836 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2837 OpFlags = X86II::MO_PLT;
2838 } else if (Subtarget->isPICStyleStubAny() &&
2839 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2840 (!Subtarget->getTargetTriple().isMacOSX() ||
2841 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2842 // PC-relative references to external symbols should go through $stub,
2843 // unless we're building with the leopard linker or later, which
2844 // automatically synthesizes these stubs.
2845 OpFlags = X86II::MO_DARWIN_STUB;
2846 } else if (Subtarget->isPICStyleRIPRel() &&
2847 isa<Function>(GV) &&
2848 cast<Function>(GV)->getAttributes().
2849 hasAttribute(AttributeSet::FunctionIndex,
2850 Attribute::NonLazyBind)) {
2851 // If the function is marked as non-lazy, generate an indirect call
2852 // which loads from the GOT directly. This avoids runtime overhead
2853 // at the cost of eager binding (and one extra byte of encoding).
2854 OpFlags = X86II::MO_GOTPCREL;
2855 WrapperKind = X86ISD::WrapperRIP;
2859 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2860 G->getOffset(), OpFlags);
2862 // Add a wrapper if needed.
2863 if (WrapperKind != ISD::DELETED_NODE)
2864 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2865 // Add extra indirection if needed.
2867 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2868 MachinePointerInfo::getGOT(),
2869 false, false, false, 0);
2871 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2872 unsigned char OpFlags = 0;
2874 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2875 // external symbols should go through the PLT.
2876 if (Subtarget->isTargetELF() &&
2877 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2878 OpFlags = X86II::MO_PLT;
2879 } else if (Subtarget->isPICStyleStubAny() &&
2880 (!Subtarget->getTargetTriple().isMacOSX() ||
2881 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2882 // PC-relative references to external symbols should go through $stub,
2883 // unless we're building with the leopard linker or later, which
2884 // automatically synthesizes these stubs.
2885 OpFlags = X86II::MO_DARWIN_STUB;
2888 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2892 // Returns a chain & a flag for retval copy to use.
2893 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2894 SmallVector<SDValue, 8> Ops;
2896 if (!IsSibcall && isTailCall) {
2897 Chain = DAG.getCALLSEQ_END(Chain,
2898 DAG.getIntPtrConstant(NumBytesToPop, true),
2899 DAG.getIntPtrConstant(0, true), InFlag, dl);
2900 InFlag = Chain.getValue(1);
2903 Ops.push_back(Chain);
2904 Ops.push_back(Callee);
2907 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2909 // Add argument registers to the end of the list so that they are known live
2911 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2912 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2913 RegsToPass[i].second.getValueType()));
2915 // Add a register mask operand representing the call-preserved registers.
2916 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2917 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2918 assert(Mask && "Missing call preserved mask for calling convention");
2919 Ops.push_back(DAG.getRegisterMask(Mask));
2921 if (InFlag.getNode())
2922 Ops.push_back(InFlag);
2926 //// If this is the first return lowered for this function, add the regs
2927 //// to the liveout set for the function.
2928 // This isn't right, although it's probably harmless on x86; liveouts
2929 // should be computed from returns not tail calls. Consider a void
2930 // function making a tail call to a function returning int.
2931 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2934 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2935 InFlag = Chain.getValue(1);
2937 // Create the CALLSEQ_END node.
2938 unsigned NumBytesForCalleeToPop;
2939 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2940 getTargetMachine().Options.GuaranteedTailCallOpt))
2941 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2942 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2943 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2944 SR == StackStructReturn)
2945 // If this is a call to a struct-return function, the callee
2946 // pops the hidden struct pointer, so we have to push it back.
2947 // This is common for Darwin/X86, Linux & Mingw32 targets.
2948 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2949 NumBytesForCalleeToPop = 4;
2951 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2953 // Returns a flag for retval copy to use.
2955 Chain = DAG.getCALLSEQ_END(Chain,
2956 DAG.getIntPtrConstant(NumBytesToPop, true),
2957 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2960 InFlag = Chain.getValue(1);
2963 // Handle result values, copying them out of physregs into vregs that we
2965 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2966 Ins, dl, DAG, InVals);
2969 //===----------------------------------------------------------------------===//
2970 // Fast Calling Convention (tail call) implementation
2971 //===----------------------------------------------------------------------===//
2973 // Like std call, callee cleans arguments, convention except that ECX is
2974 // reserved for storing the tail called function address. Only 2 registers are
2975 // free for argument passing (inreg). Tail call optimization is performed
2977 // * tailcallopt is enabled
2978 // * caller/callee are fastcc
2979 // On X86_64 architecture with GOT-style position independent code only local
2980 // (within module) calls are supported at the moment.
2981 // To keep the stack aligned according to platform abi the function
2982 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2983 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2984 // If a tail called function callee has more arguments than the caller the
2985 // caller needs to make sure that there is room to move the RETADDR to. This is
2986 // achieved by reserving an area the size of the argument delta right after the
2987 // original REtADDR, but before the saved framepointer or the spilled registers
2988 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3000 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3001 /// for a 16 byte align requirement.
3003 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3004 SelectionDAG& DAG) const {
3005 MachineFunction &MF = DAG.getMachineFunction();
3006 const TargetMachine &TM = MF.getTarget();
3007 const X86RegisterInfo *RegInfo =
3008 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3009 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3010 unsigned StackAlignment = TFI.getStackAlignment();
3011 uint64_t AlignMask = StackAlignment - 1;
3012 int64_t Offset = StackSize;
3013 unsigned SlotSize = RegInfo->getSlotSize();
3014 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3015 // Number smaller than 12 so just add the difference.
3016 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3018 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3019 Offset = ((~AlignMask) & Offset) + StackAlignment +
3020 (StackAlignment-SlotSize);
3025 /// MatchingStackOffset - Return true if the given stack call argument is
3026 /// already available in the same position (relatively) of the caller's
3027 /// incoming argument stack.
3029 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3030 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3031 const X86InstrInfo *TII) {
3032 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3034 if (Arg.getOpcode() == ISD::CopyFromReg) {
3035 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3036 if (!TargetRegisterInfo::isVirtualRegister(VR))
3038 MachineInstr *Def = MRI->getVRegDef(VR);
3041 if (!Flags.isByVal()) {
3042 if (!TII->isLoadFromStackSlot(Def, FI))
3045 unsigned Opcode = Def->getOpcode();
3046 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3047 Def->getOperand(1).isFI()) {
3048 FI = Def->getOperand(1).getIndex();
3049 Bytes = Flags.getByValSize();
3053 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3054 if (Flags.isByVal())
3055 // ByVal argument is passed in as a pointer but it's now being
3056 // dereferenced. e.g.
3057 // define @foo(%struct.X* %A) {
3058 // tail call @bar(%struct.X* byval %A)
3061 SDValue Ptr = Ld->getBasePtr();
3062 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3065 FI = FINode->getIndex();
3066 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3067 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3068 FI = FINode->getIndex();
3069 Bytes = Flags.getByValSize();
3073 assert(FI != INT_MAX);
3074 if (!MFI->isFixedObjectIndex(FI))
3076 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3079 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3080 /// for tail call optimization. Targets which want to do tail call
3081 /// optimization should implement this function.
3083 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3084 CallingConv::ID CalleeCC,
3086 bool isCalleeStructRet,
3087 bool isCallerStructRet,
3089 const SmallVectorImpl<ISD::OutputArg> &Outs,
3090 const SmallVectorImpl<SDValue> &OutVals,
3091 const SmallVectorImpl<ISD::InputArg> &Ins,
3092 SelectionDAG &DAG) const {
3093 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3096 // If -tailcallopt is specified, make fastcc functions tail-callable.
3097 const MachineFunction &MF = DAG.getMachineFunction();
3098 const Function *CallerF = MF.getFunction();
3100 // If the function return type is x86_fp80 and the callee return type is not,
3101 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3102 // perform a tailcall optimization here.
3103 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3106 CallingConv::ID CallerCC = CallerF->getCallingConv();
3107 bool CCMatch = CallerCC == CalleeCC;
3108 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3109 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3111 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3112 if (IsTailCallConvention(CalleeCC) && CCMatch)
3117 // Look for obvious safe cases to perform tail call optimization that do not
3118 // require ABI changes. This is what gcc calls sibcall.
3120 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3121 // emit a special epilogue.
3122 const X86RegisterInfo *RegInfo =
3123 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3124 if (RegInfo->needsStackRealignment(MF))
3127 // Also avoid sibcall optimization if either caller or callee uses struct
3128 // return semantics.
3129 if (isCalleeStructRet || isCallerStructRet)
3132 // An stdcall/thiscall caller is expected to clean up its arguments; the
3133 // callee isn't going to do that.
3134 // FIXME: this is more restrictive than needed. We could produce a tailcall
3135 // when the stack adjustment matches. For example, with a thiscall that takes
3136 // only one argument.
3137 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3138 CallerCC == CallingConv::X86_ThisCall))
3141 // Do not sibcall optimize vararg calls unless all arguments are passed via
3143 if (isVarArg && !Outs.empty()) {
3145 // Optimizing for varargs on Win64 is unlikely to be safe without
3146 // additional testing.
3147 if (IsCalleeWin64 || IsCallerWin64)
3150 SmallVector<CCValAssign, 16> ArgLocs;
3151 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3152 getTargetMachine(), ArgLocs, *DAG.getContext());
3154 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3155 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3156 if (!ArgLocs[i].isRegLoc())
3160 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3161 // stack. Therefore, if it's not used by the call it is not safe to optimize
3162 // this into a sibcall.
3163 bool Unused = false;
3164 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3171 SmallVector<CCValAssign, 16> RVLocs;
3172 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3173 getTargetMachine(), RVLocs, *DAG.getContext());
3174 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3175 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3176 CCValAssign &VA = RVLocs[i];
3177 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3182 // If the calling conventions do not match, then we'd better make sure the
3183 // results are returned in the same way as what the caller expects.
3185 SmallVector<CCValAssign, 16> RVLocs1;
3186 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3187 getTargetMachine(), RVLocs1, *DAG.getContext());
3188 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3190 SmallVector<CCValAssign, 16> RVLocs2;
3191 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3192 getTargetMachine(), RVLocs2, *DAG.getContext());
3193 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3195 if (RVLocs1.size() != RVLocs2.size())
3197 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3198 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3200 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3202 if (RVLocs1[i].isRegLoc()) {
3203 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3206 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3212 // If the callee takes no arguments then go on to check the results of the
3214 if (!Outs.empty()) {
3215 // Check if stack adjustment is needed. For now, do not do this if any
3216 // argument is passed on the stack.
3217 SmallVector<CCValAssign, 16> ArgLocs;
3218 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3219 getTargetMachine(), ArgLocs, *DAG.getContext());
3221 // Allocate shadow area for Win64
3223 CCInfo.AllocateStack(32, 8);
3225 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3226 if (CCInfo.getNextStackOffset()) {
3227 MachineFunction &MF = DAG.getMachineFunction();
3228 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3231 // Check if the arguments are already laid out in the right way as
3232 // the caller's fixed stack objects.
3233 MachineFrameInfo *MFI = MF.getFrameInfo();
3234 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3235 const X86InstrInfo *TII =
3236 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3237 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3238 CCValAssign &VA = ArgLocs[i];
3239 SDValue Arg = OutVals[i];
3240 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3241 if (VA.getLocInfo() == CCValAssign::Indirect)
3243 if (!VA.isRegLoc()) {
3244 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3251 // If the tailcall address may be in a register, then make sure it's
3252 // possible to register allocate for it. In 32-bit, the call address can
3253 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3254 // callee-saved registers are restored. These happen to be the same
3255 // registers used to pass 'inreg' arguments so watch out for those.
3256 if (!Subtarget->is64Bit() &&
3257 ((!isa<GlobalAddressSDNode>(Callee) &&
3258 !isa<ExternalSymbolSDNode>(Callee)) ||
3259 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3260 unsigned NumInRegs = 0;
3261 // In PIC we need an extra register to formulate the address computation
3263 unsigned MaxInRegs =
3264 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3266 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3267 CCValAssign &VA = ArgLocs[i];
3270 unsigned Reg = VA.getLocReg();
3273 case X86::EAX: case X86::EDX: case X86::ECX:
3274 if (++NumInRegs == MaxInRegs)
3286 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3287 const TargetLibraryInfo *libInfo) const {
3288 return X86::createFastISel(funcInfo, libInfo);
3291 //===----------------------------------------------------------------------===//
3292 // Other Lowering Hooks
3293 //===----------------------------------------------------------------------===//
3295 static bool MayFoldLoad(SDValue Op) {
3296 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3299 static bool MayFoldIntoStore(SDValue Op) {
3300 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3303 static bool isTargetShuffle(unsigned Opcode) {
3305 default: return false;
3306 case X86ISD::PSHUFD:
3307 case X86ISD::PSHUFHW:
3308 case X86ISD::PSHUFLW:
3310 case X86ISD::PALIGNR:
3311 case X86ISD::MOVLHPS:
3312 case X86ISD::MOVLHPD:
3313 case X86ISD::MOVHLPS:
3314 case X86ISD::MOVLPS:
3315 case X86ISD::MOVLPD:
3316 case X86ISD::MOVSHDUP:
3317 case X86ISD::MOVSLDUP:
3318 case X86ISD::MOVDDUP:
3321 case X86ISD::UNPCKL:
3322 case X86ISD::UNPCKH:
3323 case X86ISD::VPERMILP:
3324 case X86ISD::VPERM2X128:
3325 case X86ISD::VPERMI:
3330 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3331 SDValue V1, SelectionDAG &DAG) {
3333 default: llvm_unreachable("Unknown x86 shuffle node");
3334 case X86ISD::MOVSHDUP:
3335 case X86ISD::MOVSLDUP:
3336 case X86ISD::MOVDDUP:
3337 return DAG.getNode(Opc, dl, VT, V1);
3341 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3342 SDValue V1, unsigned TargetMask,
3343 SelectionDAG &DAG) {
3345 default: llvm_unreachable("Unknown x86 shuffle node");
3346 case X86ISD::PSHUFD:
3347 case X86ISD::PSHUFHW:
3348 case X86ISD::PSHUFLW:
3349 case X86ISD::VPERMILP:
3350 case X86ISD::VPERMI:
3351 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3355 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3356 SDValue V1, SDValue V2, unsigned TargetMask,
3357 SelectionDAG &DAG) {
3359 default: llvm_unreachable("Unknown x86 shuffle node");
3360 case X86ISD::PALIGNR:
3362 case X86ISD::VPERM2X128:
3363 return DAG.getNode(Opc, dl, VT, V1, V2,
3364 DAG.getConstant(TargetMask, MVT::i8));
3368 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3369 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3371 default: llvm_unreachable("Unknown x86 shuffle node");
3372 case X86ISD::MOVLHPS:
3373 case X86ISD::MOVLHPD:
3374 case X86ISD::MOVHLPS:
3375 case X86ISD::MOVLPS:
3376 case X86ISD::MOVLPD:
3379 case X86ISD::UNPCKL:
3380 case X86ISD::UNPCKH:
3381 return DAG.getNode(Opc, dl, VT, V1, V2);
3385 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3386 MachineFunction &MF = DAG.getMachineFunction();
3387 const X86RegisterInfo *RegInfo =
3388 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3389 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3390 int ReturnAddrIndex = FuncInfo->getRAIndex();
3392 if (ReturnAddrIndex == 0) {
3393 // Set up a frame object for the return address.
3394 unsigned SlotSize = RegInfo->getSlotSize();
3395 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3398 FuncInfo->setRAIndex(ReturnAddrIndex);
3401 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3404 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3405 bool hasSymbolicDisplacement) {
3406 // Offset should fit into 32 bit immediate field.
3407 if (!isInt<32>(Offset))
3410 // If we don't have a symbolic displacement - we don't have any extra
3412 if (!hasSymbolicDisplacement)
3415 // FIXME: Some tweaks might be needed for medium code model.
3416 if (M != CodeModel::Small && M != CodeModel::Kernel)
3419 // For small code model we assume that latest object is 16MB before end of 31
3420 // bits boundary. We may also accept pretty large negative constants knowing
3421 // that all objects are in the positive half of address space.
3422 if (M == CodeModel::Small && Offset < 16*1024*1024)
3425 // For kernel code model we know that all object resist in the negative half
3426 // of 32bits address space. We may not accept negative offsets, since they may
3427 // be just off and we may accept pretty large positive ones.
3428 if (M == CodeModel::Kernel && Offset > 0)
3434 /// isCalleePop - Determines whether the callee is required to pop its
3435 /// own arguments. Callee pop is necessary to support tail calls.
3436 bool X86::isCalleePop(CallingConv::ID CallingConv,
3437 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3441 switch (CallingConv) {
3444 case CallingConv::X86_StdCall:
3446 case CallingConv::X86_FastCall:
3448 case CallingConv::X86_ThisCall:
3450 case CallingConv::Fast:
3452 case CallingConv::GHC:
3454 case CallingConv::HiPE:
3459 /// \brief Return true if the condition is an unsigned comparison operation.
3460 static bool isX86CCUnsigned(unsigned X86CC) {
3462 default: llvm_unreachable("Invalid integer condition!");
3463 case X86::COND_E: return true;
3464 case X86::COND_G: return false;
3465 case X86::COND_GE: return false;
3466 case X86::COND_L: return false;
3467 case X86::COND_LE: return false;
3468 case X86::COND_NE: return true;
3469 case X86::COND_B: return true;
3470 case X86::COND_A: return true;
3471 case X86::COND_BE: return true;
3472 case X86::COND_AE: return true;
3474 llvm_unreachable("covered switch fell through?!");
3477 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3478 /// specific condition code, returning the condition code and the LHS/RHS of the
3479 /// comparison to make.
3480 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3481 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3483 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3484 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3485 // X > -1 -> X == 0, jump !sign.
3486 RHS = DAG.getConstant(0, RHS.getValueType());
3487 return X86::COND_NS;
3489 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3490 // X < 0 -> X == 0, jump on sign.
3493 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3495 RHS = DAG.getConstant(0, RHS.getValueType());
3496 return X86::COND_LE;
3500 switch (SetCCOpcode) {
3501 default: llvm_unreachable("Invalid integer condition!");
3502 case ISD::SETEQ: return X86::COND_E;
3503 case ISD::SETGT: return X86::COND_G;
3504 case ISD::SETGE: return X86::COND_GE;
3505 case ISD::SETLT: return X86::COND_L;
3506 case ISD::SETLE: return X86::COND_LE;
3507 case ISD::SETNE: return X86::COND_NE;
3508 case ISD::SETULT: return X86::COND_B;
3509 case ISD::SETUGT: return X86::COND_A;
3510 case ISD::SETULE: return X86::COND_BE;
3511 case ISD::SETUGE: return X86::COND_AE;
3515 // First determine if it is required or is profitable to flip the operands.
3517 // If LHS is a foldable load, but RHS is not, flip the condition.
3518 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3519 !ISD::isNON_EXTLoad(RHS.getNode())) {
3520 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3521 std::swap(LHS, RHS);
3524 switch (SetCCOpcode) {
3530 std::swap(LHS, RHS);
3534 // On a floating point condition, the flags are set as follows:
3536 // 0 | 0 | 0 | X > Y
3537 // 0 | 0 | 1 | X < Y
3538 // 1 | 0 | 0 | X == Y
3539 // 1 | 1 | 1 | unordered
3540 switch (SetCCOpcode) {
3541 default: llvm_unreachable("Condcode should be pre-legalized away");
3543 case ISD::SETEQ: return X86::COND_E;
3544 case ISD::SETOLT: // flipped
3546 case ISD::SETGT: return X86::COND_A;
3547 case ISD::SETOLE: // flipped
3549 case ISD::SETGE: return X86::COND_AE;
3550 case ISD::SETUGT: // flipped
3552 case ISD::SETLT: return X86::COND_B;
3553 case ISD::SETUGE: // flipped
3555 case ISD::SETLE: return X86::COND_BE;
3557 case ISD::SETNE: return X86::COND_NE;
3558 case ISD::SETUO: return X86::COND_P;
3559 case ISD::SETO: return X86::COND_NP;
3561 case ISD::SETUNE: return X86::COND_INVALID;
3565 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3566 /// code. Current x86 isa includes the following FP cmov instructions:
3567 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3568 static bool hasFPCMov(unsigned X86CC) {
3584 /// isFPImmLegal - Returns true if the target can instruction select the
3585 /// specified FP immediate natively. If false, the legalizer will
3586 /// materialize the FP immediate as a load from a constant pool.
3587 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3588 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3589 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3595 /// \brief Returns true if it is beneficial to convert a load of a constant
3596 /// to just the constant itself.
3597 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3599 assert(Ty->isIntegerTy());
3601 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3602 if (BitSize == 0 || BitSize > 64)
3607 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3608 /// the specified range (L, H].
3609 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3610 return (Val < 0) || (Val >= Low && Val < Hi);
3613 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3614 /// specified value.
3615 static bool isUndefOrEqual(int Val, int CmpVal) {
3616 return (Val < 0 || Val == CmpVal);
3619 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3620 /// from position Pos and ending in Pos+Size, falls within the specified
3621 /// sequential range (L, L+Pos]. or is undef.
3622 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3623 unsigned Pos, unsigned Size, int Low) {
3624 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3625 if (!isUndefOrEqual(Mask[i], Low))
3630 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3631 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3632 /// the second operand.
3633 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3634 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3635 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3636 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3637 return (Mask[0] < 2 && Mask[1] < 2);
3641 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3642 /// is suitable for input to PSHUFHW.
3643 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3644 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3647 // Lower quadword copied in order or undef.
3648 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3651 // Upper quadword shuffled.
3652 for (unsigned i = 4; i != 8; ++i)
3653 if (!isUndefOrInRange(Mask[i], 4, 8))
3656 if (VT == MVT::v16i16) {
3657 // Lower quadword copied in order or undef.
3658 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3661 // Upper quadword shuffled.
3662 for (unsigned i = 12; i != 16; ++i)
3663 if (!isUndefOrInRange(Mask[i], 12, 16))
3670 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3671 /// is suitable for input to PSHUFLW.
3672 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3673 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3676 // Upper quadword copied in order.
3677 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3680 // Lower quadword shuffled.
3681 for (unsigned i = 0; i != 4; ++i)
3682 if (!isUndefOrInRange(Mask[i], 0, 4))
3685 if (VT == MVT::v16i16) {
3686 // Upper quadword copied in order.
3687 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3690 // Lower quadword shuffled.
3691 for (unsigned i = 8; i != 12; ++i)
3692 if (!isUndefOrInRange(Mask[i], 8, 12))
3699 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3700 /// is suitable for input to PALIGNR.
3701 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3702 const X86Subtarget *Subtarget) {
3703 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3704 (VT.is256BitVector() && !Subtarget->hasInt256()))
3707 unsigned NumElts = VT.getVectorNumElements();
3708 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3709 unsigned NumLaneElts = NumElts/NumLanes;
3711 // Do not handle 64-bit element shuffles with palignr.
3712 if (NumLaneElts == 2)
3715 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3717 for (i = 0; i != NumLaneElts; ++i) {
3722 // Lane is all undef, go to next lane
3723 if (i == NumLaneElts)
3726 int Start = Mask[i+l];
3728 // Make sure its in this lane in one of the sources
3729 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3730 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3733 // If not lane 0, then we must match lane 0
3734 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3737 // Correct second source to be contiguous with first source
3738 if (Start >= (int)NumElts)
3739 Start -= NumElts - NumLaneElts;
3741 // Make sure we're shifting in the right direction.
3742 if (Start <= (int)(i+l))
3747 // Check the rest of the elements to see if they are consecutive.
3748 for (++i; i != NumLaneElts; ++i) {
3749 int Idx = Mask[i+l];
3751 // Make sure its in this lane
3752 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3753 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3756 // If not lane 0, then we must match lane 0
3757 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3760 if (Idx >= (int)NumElts)
3761 Idx -= NumElts - NumLaneElts;
3763 if (!isUndefOrEqual(Idx, Start+i))
3772 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3773 /// the two vector operands have swapped position.
3774 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3775 unsigned NumElems) {
3776 for (unsigned i = 0; i != NumElems; ++i) {
3780 else if (idx < (int)NumElems)
3781 Mask[i] = idx + NumElems;
3783 Mask[i] = idx - NumElems;
3787 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3788 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3789 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3790 /// reverse of what x86 shuffles want.
3791 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3793 unsigned NumElems = VT.getVectorNumElements();
3794 unsigned NumLanes = VT.getSizeInBits()/128;
3795 unsigned NumLaneElems = NumElems/NumLanes;
3797 if (NumLaneElems != 2 && NumLaneElems != 4)
3800 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3801 bool symetricMaskRequired =
3802 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3804 // VSHUFPSY divides the resulting vector into 4 chunks.
3805 // The sources are also splitted into 4 chunks, and each destination
3806 // chunk must come from a different source chunk.
3808 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3809 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3811 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3812 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3814 // VSHUFPDY divides the resulting vector into 4 chunks.
3815 // The sources are also splitted into 4 chunks, and each destination
3816 // chunk must come from a different source chunk.
3818 // SRC1 => X3 X2 X1 X0
3819 // SRC2 => Y3 Y2 Y1 Y0
3821 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3823 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3824 unsigned HalfLaneElems = NumLaneElems/2;
3825 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3826 for (unsigned i = 0; i != NumLaneElems; ++i) {
3827 int Idx = Mask[i+l];
3828 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3829 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3831 // For VSHUFPSY, the mask of the second half must be the same as the
3832 // first but with the appropriate offsets. This works in the same way as
3833 // VPERMILPS works with masks.
3834 if (!symetricMaskRequired || Idx < 0)
3836 if (MaskVal[i] < 0) {
3837 MaskVal[i] = Idx - l;
3840 if ((signed)(Idx - l) != MaskVal[i])
3848 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3849 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3850 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3851 if (!VT.is128BitVector())
3854 unsigned NumElems = VT.getVectorNumElements();
3859 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3860 return isUndefOrEqual(Mask[0], 6) &&
3861 isUndefOrEqual(Mask[1], 7) &&
3862 isUndefOrEqual(Mask[2], 2) &&
3863 isUndefOrEqual(Mask[3], 3);
3866 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3867 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3869 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3870 if (!VT.is128BitVector())
3873 unsigned NumElems = VT.getVectorNumElements();
3878 return isUndefOrEqual(Mask[0], 2) &&
3879 isUndefOrEqual(Mask[1], 3) &&
3880 isUndefOrEqual(Mask[2], 2) &&
3881 isUndefOrEqual(Mask[3], 3);
3884 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3885 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3886 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3887 if (!VT.is128BitVector())
3890 unsigned NumElems = VT.getVectorNumElements();
3892 if (NumElems != 2 && NumElems != 4)
3895 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3896 if (!isUndefOrEqual(Mask[i], i + NumElems))
3899 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3900 if (!isUndefOrEqual(Mask[i], i))
3906 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3907 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3908 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3909 if (!VT.is128BitVector())
3912 unsigned NumElems = VT.getVectorNumElements();
3914 if (NumElems != 2 && NumElems != 4)
3917 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3918 if (!isUndefOrEqual(Mask[i], i))
3921 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3922 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3929 // Some special combinations that can be optimized.
3932 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3933 SelectionDAG &DAG) {
3934 MVT VT = SVOp->getSimpleValueType(0);
3937 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3940 ArrayRef<int> Mask = SVOp->getMask();
3942 // These are the special masks that may be optimized.
3943 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3944 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3945 bool MatchEvenMask = true;
3946 bool MatchOddMask = true;
3947 for (int i=0; i<8; ++i) {
3948 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3949 MatchEvenMask = false;
3950 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3951 MatchOddMask = false;
3954 if (!MatchEvenMask && !MatchOddMask)
3957 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3959 SDValue Op0 = SVOp->getOperand(0);
3960 SDValue Op1 = SVOp->getOperand(1);
3962 if (MatchEvenMask) {
3963 // Shift the second operand right to 32 bits.
3964 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3965 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3967 // Shift the first operand left to 32 bits.
3968 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3969 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3971 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3972 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3975 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3976 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3977 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3978 bool HasInt256, bool V2IsSplat = false) {
3980 assert(VT.getSizeInBits() >= 128 &&
3981 "Unsupported vector type for unpckl");
3983 // AVX defines UNPCK* to operate independently on 128-bit lanes.
3985 unsigned NumOf256BitLanes;
3986 unsigned NumElts = VT.getVectorNumElements();
3987 if (VT.is256BitVector()) {
3988 if (NumElts != 4 && NumElts != 8 &&
3989 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3992 NumOf256BitLanes = 1;
3993 } else if (VT.is512BitVector()) {
3994 assert(VT.getScalarType().getSizeInBits() >= 32 &&
3995 "Unsupported vector type for unpckh");
3997 NumOf256BitLanes = 2;
4000 NumOf256BitLanes = 1;
4003 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4004 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4006 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4007 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4008 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4009 int BitI = Mask[l256*NumEltsInStride+l+i];
4010 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4011 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4013 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4015 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4023 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4024 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4025 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4026 bool HasInt256, bool V2IsSplat = false) {
4027 assert(VT.getSizeInBits() >= 128 &&
4028 "Unsupported vector type for unpckh");
4030 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4032 unsigned NumOf256BitLanes;
4033 unsigned NumElts = VT.getVectorNumElements();
4034 if (VT.is256BitVector()) {
4035 if (NumElts != 4 && NumElts != 8 &&
4036 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4039 NumOf256BitLanes = 1;
4040 } else if (VT.is512BitVector()) {
4041 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4042 "Unsupported vector type for unpckh");
4044 NumOf256BitLanes = 2;
4047 NumOf256BitLanes = 1;
4050 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4051 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4053 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4054 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4055 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4056 int BitI = Mask[l256*NumEltsInStride+l+i];
4057 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4058 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4060 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4062 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4070 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4071 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4073 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4074 unsigned NumElts = VT.getVectorNumElements();
4075 bool Is256BitVec = VT.is256BitVector();
4077 if (VT.is512BitVector())
4079 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4080 "Unsupported vector type for unpckh");
4082 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4083 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4086 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4087 // FIXME: Need a better way to get rid of this, there's no latency difference
4088 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4089 // the former later. We should also remove the "_undef" special mask.
4090 if (NumElts == 4 && Is256BitVec)
4093 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4094 // independently on 128-bit lanes.
4095 unsigned NumLanes = VT.getSizeInBits()/128;
4096 unsigned NumLaneElts = NumElts/NumLanes;
4098 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4099 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4100 int BitI = Mask[l+i];
4101 int BitI1 = Mask[l+i+1];
4103 if (!isUndefOrEqual(BitI, j))
4105 if (!isUndefOrEqual(BitI1, j))
4113 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4114 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4116 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4117 unsigned NumElts = VT.getVectorNumElements();
4119 if (VT.is512BitVector())
4122 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4123 "Unsupported vector type for unpckh");
4125 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4126 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4129 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4130 // independently on 128-bit lanes.
4131 unsigned NumLanes = VT.getSizeInBits()/128;
4132 unsigned NumLaneElts = NumElts/NumLanes;
4134 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4135 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4136 int BitI = Mask[l+i];
4137 int BitI1 = Mask[l+i+1];
4138 if (!isUndefOrEqual(BitI, j))
4140 if (!isUndefOrEqual(BitI1, j))
4147 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4148 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4149 /// MOVSD, and MOVD, i.e. setting the lowest element.
4150 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4151 if (VT.getVectorElementType().getSizeInBits() < 32)
4153 if (!VT.is128BitVector())
4156 unsigned NumElts = VT.getVectorNumElements();
4158 if (!isUndefOrEqual(Mask[0], NumElts))
4161 for (unsigned i = 1; i != NumElts; ++i)
4162 if (!isUndefOrEqual(Mask[i], i))
4168 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4169 /// as permutations between 128-bit chunks or halves. As an example: this
4171 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4172 /// The first half comes from the second half of V1 and the second half from the
4173 /// the second half of V2.
4174 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4175 if (!HasFp256 || !VT.is256BitVector())
4178 // The shuffle result is divided into half A and half B. In total the two
4179 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4180 // B must come from C, D, E or F.
4181 unsigned HalfSize = VT.getVectorNumElements()/2;
4182 bool MatchA = false, MatchB = false;
4184 // Check if A comes from one of C, D, E, F.
4185 for (unsigned Half = 0; Half != 4; ++Half) {
4186 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4192 // Check if B comes from one of C, D, E, F.
4193 for (unsigned Half = 0; Half != 4; ++Half) {
4194 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4200 return MatchA && MatchB;
4203 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4204 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4205 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4206 MVT VT = SVOp->getSimpleValueType(0);
4208 unsigned HalfSize = VT.getVectorNumElements()/2;
4210 unsigned FstHalf = 0, SndHalf = 0;
4211 for (unsigned i = 0; i < HalfSize; ++i) {
4212 if (SVOp->getMaskElt(i) > 0) {
4213 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4217 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4218 if (SVOp->getMaskElt(i) > 0) {
4219 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4224 return (FstHalf | (SndHalf << 4));
4227 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4228 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4229 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4233 unsigned NumElts = VT.getVectorNumElements();
4235 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4236 for (unsigned i = 0; i != NumElts; ++i) {
4239 Imm8 |= Mask[i] << (i*2);
4244 unsigned LaneSize = 4;
4245 SmallVector<int, 4> MaskVal(LaneSize, -1);
4247 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4248 for (unsigned i = 0; i != LaneSize; ++i) {
4249 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4253 if (MaskVal[i] < 0) {
4254 MaskVal[i] = Mask[i+l] - l;
4255 Imm8 |= MaskVal[i] << (i*2);
4258 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4265 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4266 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4267 /// Note that VPERMIL mask matching is different depending whether theunderlying
4268 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4269 /// to the same elements of the low, but to the higher half of the source.
4270 /// In VPERMILPD the two lanes could be shuffled independently of each other
4271 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4272 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4273 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4274 if (VT.getSizeInBits() < 256 || EltSize < 32)
4276 bool symetricMaskRequired = (EltSize == 32);
4277 unsigned NumElts = VT.getVectorNumElements();
4279 unsigned NumLanes = VT.getSizeInBits()/128;
4280 unsigned LaneSize = NumElts/NumLanes;
4281 // 2 or 4 elements in one lane
4283 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4284 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4285 for (unsigned i = 0; i != LaneSize; ++i) {
4286 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4288 if (symetricMaskRequired) {
4289 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4290 ExpectedMaskVal[i] = Mask[i+l] - l;
4293 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4301 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4302 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4303 /// element of vector 2 and the other elements to come from vector 1 in order.
4304 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4305 bool V2IsSplat = false, bool V2IsUndef = false) {
4306 if (!VT.is128BitVector())
4309 unsigned NumOps = VT.getVectorNumElements();
4310 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4313 if (!isUndefOrEqual(Mask[0], 0))
4316 for (unsigned i = 1; i != NumOps; ++i)
4317 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4318 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4319 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4325 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4326 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4327 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4328 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4329 const X86Subtarget *Subtarget) {
4330 if (!Subtarget->hasSSE3())
4333 unsigned NumElems = VT.getVectorNumElements();
4335 if ((VT.is128BitVector() && NumElems != 4) ||
4336 (VT.is256BitVector() && NumElems != 8) ||
4337 (VT.is512BitVector() && NumElems != 16))
4340 // "i+1" is the value the indexed mask element must have
4341 for (unsigned i = 0; i != NumElems; i += 2)
4342 if (!isUndefOrEqual(Mask[i], i+1) ||
4343 !isUndefOrEqual(Mask[i+1], i+1))
4349 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4350 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4351 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4352 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4353 const X86Subtarget *Subtarget) {
4354 if (!Subtarget->hasSSE3())
4357 unsigned NumElems = VT.getVectorNumElements();
4359 if ((VT.is128BitVector() && NumElems != 4) ||
4360 (VT.is256BitVector() && NumElems != 8) ||
4361 (VT.is512BitVector() && NumElems != 16))
4364 // "i" is the value the indexed mask element must have
4365 for (unsigned i = 0; i != NumElems; i += 2)
4366 if (!isUndefOrEqual(Mask[i], i) ||
4367 !isUndefOrEqual(Mask[i+1], i))
4373 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4374 /// specifies a shuffle of elements that is suitable for input to 256-bit
4375 /// version of MOVDDUP.
4376 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4377 if (!HasFp256 || !VT.is256BitVector())
4380 unsigned NumElts = VT.getVectorNumElements();
4384 for (unsigned i = 0; i != NumElts/2; ++i)
4385 if (!isUndefOrEqual(Mask[i], 0))
4387 for (unsigned i = NumElts/2; i != NumElts; ++i)
4388 if (!isUndefOrEqual(Mask[i], NumElts/2))
4393 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4394 /// specifies a shuffle of elements that is suitable for input to 128-bit
4395 /// version of MOVDDUP.
4396 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4397 if (!VT.is128BitVector())
4400 unsigned e = VT.getVectorNumElements() / 2;
4401 for (unsigned i = 0; i != e; ++i)
4402 if (!isUndefOrEqual(Mask[i], i))
4404 for (unsigned i = 0; i != e; ++i)
4405 if (!isUndefOrEqual(Mask[e+i], i))
4410 /// isVEXTRACTIndex - Return true if the specified
4411 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4412 /// suitable for instruction that extract 128 or 256 bit vectors
4413 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4414 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4415 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4418 // The index should be aligned on a vecWidth-bit boundary.
4420 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4422 MVT VT = N->getSimpleValueType(0);
4423 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4424 bool Result = (Index * ElSize) % vecWidth == 0;
4429 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4430 /// operand specifies a subvector insert that is suitable for input to
4431 /// insertion of 128 or 256-bit subvectors
4432 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4433 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4434 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4436 // The index should be aligned on a vecWidth-bit boundary.
4438 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4440 MVT VT = N->getSimpleValueType(0);
4441 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4442 bool Result = (Index * ElSize) % vecWidth == 0;
4447 bool X86::isVINSERT128Index(SDNode *N) {
4448 return isVINSERTIndex(N, 128);
4451 bool X86::isVINSERT256Index(SDNode *N) {
4452 return isVINSERTIndex(N, 256);
4455 bool X86::isVEXTRACT128Index(SDNode *N) {
4456 return isVEXTRACTIndex(N, 128);
4459 bool X86::isVEXTRACT256Index(SDNode *N) {
4460 return isVEXTRACTIndex(N, 256);
4463 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4464 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4465 /// Handles 128-bit and 256-bit.
4466 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4467 MVT VT = N->getSimpleValueType(0);
4469 assert((VT.getSizeInBits() >= 128) &&
4470 "Unsupported vector type for PSHUF/SHUFP");
4472 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4473 // independently on 128-bit lanes.
4474 unsigned NumElts = VT.getVectorNumElements();
4475 unsigned NumLanes = VT.getSizeInBits()/128;
4476 unsigned NumLaneElts = NumElts/NumLanes;
4478 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4479 "Only supports 2, 4 or 8 elements per lane");
4481 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4483 for (unsigned i = 0; i != NumElts; ++i) {
4484 int Elt = N->getMaskElt(i);
4485 if (Elt < 0) continue;
4486 Elt &= NumLaneElts - 1;
4487 unsigned ShAmt = (i << Shift) % 8;
4488 Mask |= Elt << ShAmt;
4494 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4495 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4496 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4497 MVT VT = N->getSimpleValueType(0);
4499 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4500 "Unsupported vector type for PSHUFHW");
4502 unsigned NumElts = VT.getVectorNumElements();
4505 for (unsigned l = 0; l != NumElts; l += 8) {
4506 // 8 nodes per lane, but we only care about the last 4.
4507 for (unsigned i = 0; i < 4; ++i) {
4508 int Elt = N->getMaskElt(l+i+4);
4509 if (Elt < 0) continue;
4510 Elt &= 0x3; // only 2-bits.
4511 Mask |= Elt << (i * 2);
4518 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4519 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4520 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4521 MVT VT = N->getSimpleValueType(0);
4523 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4524 "Unsupported vector type for PSHUFHW");
4526 unsigned NumElts = VT.getVectorNumElements();
4529 for (unsigned l = 0; l != NumElts; l += 8) {
4530 // 8 nodes per lane, but we only care about the first 4.
4531 for (unsigned i = 0; i < 4; ++i) {
4532 int Elt = N->getMaskElt(l+i);
4533 if (Elt < 0) continue;
4534 Elt &= 0x3; // only 2-bits
4535 Mask |= Elt << (i * 2);
4542 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4543 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4544 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4545 MVT VT = SVOp->getSimpleValueType(0);
4546 unsigned EltSize = VT.is512BitVector() ? 1 :
4547 VT.getVectorElementType().getSizeInBits() >> 3;
4549 unsigned NumElts = VT.getVectorNumElements();
4550 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4551 unsigned NumLaneElts = NumElts/NumLanes;
4555 for (i = 0; i != NumElts; ++i) {
4556 Val = SVOp->getMaskElt(i);
4560 if (Val >= (int)NumElts)
4561 Val -= NumElts - NumLaneElts;
4563 assert(Val - i > 0 && "PALIGNR imm should be positive");
4564 return (Val - i) * EltSize;
4567 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4568 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4569 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4570 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4573 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4575 MVT VecVT = N->getOperand(0).getSimpleValueType();
4576 MVT ElVT = VecVT.getVectorElementType();
4578 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4579 return Index / NumElemsPerChunk;
4582 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4583 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4584 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4585 llvm_unreachable("Illegal insert subvector for VINSERT");
4588 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4590 MVT VecVT = N->getSimpleValueType(0);
4591 MVT ElVT = VecVT.getVectorElementType();
4593 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4594 return Index / NumElemsPerChunk;
4597 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4598 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4599 /// and VINSERTI128 instructions.
4600 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4601 return getExtractVEXTRACTImmediate(N, 128);
4604 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4605 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4606 /// and VINSERTI64x4 instructions.
4607 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4608 return getExtractVEXTRACTImmediate(N, 256);
4611 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4612 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4613 /// and VINSERTI128 instructions.
4614 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4615 return getInsertVINSERTImmediate(N, 128);
4618 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4619 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4620 /// and VINSERTI64x4 instructions.
4621 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4622 return getInsertVINSERTImmediate(N, 256);
4625 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4627 bool X86::isZeroNode(SDValue Elt) {
4628 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4629 return CN->isNullValue();
4630 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4631 return CFP->getValueAPF().isPosZero();
4635 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4636 /// their permute mask.
4637 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4638 SelectionDAG &DAG) {
4639 MVT VT = SVOp->getSimpleValueType(0);
4640 unsigned NumElems = VT.getVectorNumElements();
4641 SmallVector<int, 8> MaskVec;
4643 for (unsigned i = 0; i != NumElems; ++i) {
4644 int Idx = SVOp->getMaskElt(i);
4646 if (Idx < (int)NumElems)
4651 MaskVec.push_back(Idx);
4653 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4654 SVOp->getOperand(0), &MaskVec[0]);
4657 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4658 /// match movhlps. The lower half elements should come from upper half of
4659 /// V1 (and in order), and the upper half elements should come from the upper
4660 /// half of V2 (and in order).
4661 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4662 if (!VT.is128BitVector())
4664 if (VT.getVectorNumElements() != 4)
4666 for (unsigned i = 0, e = 2; i != e; ++i)
4667 if (!isUndefOrEqual(Mask[i], i+2))
4669 for (unsigned i = 2; i != 4; ++i)
4670 if (!isUndefOrEqual(Mask[i], i+4))
4675 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4676 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4678 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4679 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4681 N = N->getOperand(0).getNode();
4682 if (!ISD::isNON_EXTLoad(N))
4685 *LD = cast<LoadSDNode>(N);
4689 // Test whether the given value is a vector value which will be legalized
4691 static bool WillBeConstantPoolLoad(SDNode *N) {
4692 if (N->getOpcode() != ISD::BUILD_VECTOR)
4695 // Check for any non-constant elements.
4696 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4697 switch (N->getOperand(i).getNode()->getOpcode()) {
4699 case ISD::ConstantFP:
4706 // Vectors of all-zeros and all-ones are materialized with special
4707 // instructions rather than being loaded.
4708 return !ISD::isBuildVectorAllZeros(N) &&
4709 !ISD::isBuildVectorAllOnes(N);
4712 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4713 /// match movlp{s|d}. The lower half elements should come from lower half of
4714 /// V1 (and in order), and the upper half elements should come from the upper
4715 /// half of V2 (and in order). And since V1 will become the source of the
4716 /// MOVLP, it must be either a vector load or a scalar load to vector.
4717 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4718 ArrayRef<int> Mask, MVT VT) {
4719 if (!VT.is128BitVector())
4722 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4724 // Is V2 is a vector load, don't do this transformation. We will try to use
4725 // load folding shufps op.
4726 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4729 unsigned NumElems = VT.getVectorNumElements();
4731 if (NumElems != 2 && NumElems != 4)
4733 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4734 if (!isUndefOrEqual(Mask[i], i))
4736 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4737 if (!isUndefOrEqual(Mask[i], i+NumElems))
4742 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4744 static bool isSplatVector(SDNode *N) {
4745 if (N->getOpcode() != ISD::BUILD_VECTOR)
4748 SDValue SplatValue = N->getOperand(0);
4749 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4750 if (N->getOperand(i) != SplatValue)
4755 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4756 /// to an zero vector.
4757 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4758 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4759 SDValue V1 = N->getOperand(0);
4760 SDValue V2 = N->getOperand(1);
4761 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4762 for (unsigned i = 0; i != NumElems; ++i) {
4763 int Idx = N->getMaskElt(i);
4764 if (Idx >= (int)NumElems) {
4765 unsigned Opc = V2.getOpcode();
4766 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4768 if (Opc != ISD::BUILD_VECTOR ||
4769 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4771 } else if (Idx >= 0) {
4772 unsigned Opc = V1.getOpcode();
4773 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4775 if (Opc != ISD::BUILD_VECTOR ||
4776 !X86::isZeroNode(V1.getOperand(Idx)))
4783 /// getZeroVector - Returns a vector of specified type with all zero elements.
4785 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4786 SelectionDAG &DAG, SDLoc dl) {
4787 assert(VT.isVector() && "Expected a vector type");
4789 // Always build SSE zero vectors as <4 x i32> bitcasted
4790 // to their dest type. This ensures they get CSE'd.
4792 if (VT.is128BitVector()) { // SSE
4793 if (Subtarget->hasSSE2()) { // SSE2
4794 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4795 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4797 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4798 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4800 } else if (VT.is256BitVector()) { // AVX
4801 if (Subtarget->hasInt256()) { // AVX2
4802 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4803 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4804 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4805 array_lengthof(Ops));
4807 // 256-bit logic and arithmetic instructions in AVX are all
4808 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4809 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4810 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4811 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4812 array_lengthof(Ops));
4814 } else if (VT.is512BitVector()) { // AVX-512
4815 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4816 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4817 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4818 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4819 } else if (VT.getScalarType() == MVT::i1) {
4820 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4821 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4822 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4823 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4824 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
4825 Ops, VT.getVectorNumElements());
4827 llvm_unreachable("Unexpected vector type");
4829 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4832 /// getOnesVector - Returns a vector of specified type with all bits set.
4833 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4834 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4835 /// Then bitcast to their original type, ensuring they get CSE'd.
4836 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4838 assert(VT.isVector() && "Expected a vector type");
4840 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4842 if (VT.is256BitVector()) {
4843 if (HasInt256) { // AVX2
4844 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4845 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4846 array_lengthof(Ops));
4848 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4849 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4851 } else if (VT.is128BitVector()) {
4852 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4854 llvm_unreachable("Unexpected vector type");
4856 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4859 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4860 /// that point to V2 points to its first element.
4861 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4862 for (unsigned i = 0; i != NumElems; ++i) {
4863 if (Mask[i] > (int)NumElems) {
4869 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4870 /// operation of specified width.
4871 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4873 unsigned NumElems = VT.getVectorNumElements();
4874 SmallVector<int, 8> Mask;
4875 Mask.push_back(NumElems);
4876 for (unsigned i = 1; i != NumElems; ++i)
4878 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4881 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4882 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4884 unsigned NumElems = VT.getVectorNumElements();
4885 SmallVector<int, 8> Mask;
4886 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4888 Mask.push_back(i + NumElems);
4890 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4893 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4894 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4896 unsigned NumElems = VT.getVectorNumElements();
4897 SmallVector<int, 8> Mask;
4898 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4899 Mask.push_back(i + Half);
4900 Mask.push_back(i + NumElems + Half);
4902 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4905 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4906 // a generic shuffle instruction because the target has no such instructions.
4907 // Generate shuffles which repeat i16 and i8 several times until they can be
4908 // represented by v4f32 and then be manipulated by target suported shuffles.
4909 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4910 MVT VT = V.getSimpleValueType();
4911 int NumElems = VT.getVectorNumElements();
4914 while (NumElems > 4) {
4915 if (EltNo < NumElems/2) {
4916 V = getUnpackl(DAG, dl, VT, V, V);
4918 V = getUnpackh(DAG, dl, VT, V, V);
4919 EltNo -= NumElems/2;
4926 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4927 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4928 MVT VT = V.getSimpleValueType();
4931 if (VT.is128BitVector()) {
4932 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4933 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4934 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4936 } else if (VT.is256BitVector()) {
4937 // To use VPERMILPS to splat scalars, the second half of indicies must
4938 // refer to the higher part, which is a duplication of the lower one,
4939 // because VPERMILPS can only handle in-lane permutations.
4940 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4941 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4943 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4944 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4947 llvm_unreachable("Vector size not supported");
4949 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4952 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4953 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4954 MVT SrcVT = SV->getSimpleValueType(0);
4955 SDValue V1 = SV->getOperand(0);
4958 int EltNo = SV->getSplatIndex();
4959 int NumElems = SrcVT.getVectorNumElements();
4960 bool Is256BitVec = SrcVT.is256BitVector();
4962 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4963 "Unknown how to promote splat for type");
4965 // Extract the 128-bit part containing the splat element and update
4966 // the splat element index when it refers to the higher register.
4968 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4969 if (EltNo >= NumElems/2)
4970 EltNo -= NumElems/2;
4973 // All i16 and i8 vector types can't be used directly by a generic shuffle
4974 // instruction because the target has no such instruction. Generate shuffles
4975 // which repeat i16 and i8 several times until they fit in i32, and then can
4976 // be manipulated by target suported shuffles.
4977 MVT EltVT = SrcVT.getVectorElementType();
4978 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4979 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4981 // Recreate the 256-bit vector and place the same 128-bit vector
4982 // into the low and high part. This is necessary because we want
4983 // to use VPERM* to shuffle the vectors
4985 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4988 return getLegalSplat(DAG, V1, EltNo);
4991 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4992 /// vector of zero or undef vector. This produces a shuffle where the low
4993 /// element of V2 is swizzled into the zero/undef vector, landing at element
4994 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4995 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4997 const X86Subtarget *Subtarget,
4998 SelectionDAG &DAG) {
4999 MVT VT = V2.getSimpleValueType();
5001 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5002 unsigned NumElems = VT.getVectorNumElements();
5003 SmallVector<int, 16> MaskVec;
5004 for (unsigned i = 0; i != NumElems; ++i)
5005 // If this is the insertion idx, put the low elt of V2 here.
5006 MaskVec.push_back(i == Idx ? NumElems : i);
5007 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5010 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5011 /// target specific opcode. Returns true if the Mask could be calculated.
5012 /// Sets IsUnary to true if only uses one source.
5013 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5014 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5015 unsigned NumElems = VT.getVectorNumElements();
5019 switch(N->getOpcode()) {
5021 ImmN = N->getOperand(N->getNumOperands()-1);
5022 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5024 case X86ISD::UNPCKH:
5025 DecodeUNPCKHMask(VT, Mask);
5027 case X86ISD::UNPCKL:
5028 DecodeUNPCKLMask(VT, Mask);
5030 case X86ISD::MOVHLPS:
5031 DecodeMOVHLPSMask(NumElems, Mask);
5033 case X86ISD::MOVLHPS:
5034 DecodeMOVLHPSMask(NumElems, Mask);
5036 case X86ISD::PALIGNR:
5037 ImmN = N->getOperand(N->getNumOperands()-1);
5038 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5040 case X86ISD::PSHUFD:
5041 case X86ISD::VPERMILP:
5042 ImmN = N->getOperand(N->getNumOperands()-1);
5043 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5046 case X86ISD::PSHUFHW:
5047 ImmN = N->getOperand(N->getNumOperands()-1);
5048 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5051 case X86ISD::PSHUFLW:
5052 ImmN = N->getOperand(N->getNumOperands()-1);
5053 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5056 case X86ISD::VPERMI:
5057 ImmN = N->getOperand(N->getNumOperands()-1);
5058 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5062 case X86ISD::MOVSD: {
5063 // The index 0 always comes from the first element of the second source,
5064 // this is why MOVSS and MOVSD are used in the first place. The other
5065 // elements come from the other positions of the first source vector
5066 Mask.push_back(NumElems);
5067 for (unsigned i = 1; i != NumElems; ++i) {
5072 case X86ISD::VPERM2X128:
5073 ImmN = N->getOperand(N->getNumOperands()-1);
5074 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5075 if (Mask.empty()) return false;
5077 case X86ISD::MOVDDUP:
5078 case X86ISD::MOVLHPD:
5079 case X86ISD::MOVLPD:
5080 case X86ISD::MOVLPS:
5081 case X86ISD::MOVSHDUP:
5082 case X86ISD::MOVSLDUP:
5083 // Not yet implemented
5085 default: llvm_unreachable("unknown target shuffle node");
5091 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5092 /// element of the result of the vector shuffle.
5093 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5096 return SDValue(); // Limit search depth.
5098 SDValue V = SDValue(N, 0);
5099 EVT VT = V.getValueType();
5100 unsigned Opcode = V.getOpcode();
5102 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5103 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5104 int Elt = SV->getMaskElt(Index);
5107 return DAG.getUNDEF(VT.getVectorElementType());
5109 unsigned NumElems = VT.getVectorNumElements();
5110 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5111 : SV->getOperand(1);
5112 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5115 // Recurse into target specific vector shuffles to find scalars.
5116 if (isTargetShuffle(Opcode)) {
5117 MVT ShufVT = V.getSimpleValueType();
5118 unsigned NumElems = ShufVT.getVectorNumElements();
5119 SmallVector<int, 16> ShuffleMask;
5122 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5125 int Elt = ShuffleMask[Index];
5127 return DAG.getUNDEF(ShufVT.getVectorElementType());
5129 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5131 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5135 // Actual nodes that may contain scalar elements
5136 if (Opcode == ISD::BITCAST) {
5137 V = V.getOperand(0);
5138 EVT SrcVT = V.getValueType();
5139 unsigned NumElems = VT.getVectorNumElements();
5141 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5145 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5146 return (Index == 0) ? V.getOperand(0)
5147 : DAG.getUNDEF(VT.getVectorElementType());
5149 if (V.getOpcode() == ISD::BUILD_VECTOR)
5150 return V.getOperand(Index);
5155 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5156 /// shuffle operation which come from a consecutively from a zero. The
5157 /// search can start in two different directions, from left or right.
5158 /// We count undefs as zeros until PreferredNum is reached.
5159 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5160 unsigned NumElems, bool ZerosFromLeft,
5162 unsigned PreferredNum = -1U) {
5163 unsigned NumZeros = 0;
5164 for (unsigned i = 0; i != NumElems; ++i) {
5165 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5166 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5170 if (X86::isZeroNode(Elt))
5172 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5173 NumZeros = std::min(NumZeros + 1, PreferredNum);
5181 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5182 /// correspond consecutively to elements from one of the vector operands,
5183 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5185 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5186 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5187 unsigned NumElems, unsigned &OpNum) {
5188 bool SeenV1 = false;
5189 bool SeenV2 = false;
5191 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5192 int Idx = SVOp->getMaskElt(i);
5193 // Ignore undef indicies
5197 if (Idx < (int)NumElems)
5202 // Only accept consecutive elements from the same vector
5203 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5207 OpNum = SeenV1 ? 0 : 1;
5211 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5212 /// logical left shift of a vector.
5213 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5214 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5216 SVOp->getSimpleValueType(0).getVectorNumElements();
5217 unsigned NumZeros = getNumOfConsecutiveZeros(
5218 SVOp, NumElems, false /* check zeros from right */, DAG,
5219 SVOp->getMaskElt(0));
5225 // Considering the elements in the mask that are not consecutive zeros,
5226 // check if they consecutively come from only one of the source vectors.
5228 // V1 = {X, A, B, C} 0
5230 // vector_shuffle V1, V2 <1, 2, 3, X>
5232 if (!isShuffleMaskConsecutive(SVOp,
5233 0, // Mask Start Index
5234 NumElems-NumZeros, // Mask End Index(exclusive)
5235 NumZeros, // Where to start looking in the src vector
5236 NumElems, // Number of elements in vector
5237 OpSrc)) // Which source operand ?
5242 ShVal = SVOp->getOperand(OpSrc);
5246 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5247 /// logical left shift of a vector.
5248 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5249 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5251 SVOp->getSimpleValueType(0).getVectorNumElements();
5252 unsigned NumZeros = getNumOfConsecutiveZeros(
5253 SVOp, NumElems, true /* check zeros from left */, DAG,
5254 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5260 // Considering the elements in the mask that are not consecutive zeros,
5261 // check if they consecutively come from only one of the source vectors.
5263 // 0 { A, B, X, X } = V2
5265 // vector_shuffle V1, V2 <X, X, 4, 5>
5267 if (!isShuffleMaskConsecutive(SVOp,
5268 NumZeros, // Mask Start Index
5269 NumElems, // Mask End Index(exclusive)
5270 0, // Where to start looking in the src vector
5271 NumElems, // Number of elements in vector
5272 OpSrc)) // Which source operand ?
5277 ShVal = SVOp->getOperand(OpSrc);
5281 /// isVectorShift - Returns true if the shuffle can be implemented as a
5282 /// logical left or right shift of a vector.
5283 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5284 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5285 // Although the logic below support any bitwidth size, there are no
5286 // shift instructions which handle more than 128-bit vectors.
5287 if (!SVOp->getSimpleValueType(0).is128BitVector())
5290 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5291 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5297 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5299 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5300 unsigned NumNonZero, unsigned NumZero,
5302 const X86Subtarget* Subtarget,
5303 const TargetLowering &TLI) {
5310 for (unsigned i = 0; i < 16; ++i) {
5311 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5312 if (ThisIsNonZero && First) {
5314 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5316 V = DAG.getUNDEF(MVT::v8i16);
5321 SDValue ThisElt(0, 0), LastElt(0, 0);
5322 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5323 if (LastIsNonZero) {
5324 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5325 MVT::i16, Op.getOperand(i-1));
5327 if (ThisIsNonZero) {
5328 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5329 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5330 ThisElt, DAG.getConstant(8, MVT::i8));
5332 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5336 if (ThisElt.getNode())
5337 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5338 DAG.getIntPtrConstant(i/2));
5342 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5345 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5347 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5348 unsigned NumNonZero, unsigned NumZero,
5350 const X86Subtarget* Subtarget,
5351 const TargetLowering &TLI) {
5358 for (unsigned i = 0; i < 8; ++i) {
5359 bool isNonZero = (NonZeros & (1 << i)) != 0;
5363 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5365 V = DAG.getUNDEF(MVT::v8i16);
5368 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5369 MVT::v8i16, V, Op.getOperand(i),
5370 DAG.getIntPtrConstant(i));
5377 /// getVShift - Return a vector logical shift node.
5379 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5380 unsigned NumBits, SelectionDAG &DAG,
5381 const TargetLowering &TLI, SDLoc dl) {
5382 assert(VT.is128BitVector() && "Unknown type for VShift");
5383 EVT ShVT = MVT::v2i64;
5384 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5385 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5386 return DAG.getNode(ISD::BITCAST, dl, VT,
5387 DAG.getNode(Opc, dl, ShVT, SrcOp,
5388 DAG.getConstant(NumBits,
5389 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5393 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5395 // Check if the scalar load can be widened into a vector load. And if
5396 // the address is "base + cst" see if the cst can be "absorbed" into
5397 // the shuffle mask.
5398 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5399 SDValue Ptr = LD->getBasePtr();
5400 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5402 EVT PVT = LD->getValueType(0);
5403 if (PVT != MVT::i32 && PVT != MVT::f32)
5408 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5409 FI = FINode->getIndex();
5411 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5412 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5413 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5414 Offset = Ptr.getConstantOperandVal(1);
5415 Ptr = Ptr.getOperand(0);
5420 // FIXME: 256-bit vector instructions don't require a strict alignment,
5421 // improve this code to support it better.
5422 unsigned RequiredAlign = VT.getSizeInBits()/8;
5423 SDValue Chain = LD->getChain();
5424 // Make sure the stack object alignment is at least 16 or 32.
5425 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5426 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5427 if (MFI->isFixedObjectIndex(FI)) {
5428 // Can't change the alignment. FIXME: It's possible to compute
5429 // the exact stack offset and reference FI + adjust offset instead.
5430 // If someone *really* cares about this. That's the way to implement it.
5433 MFI->setObjectAlignment(FI, RequiredAlign);
5437 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5438 // Ptr + (Offset & ~15).
5441 if ((Offset % RequiredAlign) & 3)
5443 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5445 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5446 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5448 int EltNo = (Offset - StartOffset) >> 2;
5449 unsigned NumElems = VT.getVectorNumElements();
5451 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5452 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5453 LD->getPointerInfo().getWithOffset(StartOffset),
5454 false, false, false, 0);
5456 SmallVector<int, 8> Mask;
5457 for (unsigned i = 0; i != NumElems; ++i)
5458 Mask.push_back(EltNo);
5460 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5466 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5467 /// vector of type 'VT', see if the elements can be replaced by a single large
5468 /// load which has the same value as a build_vector whose operands are 'elts'.
5470 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5472 /// FIXME: we'd also like to handle the case where the last elements are zero
5473 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5474 /// There's even a handy isZeroNode for that purpose.
5475 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5476 SDLoc &DL, SelectionDAG &DAG,
5477 bool isAfterLegalize) {
5478 EVT EltVT = VT.getVectorElementType();
5479 unsigned NumElems = Elts.size();
5481 LoadSDNode *LDBase = NULL;
5482 unsigned LastLoadedElt = -1U;
5484 // For each element in the initializer, see if we've found a load or an undef.
5485 // If we don't find an initial load element, or later load elements are
5486 // non-consecutive, bail out.
5487 for (unsigned i = 0; i < NumElems; ++i) {
5488 SDValue Elt = Elts[i];
5490 if (!Elt.getNode() ||
5491 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5494 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5496 LDBase = cast<LoadSDNode>(Elt.getNode());
5500 if (Elt.getOpcode() == ISD::UNDEF)
5503 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5504 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5509 // If we have found an entire vector of loads and undefs, then return a large
5510 // load of the entire vector width starting at the base pointer. If we found
5511 // consecutive loads for the low half, generate a vzext_load node.
5512 if (LastLoadedElt == NumElems - 1) {
5514 if (isAfterLegalize &&
5515 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5518 SDValue NewLd = SDValue();
5520 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5521 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5522 LDBase->getPointerInfo(),
5523 LDBase->isVolatile(), LDBase->isNonTemporal(),
5524 LDBase->isInvariant(), 0);
5525 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5526 LDBase->getPointerInfo(),
5527 LDBase->isVolatile(), LDBase->isNonTemporal(),
5528 LDBase->isInvariant(), LDBase->getAlignment());
5530 if (LDBase->hasAnyUseOfValue(1)) {
5531 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5533 SDValue(NewLd.getNode(), 1));
5534 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5535 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5536 SDValue(NewLd.getNode(), 1));
5541 if (NumElems == 4 && LastLoadedElt == 1 &&
5542 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5543 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5544 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5546 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5547 array_lengthof(Ops), MVT::i64,
5548 LDBase->getPointerInfo(),
5549 LDBase->getAlignment(),
5550 false/*isVolatile*/, true/*ReadMem*/,
5553 // Make sure the newly-created LOAD is in the same position as LDBase in
5554 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5555 // update uses of LDBase's output chain to use the TokenFactor.
5556 if (LDBase->hasAnyUseOfValue(1)) {
5557 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5558 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5559 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5560 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5561 SDValue(ResNode.getNode(), 1));
5564 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5569 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5570 /// to generate a splat value for the following cases:
5571 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5572 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5573 /// a scalar load, or a constant.
5574 /// The VBROADCAST node is returned when a pattern is found,
5575 /// or SDValue() otherwise.
5576 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5577 SelectionDAG &DAG) {
5578 if (!Subtarget->hasFp256())
5581 MVT VT = Op.getSimpleValueType();
5584 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5585 "Unsupported vector type for broadcast.");
5590 switch (Op.getOpcode()) {
5592 // Unknown pattern found.
5595 case ISD::BUILD_VECTOR: {
5596 // The BUILD_VECTOR node must be a splat.
5597 if (!isSplatVector(Op.getNode()))
5600 Ld = Op.getOperand(0);
5601 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5602 Ld.getOpcode() == ISD::ConstantFP);
5604 // The suspected load node has several users. Make sure that all
5605 // of its users are from the BUILD_VECTOR node.
5606 // Constants may have multiple users.
5607 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5612 case ISD::VECTOR_SHUFFLE: {
5613 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5615 // Shuffles must have a splat mask where the first element is
5617 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5620 SDValue Sc = Op.getOperand(0);
5621 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5622 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5624 if (!Subtarget->hasInt256())
5627 // Use the register form of the broadcast instruction available on AVX2.
5628 if (VT.getSizeInBits() >= 256)
5629 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5630 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5633 Ld = Sc.getOperand(0);
5634 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5635 Ld.getOpcode() == ISD::ConstantFP);
5637 // The scalar_to_vector node and the suspected
5638 // load node must have exactly one user.
5639 // Constants may have multiple users.
5641 // AVX-512 has register version of the broadcast
5642 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5643 Ld.getValueType().getSizeInBits() >= 32;
5644 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5651 bool IsGE256 = (VT.getSizeInBits() >= 256);
5653 // Handle the broadcasting a single constant scalar from the constant pool
5654 // into a vector. On Sandybridge it is still better to load a constant vector
5655 // from the constant pool and not to broadcast it from a scalar.
5656 if (ConstSplatVal && Subtarget->hasInt256()) {
5657 EVT CVT = Ld.getValueType();
5658 assert(!CVT.isVector() && "Must not broadcast a vector type");
5659 unsigned ScalarSize = CVT.getSizeInBits();
5661 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5662 const Constant *C = 0;
5663 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5664 C = CI->getConstantIntValue();
5665 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5666 C = CF->getConstantFPValue();
5668 assert(C && "Invalid constant type");
5670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5671 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5672 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5673 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5674 MachinePointerInfo::getConstantPool(),
5675 false, false, false, Alignment);
5677 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5681 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5682 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5684 // Handle AVX2 in-register broadcasts.
5685 if (!IsLoad && Subtarget->hasInt256() &&
5686 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5687 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5689 // The scalar source must be a normal load.
5693 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5694 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5696 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5697 // double since there is no vbroadcastsd xmm
5698 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5699 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5700 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5703 // Unsupported broadcast.
5707 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5708 /// underlying vector and index.
5710 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5712 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5714 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5715 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5718 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5720 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5722 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5723 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5726 // In this case the vector is the extract_subvector expression and the index
5727 // is 2, as specified by the shuffle.
5728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5729 SDValue ShuffleVec = SVOp->getOperand(0);
5730 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5731 assert(ShuffleVecVT.getVectorElementType() ==
5732 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5734 int ShuffleIdx = SVOp->getMaskElt(Idx);
5735 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5736 ExtractedFromVec = ShuffleVec;
5742 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5743 MVT VT = Op.getSimpleValueType();
5745 // Skip if insert_vec_elt is not supported.
5746 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5747 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5751 unsigned NumElems = Op.getNumOperands();
5755 SmallVector<unsigned, 4> InsertIndices;
5756 SmallVector<int, 8> Mask(NumElems, -1);
5758 for (unsigned i = 0; i != NumElems; ++i) {
5759 unsigned Opc = Op.getOperand(i).getOpcode();
5761 if (Opc == ISD::UNDEF)
5764 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5765 // Quit if more than 1 elements need inserting.
5766 if (InsertIndices.size() > 1)
5769 InsertIndices.push_back(i);
5773 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5774 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5775 // Quit if non-constant index.
5776 if (!isa<ConstantSDNode>(ExtIdx))
5778 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5780 // Quit if extracted from vector of different type.
5781 if (ExtractedFromVec.getValueType() != VT)
5784 if (VecIn1.getNode() == 0)
5785 VecIn1 = ExtractedFromVec;
5786 else if (VecIn1 != ExtractedFromVec) {
5787 if (VecIn2.getNode() == 0)
5788 VecIn2 = ExtractedFromVec;
5789 else if (VecIn2 != ExtractedFromVec)
5790 // Quit if more than 2 vectors to shuffle
5794 if (ExtractedFromVec == VecIn1)
5796 else if (ExtractedFromVec == VecIn2)
5797 Mask[i] = Idx + NumElems;
5800 if (VecIn1.getNode() == 0)
5803 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5804 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5805 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5806 unsigned Idx = InsertIndices[i];
5807 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5808 DAG.getIntPtrConstant(Idx));
5814 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5816 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5818 MVT VT = Op.getSimpleValueType();
5819 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5820 "Unexpected type in LowerBUILD_VECTORvXi1!");
5823 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5824 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5825 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5826 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5827 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5828 Ops, VT.getVectorNumElements());
5831 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5832 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5833 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5834 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5835 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5836 Ops, VT.getVectorNumElements());
5839 bool AllContants = true;
5840 uint64_t Immediate = 0;
5841 int NonConstIdx = -1;
5842 bool IsSplat = true;
5843 unsigned NumNonConsts = 0;
5844 unsigned NumConsts = 0;
5845 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5846 SDValue In = Op.getOperand(idx);
5847 if (In.getOpcode() == ISD::UNDEF)
5849 if (!isa<ConstantSDNode>(In)) {
5850 AllContants = false;
5856 if (cast<ConstantSDNode>(In)->getZExtValue())
5857 Immediate |= (1ULL << idx);
5859 if (In != Op.getOperand(0))
5864 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5865 DAG.getConstant(Immediate, MVT::i16));
5866 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5867 DAG.getIntPtrConstant(0));
5870 if (NumNonConsts == 1 && NonConstIdx != 0) {
5873 SDValue VecAsImm = DAG.getConstant(Immediate,
5874 MVT::getIntegerVT(VT.getSizeInBits()));
5875 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5878 DstVec = DAG.getUNDEF(VT);
5879 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5880 Op.getOperand(NonConstIdx),
5881 DAG.getIntPtrConstant(NonConstIdx));
5883 if (!IsSplat && (NonConstIdx != 0))
5884 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5885 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5888 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5889 DAG.getConstant(-1, SelectVT),
5890 DAG.getConstant(0, SelectVT));
5892 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5893 DAG.getConstant((Immediate | 1), SelectVT),
5894 DAG.getConstant(Immediate, SelectVT));
5895 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5899 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5902 MVT VT = Op.getSimpleValueType();
5903 MVT ExtVT = VT.getVectorElementType();
5904 unsigned NumElems = Op.getNumOperands();
5906 // Generate vectors for predicate vectors.
5907 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5908 return LowerBUILD_VECTORvXi1(Op, DAG);
5910 // Vectors containing all zeros can be matched by pxor and xorps later
5911 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5912 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5913 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5914 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5917 return getZeroVector(VT, Subtarget, DAG, dl);
5920 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5921 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5922 // vpcmpeqd on 256-bit vectors.
5923 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5924 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5927 if (!VT.is512BitVector())
5928 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5931 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5932 if (Broadcast.getNode())
5935 unsigned EVTBits = ExtVT.getSizeInBits();
5937 unsigned NumZero = 0;
5938 unsigned NumNonZero = 0;
5939 unsigned NonZeros = 0;
5940 bool IsAllConstants = true;
5941 SmallSet<SDValue, 8> Values;
5942 for (unsigned i = 0; i < NumElems; ++i) {
5943 SDValue Elt = Op.getOperand(i);
5944 if (Elt.getOpcode() == ISD::UNDEF)
5947 if (Elt.getOpcode() != ISD::Constant &&
5948 Elt.getOpcode() != ISD::ConstantFP)
5949 IsAllConstants = false;
5950 if (X86::isZeroNode(Elt))
5953 NonZeros |= (1 << i);
5958 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5959 if (NumNonZero == 0)
5960 return DAG.getUNDEF(VT);
5962 // Special case for single non-zero, non-undef, element.
5963 if (NumNonZero == 1) {
5964 unsigned Idx = countTrailingZeros(NonZeros);
5965 SDValue Item = Op.getOperand(Idx);
5967 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5968 // the value are obviously zero, truncate the value to i32 and do the
5969 // insertion that way. Only do this if the value is non-constant or if the
5970 // value is a constant being inserted into element 0. It is cheaper to do
5971 // a constant pool load than it is to do a movd + shuffle.
5972 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5973 (!IsAllConstants || Idx == 0)) {
5974 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5976 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5977 EVT VecVT = MVT::v4i32;
5978 unsigned VecElts = 4;
5980 // Truncate the value (which may itself be a constant) to i32, and
5981 // convert it to a vector with movd (S2V+shuffle to zero extend).
5982 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5983 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5984 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5986 // Now we have our 32-bit value zero extended in the low element of
5987 // a vector. If Idx != 0, swizzle it into place.
5989 SmallVector<int, 4> Mask;
5990 Mask.push_back(Idx);
5991 for (unsigned i = 1; i != VecElts; ++i)
5993 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5996 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6000 // If we have a constant or non-constant insertion into the low element of
6001 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6002 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6003 // depending on what the source datatype is.
6006 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6008 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6009 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6010 if (VT.is256BitVector() || VT.is512BitVector()) {
6011 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6012 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6013 Item, DAG.getIntPtrConstant(0));
6015 assert(VT.is128BitVector() && "Expected an SSE value type!");
6016 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6017 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6018 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6021 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6022 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6023 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6024 if (VT.is256BitVector()) {
6025 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6026 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6028 assert(VT.is128BitVector() && "Expected an SSE value type!");
6029 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6031 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6035 // Is it a vector logical left shift?
6036 if (NumElems == 2 && Idx == 1 &&
6037 X86::isZeroNode(Op.getOperand(0)) &&
6038 !X86::isZeroNode(Op.getOperand(1))) {
6039 unsigned NumBits = VT.getSizeInBits();
6040 return getVShift(true, VT,
6041 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6042 VT, Op.getOperand(1)),
6043 NumBits/2, DAG, *this, dl);
6046 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6049 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6050 // is a non-constant being inserted into an element other than the low one,
6051 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6052 // movd/movss) to move this into the low element, then shuffle it into
6054 if (EVTBits == 32) {
6055 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6057 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6058 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6059 SmallVector<int, 8> MaskVec;
6060 for (unsigned i = 0; i != NumElems; ++i)
6061 MaskVec.push_back(i == Idx ? 0 : 1);
6062 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6066 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6067 if (Values.size() == 1) {
6068 if (EVTBits == 32) {
6069 // Instead of a shuffle like this:
6070 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6071 // Check if it's possible to issue this instead.
6072 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6073 unsigned Idx = countTrailingZeros(NonZeros);
6074 SDValue Item = Op.getOperand(Idx);
6075 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6076 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6081 // A vector full of immediates; various special cases are already
6082 // handled, so this is best done with a single constant-pool load.
6086 // For AVX-length vectors, build the individual 128-bit pieces and use
6087 // shuffles to put them in place.
6088 if (VT.is256BitVector() || VT.is512BitVector()) {
6089 SmallVector<SDValue, 64> V;
6090 for (unsigned i = 0; i != NumElems; ++i)
6091 V.push_back(Op.getOperand(i));
6093 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6095 // Build both the lower and upper subvector.
6096 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6097 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6100 // Recreate the wider vector with the lower and upper part.
6101 if (VT.is256BitVector())
6102 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6103 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6106 // Let legalizer expand 2-wide build_vectors.
6107 if (EVTBits == 64) {
6108 if (NumNonZero == 1) {
6109 // One half is zero or undef.
6110 unsigned Idx = countTrailingZeros(NonZeros);
6111 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6112 Op.getOperand(Idx));
6113 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6118 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6119 if (EVTBits == 8 && NumElems == 16) {
6120 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6122 if (V.getNode()) return V;
6125 if (EVTBits == 16 && NumElems == 8) {
6126 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6128 if (V.getNode()) return V;
6131 // If element VT is == 32 bits, turn it into a number of shuffles.
6132 SmallVector<SDValue, 8> V(NumElems);
6133 if (NumElems == 4 && NumZero > 0) {
6134 for (unsigned i = 0; i < 4; ++i) {
6135 bool isZero = !(NonZeros & (1 << i));
6137 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6139 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6142 for (unsigned i = 0; i < 2; ++i) {
6143 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6146 V[i] = V[i*2]; // Must be a zero vector.
6149 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6152 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6155 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6160 bool Reverse1 = (NonZeros & 0x3) == 2;
6161 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6165 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6166 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6168 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6171 if (Values.size() > 1 && VT.is128BitVector()) {
6172 // Check for a build vector of consecutive loads.
6173 for (unsigned i = 0; i < NumElems; ++i)
6174 V[i] = Op.getOperand(i);
6176 // Check for elements which are consecutive loads.
6177 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6181 // Check for a build vector from mostly shuffle plus few inserting.
6182 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6186 // For SSE 4.1, use insertps to put the high elements into the low element.
6187 if (getSubtarget()->hasSSE41()) {
6189 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6190 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6192 Result = DAG.getUNDEF(VT);
6194 for (unsigned i = 1; i < NumElems; ++i) {
6195 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6196 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6197 Op.getOperand(i), DAG.getIntPtrConstant(i));
6202 // Otherwise, expand into a number of unpckl*, start by extending each of
6203 // our (non-undef) elements to the full vector width with the element in the
6204 // bottom slot of the vector (which generates no code for SSE).
6205 for (unsigned i = 0; i < NumElems; ++i) {
6206 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6207 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6209 V[i] = DAG.getUNDEF(VT);
6212 // Next, we iteratively mix elements, e.g. for v4f32:
6213 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6214 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6215 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6216 unsigned EltStride = NumElems >> 1;
6217 while (EltStride != 0) {
6218 for (unsigned i = 0; i < EltStride; ++i) {
6219 // If V[i+EltStride] is undef and this is the first round of mixing,
6220 // then it is safe to just drop this shuffle: V[i] is already in the
6221 // right place, the one element (since it's the first round) being
6222 // inserted as undef can be dropped. This isn't safe for successive
6223 // rounds because they will permute elements within both vectors.
6224 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6225 EltStride == NumElems/2)
6228 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6237 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6238 // to create 256-bit vectors from two other 128-bit ones.
6239 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6241 MVT ResVT = Op.getSimpleValueType();
6243 assert((ResVT.is256BitVector() ||
6244 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6246 SDValue V1 = Op.getOperand(0);
6247 SDValue V2 = Op.getOperand(1);
6248 unsigned NumElems = ResVT.getVectorNumElements();
6249 if(ResVT.is256BitVector())
6250 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6252 if (Op.getNumOperands() == 4) {
6253 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6254 ResVT.getVectorNumElements()/2);
6255 SDValue V3 = Op.getOperand(2);
6256 SDValue V4 = Op.getOperand(3);
6257 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6258 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6260 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6263 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6264 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6265 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6266 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6267 Op.getNumOperands() == 4)));
6269 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6270 // from two other 128-bit ones.
6272 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6273 return LowerAVXCONCAT_VECTORS(Op, DAG);
6276 // Try to lower a shuffle node into a simple blend instruction.
6278 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6279 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6280 SDValue V1 = SVOp->getOperand(0);
6281 SDValue V2 = SVOp->getOperand(1);
6283 MVT VT = SVOp->getSimpleValueType(0);
6284 MVT EltVT = VT.getVectorElementType();
6285 unsigned NumElems = VT.getVectorNumElements();
6287 // There is no blend with immediate in AVX-512.
6288 if (VT.is512BitVector())
6291 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6293 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6296 // Check the mask for BLEND and build the value.
6297 unsigned MaskValue = 0;
6298 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6299 unsigned NumLanes = (NumElems-1)/8 + 1;
6300 unsigned NumElemsInLane = NumElems / NumLanes;
6302 // Blend for v16i16 should be symetric for the both lanes.
6303 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6305 int SndLaneEltIdx = (NumLanes == 2) ?
6306 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6307 int EltIdx = SVOp->getMaskElt(i);
6309 if ((EltIdx < 0 || EltIdx == (int)i) &&
6310 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6313 if (((unsigned)EltIdx == (i + NumElems)) &&
6314 (SndLaneEltIdx < 0 ||
6315 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6316 MaskValue |= (1<<i);
6321 // Convert i32 vectors to floating point if it is not AVX2.
6322 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6324 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6325 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6327 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6328 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6331 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6332 DAG.getConstant(MaskValue, MVT::i32));
6333 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6336 /// In vector type \p VT, return true if the element at index \p InputIdx
6337 /// falls on a different 128-bit lane than \p OutputIdx.
6338 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6339 unsigned OutputIdx) {
6340 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6341 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6344 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6345 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6346 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6347 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6349 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6350 SelectionDAG &DAG) {
6351 MVT VT = V1.getSimpleValueType();
6352 assert(VT.is128BitVector() || VT.is256BitVector());
6354 MVT EltVT = VT.getVectorElementType();
6355 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6356 unsigned NumElts = VT.getVectorNumElements();
6358 SmallVector<SDValue, 32> PshufbMask;
6359 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6360 int InputIdx = MaskVals[OutputIdx];
6361 unsigned InputByteIdx;
6363 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6364 InputByteIdx = 0x80;
6366 // Cross lane is not allowed.
6367 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6369 InputByteIdx = InputIdx * EltSizeInBytes;
6370 // Index is an byte offset within the 128-bit lane.
6371 InputByteIdx &= 0xf;
6374 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6375 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6376 if (InputByteIdx != 0x80)
6381 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6383 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6384 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6385 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT,
6386 PshufbMask.data(), PshufbMask.size()));
6389 // v8i16 shuffles - Prefer shuffles in the following order:
6390 // 1. [all] pshuflw, pshufhw, optional move
6391 // 2. [ssse3] 1 x pshufb
6392 // 3. [ssse3] 2 x pshufb + 1 x por
6393 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6395 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6396 SelectionDAG &DAG) {
6397 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6398 SDValue V1 = SVOp->getOperand(0);
6399 SDValue V2 = SVOp->getOperand(1);
6401 SmallVector<int, 8> MaskVals;
6403 // Determine if more than 1 of the words in each of the low and high quadwords
6404 // of the result come from the same quadword of one of the two inputs. Undef
6405 // mask values count as coming from any quadword, for better codegen.
6407 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6408 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6409 unsigned LoQuad[] = { 0, 0, 0, 0 };
6410 unsigned HiQuad[] = { 0, 0, 0, 0 };
6411 // Indices of quads used.
6412 std::bitset<4> InputQuads;
6413 for (unsigned i = 0; i < 8; ++i) {
6414 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6415 int EltIdx = SVOp->getMaskElt(i);
6416 MaskVals.push_back(EltIdx);
6425 InputQuads.set(EltIdx / 4);
6428 int BestLoQuad = -1;
6429 unsigned MaxQuad = 1;
6430 for (unsigned i = 0; i < 4; ++i) {
6431 if (LoQuad[i] > MaxQuad) {
6433 MaxQuad = LoQuad[i];
6437 int BestHiQuad = -1;
6439 for (unsigned i = 0; i < 4; ++i) {
6440 if (HiQuad[i] > MaxQuad) {
6442 MaxQuad = HiQuad[i];
6446 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6447 // of the two input vectors, shuffle them into one input vector so only a
6448 // single pshufb instruction is necessary. If there are more than 2 input
6449 // quads, disable the next transformation since it does not help SSSE3.
6450 bool V1Used = InputQuads[0] || InputQuads[1];
6451 bool V2Used = InputQuads[2] || InputQuads[3];
6452 if (Subtarget->hasSSSE3()) {
6453 if (InputQuads.count() == 2 && V1Used && V2Used) {
6454 BestLoQuad = InputQuads[0] ? 0 : 1;
6455 BestHiQuad = InputQuads[2] ? 2 : 3;
6457 if (InputQuads.count() > 2) {
6463 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6464 // the shuffle mask. If a quad is scored as -1, that means that it contains
6465 // words from all 4 input quadwords.
6467 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6469 BestLoQuad < 0 ? 0 : BestLoQuad,
6470 BestHiQuad < 0 ? 1 : BestHiQuad
6472 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6473 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6474 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6475 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6477 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6478 // source words for the shuffle, to aid later transformations.
6479 bool AllWordsInNewV = true;
6480 bool InOrder[2] = { true, true };
6481 for (unsigned i = 0; i != 8; ++i) {
6482 int idx = MaskVals[i];
6484 InOrder[i/4] = false;
6485 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6487 AllWordsInNewV = false;
6491 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6492 if (AllWordsInNewV) {
6493 for (int i = 0; i != 8; ++i) {
6494 int idx = MaskVals[i];
6497 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6498 if ((idx != i) && idx < 4)
6500 if ((idx != i) && idx > 3)
6509 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6510 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6511 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6512 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6513 unsigned TargetMask = 0;
6514 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6515 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6516 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6517 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6518 getShufflePSHUFLWImmediate(SVOp);
6519 V1 = NewV.getOperand(0);
6520 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6524 // Promote splats to a larger type which usually leads to more efficient code.
6525 // FIXME: Is this true if pshufb is available?
6526 if (SVOp->isSplat())
6527 return PromoteSplat(SVOp, DAG);
6529 // If we have SSSE3, and all words of the result are from 1 input vector,
6530 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6531 // is present, fall back to case 4.
6532 if (Subtarget->hasSSSE3()) {
6533 SmallVector<SDValue,16> pshufbMask;
6535 // If we have elements from both input vectors, set the high bit of the
6536 // shuffle mask element to zero out elements that come from V2 in the V1
6537 // mask, and elements that come from V1 in the V2 mask, so that the two
6538 // results can be OR'd together.
6539 bool TwoInputs = V1Used && V2Used;
6540 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6542 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6544 // Calculate the shuffle mask for the second input, shuffle it, and
6545 // OR it with the first shuffled input.
6546 CommuteVectorShuffleMask(MaskVals, 8);
6547 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6548 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6549 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6552 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6553 // and update MaskVals with new element order.
6554 std::bitset<8> InOrder;
6555 if (BestLoQuad >= 0) {
6556 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6557 for (int i = 0; i != 4; ++i) {
6558 int idx = MaskVals[i];
6561 } else if ((idx / 4) == BestLoQuad) {
6566 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6569 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6570 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6571 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6573 getShufflePSHUFLWImmediate(SVOp), DAG);
6577 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6578 // and update MaskVals with the new element order.
6579 if (BestHiQuad >= 0) {
6580 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6581 for (unsigned i = 4; i != 8; ++i) {
6582 int idx = MaskVals[i];
6585 } else if ((idx / 4) == BestHiQuad) {
6586 MaskV[i] = (idx & 3) + 4;
6590 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6593 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6594 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6595 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6597 getShufflePSHUFHWImmediate(SVOp), DAG);
6601 // In case BestHi & BestLo were both -1, which means each quadword has a word
6602 // from each of the four input quadwords, calculate the InOrder bitvector now
6603 // before falling through to the insert/extract cleanup.
6604 if (BestLoQuad == -1 && BestHiQuad == -1) {
6606 for (int i = 0; i != 8; ++i)
6607 if (MaskVals[i] < 0 || MaskVals[i] == i)
6611 // The other elements are put in the right place using pextrw and pinsrw.
6612 for (unsigned i = 0; i != 8; ++i) {
6615 int EltIdx = MaskVals[i];
6618 SDValue ExtOp = (EltIdx < 8) ?
6619 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6620 DAG.getIntPtrConstant(EltIdx)) :
6621 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6622 DAG.getIntPtrConstant(EltIdx - 8));
6623 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6624 DAG.getIntPtrConstant(i));
6629 /// \brief v16i16 shuffles
6631 /// FIXME: We only support generation of a single pshufb currently. We can
6632 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6633 /// well (e.g 2 x pshufb + 1 x por).
6635 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6636 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6637 SDValue V1 = SVOp->getOperand(0);
6638 SDValue V2 = SVOp->getOperand(1);
6641 if (V2.getOpcode() != ISD::UNDEF)
6644 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6645 return getPSHUFB(MaskVals, V1, dl, DAG);
6648 // v16i8 shuffles - Prefer shuffles in the following order:
6649 // 1. [ssse3] 1 x pshufb
6650 // 2. [ssse3] 2 x pshufb + 1 x por
6651 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6652 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6653 const X86Subtarget* Subtarget,
6654 SelectionDAG &DAG) {
6655 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6656 SDValue V1 = SVOp->getOperand(0);
6657 SDValue V2 = SVOp->getOperand(1);
6659 ArrayRef<int> MaskVals = SVOp->getMask();
6661 // Promote splats to a larger type which usually leads to more efficient code.
6662 // FIXME: Is this true if pshufb is available?
6663 if (SVOp->isSplat())
6664 return PromoteSplat(SVOp, DAG);
6666 // If we have SSSE3, case 1 is generated when all result bytes come from
6667 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6668 // present, fall back to case 3.
6670 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6671 if (Subtarget->hasSSSE3()) {
6672 SmallVector<SDValue,16> pshufbMask;
6674 // If all result elements are from one input vector, then only translate
6675 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6677 // Otherwise, we have elements from both input vectors, and must zero out
6678 // elements that come from V2 in the first mask, and V1 in the second mask
6679 // so that we can OR them together.
6680 for (unsigned i = 0; i != 16; ++i) {
6681 int EltIdx = MaskVals[i];
6682 if (EltIdx < 0 || EltIdx >= 16)
6684 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6686 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6687 DAG.getNode(ISD::BUILD_VECTOR, dl,
6688 MVT::v16i8, &pshufbMask[0], 16));
6690 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6691 // the 2nd operand if it's undefined or zero.
6692 if (V2.getOpcode() == ISD::UNDEF ||
6693 ISD::isBuildVectorAllZeros(V2.getNode()))
6696 // Calculate the shuffle mask for the second input, shuffle it, and
6697 // OR it with the first shuffled input.
6699 for (unsigned i = 0; i != 16; ++i) {
6700 int EltIdx = MaskVals[i];
6701 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6702 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6704 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6705 DAG.getNode(ISD::BUILD_VECTOR, dl,
6706 MVT::v16i8, &pshufbMask[0], 16));
6707 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6710 // No SSSE3 - Calculate in place words and then fix all out of place words
6711 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6712 // the 16 different words that comprise the two doublequadword input vectors.
6713 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6714 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6716 for (int i = 0; i != 8; ++i) {
6717 int Elt0 = MaskVals[i*2];
6718 int Elt1 = MaskVals[i*2+1];
6720 // This word of the result is all undef, skip it.
6721 if (Elt0 < 0 && Elt1 < 0)
6724 // This word of the result is already in the correct place, skip it.
6725 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6728 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6729 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6732 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6733 // using a single extract together, load it and store it.
6734 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6735 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6736 DAG.getIntPtrConstant(Elt1 / 2));
6737 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6738 DAG.getIntPtrConstant(i));
6742 // If Elt1 is defined, extract it from the appropriate source. If the
6743 // source byte is not also odd, shift the extracted word left 8 bits
6744 // otherwise clear the bottom 8 bits if we need to do an or.
6746 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6747 DAG.getIntPtrConstant(Elt1 / 2));
6748 if ((Elt1 & 1) == 0)
6749 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6751 TLI.getShiftAmountTy(InsElt.getValueType())));
6753 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6754 DAG.getConstant(0xFF00, MVT::i16));
6756 // If Elt0 is defined, extract it from the appropriate source. If the
6757 // source byte is not also even, shift the extracted word right 8 bits. If
6758 // Elt1 was also defined, OR the extracted values together before
6759 // inserting them in the result.
6761 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6762 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6763 if ((Elt0 & 1) != 0)
6764 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6766 TLI.getShiftAmountTy(InsElt0.getValueType())));
6768 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6769 DAG.getConstant(0x00FF, MVT::i16));
6770 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6773 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6774 DAG.getIntPtrConstant(i));
6776 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6779 // v32i8 shuffles - Translate to VPSHUFB if possible.
6781 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6782 const X86Subtarget *Subtarget,
6783 SelectionDAG &DAG) {
6784 MVT VT = SVOp->getSimpleValueType(0);
6785 SDValue V1 = SVOp->getOperand(0);
6786 SDValue V2 = SVOp->getOperand(1);
6788 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6790 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6791 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6792 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6794 // VPSHUFB may be generated if
6795 // (1) one of input vector is undefined or zeroinitializer.
6796 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6797 // And (2) the mask indexes don't cross the 128-bit lane.
6798 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6799 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6802 if (V1IsAllZero && !V2IsAllZero) {
6803 CommuteVectorShuffleMask(MaskVals, 32);
6806 return getPSHUFB(MaskVals, V1, dl, DAG);
6809 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6810 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6811 /// done when every pair / quad of shuffle mask elements point to elements in
6812 /// the right sequence. e.g.
6813 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6815 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6816 SelectionDAG &DAG) {
6817 MVT VT = SVOp->getSimpleValueType(0);
6819 unsigned NumElems = VT.getVectorNumElements();
6822 switch (VT.SimpleTy) {
6823 default: llvm_unreachable("Unexpected!");
6824 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6825 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6826 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6827 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6828 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6829 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6832 SmallVector<int, 8> MaskVec;
6833 for (unsigned i = 0; i != NumElems; i += Scale) {
6835 for (unsigned j = 0; j != Scale; ++j) {
6836 int EltIdx = SVOp->getMaskElt(i+j);
6840 StartIdx = (EltIdx / Scale);
6841 if (EltIdx != (int)(StartIdx*Scale + j))
6844 MaskVec.push_back(StartIdx);
6847 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6848 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6849 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6852 /// getVZextMovL - Return a zero-extending vector move low node.
6854 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6855 SDValue SrcOp, SelectionDAG &DAG,
6856 const X86Subtarget *Subtarget, SDLoc dl) {
6857 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6858 LoadSDNode *LD = NULL;
6859 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6860 LD = dyn_cast<LoadSDNode>(SrcOp);
6862 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6864 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6865 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6866 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6867 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6868 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6870 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6871 return DAG.getNode(ISD::BITCAST, dl, VT,
6872 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6873 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6881 return DAG.getNode(ISD::BITCAST, dl, VT,
6882 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6883 DAG.getNode(ISD::BITCAST, dl,
6887 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6888 /// which could not be matched by any known target speficic shuffle
6890 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6892 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6893 if (NewOp.getNode())
6896 MVT VT = SVOp->getSimpleValueType(0);
6898 unsigned NumElems = VT.getVectorNumElements();
6899 unsigned NumLaneElems = NumElems / 2;
6902 MVT EltVT = VT.getVectorElementType();
6903 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6906 SmallVector<int, 16> Mask;
6907 for (unsigned l = 0; l < 2; ++l) {
6908 // Build a shuffle mask for the output, discovering on the fly which
6909 // input vectors to use as shuffle operands (recorded in InputUsed).
6910 // If building a suitable shuffle vector proves too hard, then bail
6911 // out with UseBuildVector set.
6912 bool UseBuildVector = false;
6913 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6914 unsigned LaneStart = l * NumLaneElems;
6915 for (unsigned i = 0; i != NumLaneElems; ++i) {
6916 // The mask element. This indexes into the input.
6917 int Idx = SVOp->getMaskElt(i+LaneStart);
6919 // the mask element does not index into any input vector.
6924 // The input vector this mask element indexes into.
6925 int Input = Idx / NumLaneElems;
6927 // Turn the index into an offset from the start of the input vector.
6928 Idx -= Input * NumLaneElems;
6930 // Find or create a shuffle vector operand to hold this input.
6932 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6933 if (InputUsed[OpNo] == Input)
6934 // This input vector is already an operand.
6936 if (InputUsed[OpNo] < 0) {
6937 // Create a new operand for this input vector.
6938 InputUsed[OpNo] = Input;
6943 if (OpNo >= array_lengthof(InputUsed)) {
6944 // More than two input vectors used! Give up on trying to create a
6945 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6946 UseBuildVector = true;
6950 // Add the mask index for the new shuffle vector.
6951 Mask.push_back(Idx + OpNo * NumLaneElems);
6954 if (UseBuildVector) {
6955 SmallVector<SDValue, 16> SVOps;
6956 for (unsigned i = 0; i != NumLaneElems; ++i) {
6957 // The mask element. This indexes into the input.
6958 int Idx = SVOp->getMaskElt(i+LaneStart);
6960 SVOps.push_back(DAG.getUNDEF(EltVT));
6964 // The input vector this mask element indexes into.
6965 int Input = Idx / NumElems;
6967 // Turn the index into an offset from the start of the input vector.
6968 Idx -= Input * NumElems;
6970 // Extract the vector element by hand.
6971 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6972 SVOp->getOperand(Input),
6973 DAG.getIntPtrConstant(Idx)));
6976 // Construct the output using a BUILD_VECTOR.
6977 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6979 } else if (InputUsed[0] < 0) {
6980 // No input vectors were used! The result is undefined.
6981 Output[l] = DAG.getUNDEF(NVT);
6983 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6984 (InputUsed[0] % 2) * NumLaneElems,
6986 // If only one input was used, use an undefined vector for the other.
6987 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6988 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6989 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6990 // At least one input vector was used. Create a new shuffle vector.
6991 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6997 // Concatenate the result back
6998 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7001 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7002 /// 4 elements, and match them with several different shuffle types.
7004 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7005 SDValue V1 = SVOp->getOperand(0);
7006 SDValue V2 = SVOp->getOperand(1);
7008 MVT VT = SVOp->getSimpleValueType(0);
7010 assert(VT.is128BitVector() && "Unsupported vector size");
7012 std::pair<int, int> Locs[4];
7013 int Mask1[] = { -1, -1, -1, -1 };
7014 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7018 for (unsigned i = 0; i != 4; ++i) {
7019 int Idx = PermMask[i];
7021 Locs[i] = std::make_pair(-1, -1);
7023 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7025 Locs[i] = std::make_pair(0, NumLo);
7029 Locs[i] = std::make_pair(1, NumHi);
7031 Mask1[2+NumHi] = Idx;
7037 if (NumLo <= 2 && NumHi <= 2) {
7038 // If no more than two elements come from either vector. This can be
7039 // implemented with two shuffles. First shuffle gather the elements.
7040 // The second shuffle, which takes the first shuffle as both of its
7041 // vector operands, put the elements into the right order.
7042 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7044 int Mask2[] = { -1, -1, -1, -1 };
7046 for (unsigned i = 0; i != 4; ++i)
7047 if (Locs[i].first != -1) {
7048 unsigned Idx = (i < 2) ? 0 : 4;
7049 Idx += Locs[i].first * 2 + Locs[i].second;
7053 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7056 if (NumLo == 3 || NumHi == 3) {
7057 // Otherwise, we must have three elements from one vector, call it X, and
7058 // one element from the other, call it Y. First, use a shufps to build an
7059 // intermediate vector with the one element from Y and the element from X
7060 // that will be in the same half in the final destination (the indexes don't
7061 // matter). Then, use a shufps to build the final vector, taking the half
7062 // containing the element from Y from the intermediate, and the other half
7065 // Normalize it so the 3 elements come from V1.
7066 CommuteVectorShuffleMask(PermMask, 4);
7070 // Find the element from V2.
7072 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7073 int Val = PermMask[HiIndex];
7080 Mask1[0] = PermMask[HiIndex];
7082 Mask1[2] = PermMask[HiIndex^1];
7084 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7087 Mask1[0] = PermMask[0];
7088 Mask1[1] = PermMask[1];
7089 Mask1[2] = HiIndex & 1 ? 6 : 4;
7090 Mask1[3] = HiIndex & 1 ? 4 : 6;
7091 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7094 Mask1[0] = HiIndex & 1 ? 2 : 0;
7095 Mask1[1] = HiIndex & 1 ? 0 : 2;
7096 Mask1[2] = PermMask[2];
7097 Mask1[3] = PermMask[3];
7102 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7105 // Break it into (shuffle shuffle_hi, shuffle_lo).
7106 int LoMask[] = { -1, -1, -1, -1 };
7107 int HiMask[] = { -1, -1, -1, -1 };
7109 int *MaskPtr = LoMask;
7110 unsigned MaskIdx = 0;
7113 for (unsigned i = 0; i != 4; ++i) {
7120 int Idx = PermMask[i];
7122 Locs[i] = std::make_pair(-1, -1);
7123 } else if (Idx < 4) {
7124 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7125 MaskPtr[LoIdx] = Idx;
7128 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7129 MaskPtr[HiIdx] = Idx;
7134 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7135 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7136 int MaskOps[] = { -1, -1, -1, -1 };
7137 for (unsigned i = 0; i != 4; ++i)
7138 if (Locs[i].first != -1)
7139 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7140 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7143 static bool MayFoldVectorLoad(SDValue V) {
7144 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7145 V = V.getOperand(0);
7147 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7148 V = V.getOperand(0);
7149 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7150 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7151 // BUILD_VECTOR (load), undef
7152 V = V.getOperand(0);
7154 return MayFoldLoad(V);
7158 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7159 MVT VT = Op.getSimpleValueType();
7161 // Canonizalize to v2f64.
7162 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7163 return DAG.getNode(ISD::BITCAST, dl, VT,
7164 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7169 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7171 SDValue V1 = Op.getOperand(0);
7172 SDValue V2 = Op.getOperand(1);
7173 MVT VT = Op.getSimpleValueType();
7175 assert(VT != MVT::v2i64 && "unsupported shuffle type");
7177 if (HasSSE2 && VT == MVT::v2f64)
7178 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7180 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7181 return DAG.getNode(ISD::BITCAST, dl, VT,
7182 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7183 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7184 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7188 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7189 SDValue V1 = Op.getOperand(0);
7190 SDValue V2 = Op.getOperand(1);
7191 MVT VT = Op.getSimpleValueType();
7193 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7194 "unsupported shuffle type");
7196 if (V2.getOpcode() == ISD::UNDEF)
7200 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7204 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7205 SDValue V1 = Op.getOperand(0);
7206 SDValue V2 = Op.getOperand(1);
7207 MVT VT = Op.getSimpleValueType();
7208 unsigned NumElems = VT.getVectorNumElements();
7210 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7211 // operand of these instructions is only memory, so check if there's a
7212 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7214 bool CanFoldLoad = false;
7216 // Trivial case, when V2 comes from a load.
7217 if (MayFoldVectorLoad(V2))
7220 // When V1 is a load, it can be folded later into a store in isel, example:
7221 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7223 // (MOVLPSmr addr:$src1, VR128:$src2)
7224 // So, recognize this potential and also use MOVLPS or MOVLPD
7225 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7228 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7230 if (HasSSE2 && NumElems == 2)
7231 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7234 // If we don't care about the second element, proceed to use movss.
7235 if (SVOp->getMaskElt(1) != -1)
7236 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7239 // movl and movlp will both match v2i64, but v2i64 is never matched by
7240 // movl earlier because we make it strict to avoid messing with the movlp load
7241 // folding logic (see the code above getMOVLP call). Match it here then,
7242 // this is horrible, but will stay like this until we move all shuffle
7243 // matching to x86 specific nodes. Note that for the 1st condition all
7244 // types are matched with movsd.
7246 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7247 // as to remove this logic from here, as much as possible
7248 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7249 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7250 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7253 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7255 // Invert the operand order and use SHUFPS to match it.
7256 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7257 getShuffleSHUFImmediate(SVOp), DAG);
7260 // Reduce a vector shuffle to zext.
7261 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7262 SelectionDAG &DAG) {
7263 // PMOVZX is only available from SSE41.
7264 if (!Subtarget->hasSSE41())
7267 MVT VT = Op.getSimpleValueType();
7269 // Only AVX2 support 256-bit vector integer extending.
7270 if (!Subtarget->hasInt256() && VT.is256BitVector())
7273 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7275 SDValue V1 = Op.getOperand(0);
7276 SDValue V2 = Op.getOperand(1);
7277 unsigned NumElems = VT.getVectorNumElements();
7279 // Extending is an unary operation and the element type of the source vector
7280 // won't be equal to or larger than i64.
7281 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7282 VT.getVectorElementType() == MVT::i64)
7285 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7286 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7287 while ((1U << Shift) < NumElems) {
7288 if (SVOp->getMaskElt(1U << Shift) == 1)
7291 // The maximal ratio is 8, i.e. from i8 to i64.
7296 // Check the shuffle mask.
7297 unsigned Mask = (1U << Shift) - 1;
7298 for (unsigned i = 0; i != NumElems; ++i) {
7299 int EltIdx = SVOp->getMaskElt(i);
7300 if ((i & Mask) != 0 && EltIdx != -1)
7302 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7306 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7307 MVT NeVT = MVT::getIntegerVT(NBits);
7308 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7310 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7313 // Simplify the operand as it's prepared to be fed into shuffle.
7314 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7315 if (V1.getOpcode() == ISD::BITCAST &&
7316 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7317 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7318 V1.getOperand(0).getOperand(0)
7319 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7320 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7321 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7322 ConstantSDNode *CIdx =
7323 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7324 // If it's foldable, i.e. normal load with single use, we will let code
7325 // selection to fold it. Otherwise, we will short the conversion sequence.
7326 if (CIdx && CIdx->getZExtValue() == 0 &&
7327 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7328 MVT FullVT = V.getSimpleValueType();
7329 MVT V1VT = V1.getSimpleValueType();
7330 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7331 // The "ext_vec_elt" node is wider than the result node.
7332 // In this case we should extract subvector from V.
7333 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7334 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7335 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7336 FullVT.getVectorNumElements()/Ratio);
7337 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7338 DAG.getIntPtrConstant(0));
7340 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7344 return DAG.getNode(ISD::BITCAST, DL, VT,
7345 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7349 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7350 SelectionDAG &DAG) {
7351 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7352 MVT VT = Op.getSimpleValueType();
7354 SDValue V1 = Op.getOperand(0);
7355 SDValue V2 = Op.getOperand(1);
7357 if (isZeroShuffle(SVOp))
7358 return getZeroVector(VT, Subtarget, DAG, dl);
7360 // Handle splat operations
7361 if (SVOp->isSplat()) {
7362 // Use vbroadcast whenever the splat comes from a foldable load
7363 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7364 if (Broadcast.getNode())
7368 // Check integer expanding shuffles.
7369 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7370 if (NewOp.getNode())
7373 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7375 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7376 VT == MVT::v16i16 || VT == MVT::v32i8) {
7377 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7378 if (NewOp.getNode())
7379 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7380 } else if ((VT == MVT::v4i32 ||
7381 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7382 // FIXME: Figure out a cleaner way to do this.
7383 // Try to make use of movq to zero out the top part.
7384 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7385 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7386 if (NewOp.getNode()) {
7387 MVT NewVT = NewOp.getSimpleValueType();
7388 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7389 NewVT, true, false))
7390 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7391 DAG, Subtarget, dl);
7393 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7394 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7395 if (NewOp.getNode()) {
7396 MVT NewVT = NewOp.getSimpleValueType();
7397 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7398 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7399 DAG, Subtarget, dl);
7407 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7408 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7409 SDValue V1 = Op.getOperand(0);
7410 SDValue V2 = Op.getOperand(1);
7411 MVT VT = Op.getSimpleValueType();
7413 unsigned NumElems = VT.getVectorNumElements();
7414 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7415 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7416 bool V1IsSplat = false;
7417 bool V2IsSplat = false;
7418 bool HasSSE2 = Subtarget->hasSSE2();
7419 bool HasFp256 = Subtarget->hasFp256();
7420 bool HasInt256 = Subtarget->hasInt256();
7421 MachineFunction &MF = DAG.getMachineFunction();
7422 bool OptForSize = MF.getFunction()->getAttributes().
7423 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7425 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7427 if (V1IsUndef && V2IsUndef)
7428 return DAG.getUNDEF(VT);
7430 // When we create a shuffle node we put the UNDEF node to second operand,
7431 // but in some cases the first operand may be transformed to UNDEF.
7432 // In this case we should just commute the node.
7434 return CommuteVectorShuffle(SVOp, DAG);
7436 // Vector shuffle lowering takes 3 steps:
7438 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7439 // narrowing and commutation of operands should be handled.
7440 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7442 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7443 // so the shuffle can be broken into other shuffles and the legalizer can
7444 // try the lowering again.
7446 // The general idea is that no vector_shuffle operation should be left to
7447 // be matched during isel, all of them must be converted to a target specific
7450 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7451 // narrowing and commutation of operands should be handled. The actual code
7452 // doesn't include all of those, work in progress...
7453 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7454 if (NewOp.getNode())
7457 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7459 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7460 // unpckh_undef). Only use pshufd if speed is more important than size.
7461 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7462 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7463 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7464 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7466 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7467 V2IsUndef && MayFoldVectorLoad(V1))
7468 return getMOVDDup(Op, dl, V1, DAG);
7470 if (isMOVHLPS_v_undef_Mask(M, VT))
7471 return getMOVHighToLow(Op, dl, DAG);
7473 // Use to match splats
7474 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7475 (VT == MVT::v2f64 || VT == MVT::v2i64))
7476 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7478 if (isPSHUFDMask(M, VT)) {
7479 // The actual implementation will match the mask in the if above and then
7480 // during isel it can match several different instructions, not only pshufd
7481 // as its name says, sad but true, emulate the behavior for now...
7482 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7483 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7485 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7487 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7488 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7490 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7491 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7494 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7498 if (isPALIGNRMask(M, VT, Subtarget))
7499 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7500 getShufflePALIGNRImmediate(SVOp),
7503 // Check if this can be converted into a logical shift.
7504 bool isLeft = false;
7507 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7508 if (isShift && ShVal.hasOneUse()) {
7509 // If the shifted value has multiple uses, it may be cheaper to use
7510 // v_set0 + movlhps or movhlps, etc.
7511 MVT EltVT = VT.getVectorElementType();
7512 ShAmt *= EltVT.getSizeInBits();
7513 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7516 if (isMOVLMask(M, VT)) {
7517 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7518 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7519 if (!isMOVLPMask(M, VT)) {
7520 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7521 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7523 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7524 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7528 // FIXME: fold these into legal mask.
7529 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7530 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7532 if (isMOVHLPSMask(M, VT))
7533 return getMOVHighToLow(Op, dl, DAG);
7535 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7536 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7538 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7539 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7541 if (isMOVLPMask(M, VT))
7542 return getMOVLP(Op, dl, DAG, HasSSE2);
7544 if (ShouldXformToMOVHLPS(M, VT) ||
7545 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7546 return CommuteVectorShuffle(SVOp, DAG);
7549 // No better options. Use a vshldq / vsrldq.
7550 MVT EltVT = VT.getVectorElementType();
7551 ShAmt *= EltVT.getSizeInBits();
7552 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7555 bool Commuted = false;
7556 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7557 // 1,1,1,1 -> v8i16 though.
7558 V1IsSplat = isSplatVector(V1.getNode());
7559 V2IsSplat = isSplatVector(V2.getNode());
7561 // Canonicalize the splat or undef, if present, to be on the RHS.
7562 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7563 CommuteVectorShuffleMask(M, NumElems);
7565 std::swap(V1IsSplat, V2IsSplat);
7569 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7570 // Shuffling low element of v1 into undef, just return v1.
7573 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7574 // the instruction selector will not match, so get a canonical MOVL with
7575 // swapped operands to undo the commute.
7576 return getMOVL(DAG, dl, VT, V2, V1);
7579 if (isUNPCKLMask(M, VT, HasInt256))
7580 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7582 if (isUNPCKHMask(M, VT, HasInt256))
7583 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7586 // Normalize mask so all entries that point to V2 points to its first
7587 // element then try to match unpck{h|l} again. If match, return a
7588 // new vector_shuffle with the corrected mask.p
7589 SmallVector<int, 8> NewMask(M.begin(), M.end());
7590 NormalizeMask(NewMask, NumElems);
7591 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7592 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7593 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7594 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7598 // Commute is back and try unpck* again.
7599 // FIXME: this seems wrong.
7600 CommuteVectorShuffleMask(M, NumElems);
7602 std::swap(V1IsSplat, V2IsSplat);
7604 if (isUNPCKLMask(M, VT, HasInt256))
7605 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7607 if (isUNPCKHMask(M, VT, HasInt256))
7608 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7611 // Normalize the node to match x86 shuffle ops if needed
7612 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7613 return CommuteVectorShuffle(SVOp, DAG);
7615 // The checks below are all present in isShuffleMaskLegal, but they are
7616 // inlined here right now to enable us to directly emit target specific
7617 // nodes, and remove one by one until they don't return Op anymore.
7619 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7620 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7621 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7622 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7625 if (isPSHUFHWMask(M, VT, HasInt256))
7626 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7627 getShufflePSHUFHWImmediate(SVOp),
7630 if (isPSHUFLWMask(M, VT, HasInt256))
7631 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7632 getShufflePSHUFLWImmediate(SVOp),
7635 if (isSHUFPMask(M, VT))
7636 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7637 getShuffleSHUFImmediate(SVOp), DAG);
7639 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7640 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7641 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7642 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7644 //===--------------------------------------------------------------------===//
7645 // Generate target specific nodes for 128 or 256-bit shuffles only
7646 // supported in the AVX instruction set.
7649 // Handle VMOVDDUPY permutations
7650 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7651 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7653 // Handle VPERMILPS/D* permutations
7654 if (isVPERMILPMask(M, VT)) {
7655 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7656 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7657 getShuffleSHUFImmediate(SVOp), DAG);
7658 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7659 getShuffleSHUFImmediate(SVOp), DAG);
7662 // Handle VPERM2F128/VPERM2I128 permutations
7663 if (isVPERM2X128Mask(M, VT, HasFp256))
7664 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7665 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7667 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7668 if (BlendOp.getNode())
7672 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7673 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7675 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7676 VT.is512BitVector()) {
7677 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7678 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7679 SmallVector<SDValue, 16> permclMask;
7680 for (unsigned i = 0; i != NumElems; ++i) {
7681 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7684 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7685 &permclMask[0], NumElems);
7687 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7688 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7689 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7690 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7691 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7694 //===--------------------------------------------------------------------===//
7695 // Since no target specific shuffle was selected for this generic one,
7696 // lower it into other known shuffles. FIXME: this isn't true yet, but
7697 // this is the plan.
7700 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7701 if (VT == MVT::v8i16) {
7702 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7703 if (NewOp.getNode())
7707 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7708 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7709 if (NewOp.getNode())
7713 if (VT == MVT::v16i8) {
7714 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7715 if (NewOp.getNode())
7719 if (VT == MVT::v32i8) {
7720 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7721 if (NewOp.getNode())
7725 // Handle all 128-bit wide vectors with 4 elements, and match them with
7726 // several different shuffle types.
7727 if (NumElems == 4 && VT.is128BitVector())
7728 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7730 // Handle general 256-bit shuffles
7731 if (VT.is256BitVector())
7732 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7737 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7738 MVT VT = Op.getSimpleValueType();
7741 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7744 if (VT.getSizeInBits() == 8) {
7745 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7746 Op.getOperand(0), Op.getOperand(1));
7747 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7748 DAG.getValueType(VT));
7749 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7752 if (VT.getSizeInBits() == 16) {
7753 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7754 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7756 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7757 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7758 DAG.getNode(ISD::BITCAST, dl,
7762 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7763 Op.getOperand(0), Op.getOperand(1));
7764 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7765 DAG.getValueType(VT));
7766 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7769 if (VT == MVT::f32) {
7770 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7771 // the result back to FR32 register. It's only worth matching if the
7772 // result has a single use which is a store or a bitcast to i32. And in
7773 // the case of a store, it's not worth it if the index is a constant 0,
7774 // because a MOVSSmr can be used instead, which is smaller and faster.
7775 if (!Op.hasOneUse())
7777 SDNode *User = *Op.getNode()->use_begin();
7778 if ((User->getOpcode() != ISD::STORE ||
7779 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7780 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7781 (User->getOpcode() != ISD::BITCAST ||
7782 User->getValueType(0) != MVT::i32))
7784 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7785 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7788 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7791 if (VT == MVT::i32 || VT == MVT::i64) {
7792 // ExtractPS/pextrq works with constant index.
7793 if (isa<ConstantSDNode>(Op.getOperand(1)))
7799 /// Extract one bit from mask vector, like v16i1 or v8i1.
7800 /// AVX-512 feature.
7802 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7803 SDValue Vec = Op.getOperand(0);
7805 MVT VecVT = Vec.getSimpleValueType();
7806 SDValue Idx = Op.getOperand(1);
7807 MVT EltVT = Op.getSimpleValueType();
7809 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7811 // variable index can't be handled in mask registers,
7812 // extend vector to VR512
7813 if (!isa<ConstantSDNode>(Idx)) {
7814 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7815 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7816 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7817 ExtVT.getVectorElementType(), Ext, Idx);
7818 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7821 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7822 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7823 unsigned MaxSift = rc->getSize()*8 - 1;
7824 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7825 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7826 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7827 DAG.getConstant(MaxSift, MVT::i8));
7828 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7829 DAG.getIntPtrConstant(0));
7833 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7834 SelectionDAG &DAG) const {
7836 SDValue Vec = Op.getOperand(0);
7837 MVT VecVT = Vec.getSimpleValueType();
7838 SDValue Idx = Op.getOperand(1);
7840 if (Op.getSimpleValueType() == MVT::i1)
7841 return ExtractBitFromMaskVector(Op, DAG);
7843 if (!isa<ConstantSDNode>(Idx)) {
7844 if (VecVT.is512BitVector() ||
7845 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7846 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7849 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7850 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7851 MaskEltVT.getSizeInBits());
7853 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7854 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7855 getZeroVector(MaskVT, Subtarget, DAG, dl),
7856 Idx, DAG.getConstant(0, getPointerTy()));
7857 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7858 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7859 Perm, DAG.getConstant(0, getPointerTy()));
7864 // If this is a 256-bit vector result, first extract the 128-bit vector and
7865 // then extract the element from the 128-bit vector.
7866 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7868 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7869 // Get the 128-bit vector.
7870 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7871 MVT EltVT = VecVT.getVectorElementType();
7873 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7875 //if (IdxVal >= NumElems/2)
7876 // IdxVal -= NumElems/2;
7877 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7878 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7879 DAG.getConstant(IdxVal, MVT::i32));
7882 assert(VecVT.is128BitVector() && "Unexpected vector length");
7884 if (Subtarget->hasSSE41()) {
7885 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7890 MVT VT = Op.getSimpleValueType();
7891 // TODO: handle v16i8.
7892 if (VT.getSizeInBits() == 16) {
7893 SDValue Vec = Op.getOperand(0);
7894 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7896 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7897 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7898 DAG.getNode(ISD::BITCAST, dl,
7901 // Transform it so it match pextrw which produces a 32-bit result.
7902 MVT EltVT = MVT::i32;
7903 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7904 Op.getOperand(0), Op.getOperand(1));
7905 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7906 DAG.getValueType(VT));
7907 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7910 if (VT.getSizeInBits() == 32) {
7911 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7915 // SHUFPS the element to the lowest double word, then movss.
7916 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7917 MVT VVT = Op.getOperand(0).getSimpleValueType();
7918 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7919 DAG.getUNDEF(VVT), Mask);
7920 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7921 DAG.getIntPtrConstant(0));
7924 if (VT.getSizeInBits() == 64) {
7925 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7926 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7927 // to match extract_elt for f64.
7928 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7932 // UNPCKHPD the element to the lowest double word, then movsd.
7933 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7934 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7935 int Mask[2] = { 1, -1 };
7936 MVT VVT = Op.getOperand(0).getSimpleValueType();
7937 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7938 DAG.getUNDEF(VVT), Mask);
7939 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7940 DAG.getIntPtrConstant(0));
7946 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7947 MVT VT = Op.getSimpleValueType();
7948 MVT EltVT = VT.getVectorElementType();
7951 SDValue N0 = Op.getOperand(0);
7952 SDValue N1 = Op.getOperand(1);
7953 SDValue N2 = Op.getOperand(2);
7955 if (!VT.is128BitVector())
7958 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7959 isa<ConstantSDNode>(N2)) {
7961 if (VT == MVT::v8i16)
7962 Opc = X86ISD::PINSRW;
7963 else if (VT == MVT::v16i8)
7964 Opc = X86ISD::PINSRB;
7966 Opc = X86ISD::PINSRB;
7968 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7970 if (N1.getValueType() != MVT::i32)
7971 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7972 if (N2.getValueType() != MVT::i32)
7973 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7974 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7977 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7978 // Bits [7:6] of the constant are the source select. This will always be
7979 // zero here. The DAG Combiner may combine an extract_elt index into these
7980 // bits. For example (insert (extract, 3), 2) could be matched by putting
7981 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7982 // Bits [5:4] of the constant are the destination select. This is the
7983 // value of the incoming immediate.
7984 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7985 // combine either bitwise AND or insert of float 0.0 to set these bits.
7986 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7987 // Create this as a scalar to vector..
7988 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7989 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7992 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7993 // PINSR* works with constant index.
7999 /// Insert one bit to mask vector, like v16i1 or v8i1.
8000 /// AVX-512 feature.
8002 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8004 SDValue Vec = Op.getOperand(0);
8005 SDValue Elt = Op.getOperand(1);
8006 SDValue Idx = Op.getOperand(2);
8007 MVT VecVT = Vec.getSimpleValueType();
8009 if (!isa<ConstantSDNode>(Idx)) {
8010 // Non constant index. Extend source and destination,
8011 // insert element and then truncate the result.
8012 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8013 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8014 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8015 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8016 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8017 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8020 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8021 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8022 if (Vec.getOpcode() == ISD::UNDEF)
8023 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8024 DAG.getConstant(IdxVal, MVT::i8));
8025 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8026 unsigned MaxSift = rc->getSize()*8 - 1;
8027 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8028 DAG.getConstant(MaxSift, MVT::i8));
8029 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8030 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8031 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8034 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8035 MVT VT = Op.getSimpleValueType();
8036 MVT EltVT = VT.getVectorElementType();
8038 if (EltVT == MVT::i1)
8039 return InsertBitToMaskVector(Op, DAG);
8042 SDValue N0 = Op.getOperand(0);
8043 SDValue N1 = Op.getOperand(1);
8044 SDValue N2 = Op.getOperand(2);
8046 // If this is a 256-bit vector result, first extract the 128-bit vector,
8047 // insert the element into the extracted half and then place it back.
8048 if (VT.is256BitVector() || VT.is512BitVector()) {
8049 if (!isa<ConstantSDNode>(N2))
8052 // Get the desired 128-bit vector half.
8053 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8054 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8056 // Insert the element into the desired half.
8057 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8058 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8060 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8061 DAG.getConstant(IdxIn128, MVT::i32));
8063 // Insert the changed part back to the 256-bit vector
8064 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8067 if (Subtarget->hasSSE41())
8068 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8070 if (EltVT == MVT::i8)
8073 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8074 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8075 // as its second argument.
8076 if (N1.getValueType() != MVT::i32)
8077 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8078 if (N2.getValueType() != MVT::i32)
8079 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8080 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8085 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8087 MVT OpVT = Op.getSimpleValueType();
8089 // If this is a 256-bit vector result, first insert into a 128-bit
8090 // vector and then insert into the 256-bit vector.
8091 if (!OpVT.is128BitVector()) {
8092 // Insert into a 128-bit vector.
8093 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8094 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8095 OpVT.getVectorNumElements() / SizeFactor);
8097 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8099 // Insert the 128-bit vector.
8100 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8103 if (OpVT == MVT::v1i64 &&
8104 Op.getOperand(0).getValueType() == MVT::i64)
8105 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8107 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8108 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8109 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8110 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8113 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8114 // a simple subregister reference or explicit instructions to grab
8115 // upper bits of a vector.
8116 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8117 SelectionDAG &DAG) {
8119 SDValue In = Op.getOperand(0);
8120 SDValue Idx = Op.getOperand(1);
8121 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8122 MVT ResVT = Op.getSimpleValueType();
8123 MVT InVT = In.getSimpleValueType();
8125 if (Subtarget->hasFp256()) {
8126 if (ResVT.is128BitVector() &&
8127 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8128 isa<ConstantSDNode>(Idx)) {
8129 return Extract128BitVector(In, IdxVal, DAG, dl);
8131 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8132 isa<ConstantSDNode>(Idx)) {
8133 return Extract256BitVector(In, IdxVal, DAG, dl);
8139 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8140 // simple superregister reference or explicit instructions to insert
8141 // the upper bits of a vector.
8142 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8143 SelectionDAG &DAG) {
8144 if (Subtarget->hasFp256()) {
8145 SDLoc dl(Op.getNode());
8146 SDValue Vec = Op.getNode()->getOperand(0);
8147 SDValue SubVec = Op.getNode()->getOperand(1);
8148 SDValue Idx = Op.getNode()->getOperand(2);
8150 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8151 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8152 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8153 isa<ConstantSDNode>(Idx)) {
8154 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8155 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8158 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8159 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8160 isa<ConstantSDNode>(Idx)) {
8161 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8162 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8168 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8169 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8170 // one of the above mentioned nodes. It has to be wrapped because otherwise
8171 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8172 // be used to form addressing mode. These wrapped nodes will be selected
8175 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8176 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8178 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8180 unsigned char OpFlag = 0;
8181 unsigned WrapperKind = X86ISD::Wrapper;
8182 CodeModel::Model M = getTargetMachine().getCodeModel();
8184 if (Subtarget->isPICStyleRIPRel() &&
8185 (M == CodeModel::Small || M == CodeModel::Kernel))
8186 WrapperKind = X86ISD::WrapperRIP;
8187 else if (Subtarget->isPICStyleGOT())
8188 OpFlag = X86II::MO_GOTOFF;
8189 else if (Subtarget->isPICStyleStubPIC())
8190 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8192 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8194 CP->getOffset(), OpFlag);
8196 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8197 // With PIC, the address is actually $g + Offset.
8199 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8200 DAG.getNode(X86ISD::GlobalBaseReg,
8201 SDLoc(), getPointerTy()),
8208 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8209 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8211 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8213 unsigned char OpFlag = 0;
8214 unsigned WrapperKind = X86ISD::Wrapper;
8215 CodeModel::Model M = getTargetMachine().getCodeModel();
8217 if (Subtarget->isPICStyleRIPRel() &&
8218 (M == CodeModel::Small || M == CodeModel::Kernel))
8219 WrapperKind = X86ISD::WrapperRIP;
8220 else if (Subtarget->isPICStyleGOT())
8221 OpFlag = X86II::MO_GOTOFF;
8222 else if (Subtarget->isPICStyleStubPIC())
8223 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8225 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8228 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8230 // With PIC, the address is actually $g + Offset.
8232 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8233 DAG.getNode(X86ISD::GlobalBaseReg,
8234 SDLoc(), getPointerTy()),
8241 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8242 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8244 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8246 unsigned char OpFlag = 0;
8247 unsigned WrapperKind = X86ISD::Wrapper;
8248 CodeModel::Model M = getTargetMachine().getCodeModel();
8250 if (Subtarget->isPICStyleRIPRel() &&
8251 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8252 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8253 OpFlag = X86II::MO_GOTPCREL;
8254 WrapperKind = X86ISD::WrapperRIP;
8255 } else if (Subtarget->isPICStyleGOT()) {
8256 OpFlag = X86II::MO_GOT;
8257 } else if (Subtarget->isPICStyleStubPIC()) {
8258 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8259 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8260 OpFlag = X86II::MO_DARWIN_NONLAZY;
8263 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8266 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8268 // With PIC, the address is actually $g + Offset.
8269 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8270 !Subtarget->is64Bit()) {
8271 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8272 DAG.getNode(X86ISD::GlobalBaseReg,
8273 SDLoc(), getPointerTy()),
8277 // For symbols that require a load from a stub to get the address, emit the
8279 if (isGlobalStubReference(OpFlag))
8280 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8281 MachinePointerInfo::getGOT(), false, false, false, 0);
8287 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8288 // Create the TargetBlockAddressAddress node.
8289 unsigned char OpFlags =
8290 Subtarget->ClassifyBlockAddressReference();
8291 CodeModel::Model M = getTargetMachine().getCodeModel();
8292 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8293 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8295 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8298 if (Subtarget->isPICStyleRIPRel() &&
8299 (M == CodeModel::Small || M == CodeModel::Kernel))
8300 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8302 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8304 // With PIC, the address is actually $g + Offset.
8305 if (isGlobalRelativeToPICBase(OpFlags)) {
8306 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8307 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8315 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8316 int64_t Offset, SelectionDAG &DAG) const {
8317 // Create the TargetGlobalAddress node, folding in the constant
8318 // offset if it is legal.
8319 unsigned char OpFlags =
8320 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8321 CodeModel::Model M = getTargetMachine().getCodeModel();
8323 if (OpFlags == X86II::MO_NO_FLAG &&
8324 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8325 // A direct static reference to a global.
8326 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8329 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8332 if (Subtarget->isPICStyleRIPRel() &&
8333 (M == CodeModel::Small || M == CodeModel::Kernel))
8334 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8336 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8338 // With PIC, the address is actually $g + Offset.
8339 if (isGlobalRelativeToPICBase(OpFlags)) {
8340 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8341 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8345 // For globals that require a load from a stub to get the address, emit the
8347 if (isGlobalStubReference(OpFlags))
8348 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8349 MachinePointerInfo::getGOT(), false, false, false, 0);
8351 // If there was a non-zero offset that we didn't fold, create an explicit
8354 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8355 DAG.getConstant(Offset, getPointerTy()));
8361 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8362 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8363 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8364 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8368 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8369 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8370 unsigned char OperandFlags, bool LocalDynamic = false) {
8371 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8372 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8374 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8375 GA->getValueType(0),
8379 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8383 SDValue Ops[] = { Chain, TGA, *InFlag };
8384 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8386 SDValue Ops[] = { Chain, TGA };
8387 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8390 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8391 MFI->setAdjustsStack(true);
8393 SDValue Flag = Chain.getValue(1);
8394 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8397 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8399 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8402 SDLoc dl(GA); // ? function entry point might be better
8403 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8404 DAG.getNode(X86ISD::GlobalBaseReg,
8405 SDLoc(), PtrVT), InFlag);
8406 InFlag = Chain.getValue(1);
8408 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8411 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8413 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8415 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8416 X86::RAX, X86II::MO_TLSGD);
8419 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8425 // Get the start address of the TLS block for this module.
8426 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8427 .getInfo<X86MachineFunctionInfo>();
8428 MFI->incNumLocalDynamicTLSAccesses();
8432 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8433 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8436 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8437 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8438 InFlag = Chain.getValue(1);
8439 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8440 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8443 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8447 unsigned char OperandFlags = X86II::MO_DTPOFF;
8448 unsigned WrapperKind = X86ISD::Wrapper;
8449 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8450 GA->getValueType(0),
8451 GA->getOffset(), OperandFlags);
8452 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8454 // Add x@dtpoff with the base.
8455 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8458 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8459 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8460 const EVT PtrVT, TLSModel::Model model,
8461 bool is64Bit, bool isPIC) {
8464 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8465 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8466 is64Bit ? 257 : 256));
8468 SDValue ThreadPointer =
8469 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8470 MachinePointerInfo(Ptr), false, false, false, 0);
8472 unsigned char OperandFlags = 0;
8473 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8475 unsigned WrapperKind = X86ISD::Wrapper;
8476 if (model == TLSModel::LocalExec) {
8477 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8478 } else if (model == TLSModel::InitialExec) {
8480 OperandFlags = X86II::MO_GOTTPOFF;
8481 WrapperKind = X86ISD::WrapperRIP;
8483 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8486 llvm_unreachable("Unexpected model");
8489 // emit "addl x@ntpoff,%eax" (local exec)
8490 // or "addl x@indntpoff,%eax" (initial exec)
8491 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8493 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8494 GA->getOffset(), OperandFlags);
8495 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8497 if (model == TLSModel::InitialExec) {
8498 if (isPIC && !is64Bit) {
8499 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8500 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8504 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8505 MachinePointerInfo::getGOT(), false, false, false, 0);
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, PtrVT, ThreadPointer, Offset);
8514 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8516 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8517 const GlobalValue *GV = GA->getGlobal();
8519 if (Subtarget->isTargetELF()) {
8520 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8523 case TLSModel::GeneralDynamic:
8524 if (Subtarget->is64Bit())
8525 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8526 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8527 case TLSModel::LocalDynamic:
8528 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8529 Subtarget->is64Bit());
8530 case TLSModel::InitialExec:
8531 case TLSModel::LocalExec:
8532 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8533 Subtarget->is64Bit(),
8534 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8536 llvm_unreachable("Unknown TLS model.");
8539 if (Subtarget->isTargetDarwin()) {
8540 // Darwin only has one model of TLS. Lower to that.
8541 unsigned char OpFlag = 0;
8542 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8543 X86ISD::WrapperRIP : X86ISD::Wrapper;
8545 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8547 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8548 !Subtarget->is64Bit();
8550 OpFlag = X86II::MO_TLVP_PIC_BASE;
8552 OpFlag = X86II::MO_TLVP;
8554 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8555 GA->getValueType(0),
8556 GA->getOffset(), OpFlag);
8557 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8559 // With PIC32, the address is actually $g + Offset.
8561 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8562 DAG.getNode(X86ISD::GlobalBaseReg,
8563 SDLoc(), getPointerTy()),
8566 // Lowering the machine isd will make sure everything is in the right
8568 SDValue Chain = DAG.getEntryNode();
8569 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8570 SDValue Args[] = { Chain, Offset };
8571 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8573 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8574 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8575 MFI->setAdjustsStack(true);
8577 // And our return value (tls address) is in the standard call return value
8579 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8580 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8584 if (Subtarget->isTargetKnownWindowsMSVC() ||
8585 Subtarget->isTargetWindowsGNU()) {
8586 // Just use the implicit TLS architecture
8587 // Need to generate someting similar to:
8588 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8590 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8591 // mov rcx, qword [rdx+rcx*8]
8592 // mov eax, .tls$:tlsvar
8593 // [rax+rcx] contains the address
8594 // Windows 64bit: gs:0x58
8595 // Windows 32bit: fs:__tls_array
8597 // If GV is an alias then use the aliasee for determining
8598 // thread-localness.
8599 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8600 GV = GA->getAliasedGlobal();
8602 SDValue Chain = DAG.getEntryNode();
8604 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8605 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8606 // use its literal value of 0x2C.
8607 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8608 ? Type::getInt8PtrTy(*DAG.getContext(),
8610 : Type::getInt32PtrTy(*DAG.getContext(),
8614 Subtarget->is64Bit()
8615 ? DAG.getIntPtrConstant(0x58)
8616 : (Subtarget->isTargetWindowsGNU()
8617 ? DAG.getIntPtrConstant(0x2C)
8618 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8620 SDValue ThreadPointer =
8621 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8622 MachinePointerInfo(Ptr), false, false, false, 0);
8624 // Load the _tls_index variable
8625 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8626 if (Subtarget->is64Bit())
8627 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8628 IDX, MachinePointerInfo(), MVT::i32,
8631 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8632 false, false, false, 0);
8634 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8636 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8638 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8639 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8640 false, false, false, 0);
8642 // Get the offset of start of .tls section
8643 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8644 GA->getValueType(0),
8645 GA->getOffset(), X86II::MO_SECREL);
8646 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8648 // The address of the thread local variable is the add of the thread
8649 // pointer with the offset of the variable.
8650 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8653 llvm_unreachable("TLS not implemented for this target.");
8656 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8657 /// and take a 2 x i32 value to shift plus a shift amount.
8658 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8659 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8660 MVT VT = Op.getSimpleValueType();
8661 unsigned VTBits = VT.getSizeInBits();
8663 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8664 SDValue ShOpLo = Op.getOperand(0);
8665 SDValue ShOpHi = Op.getOperand(1);
8666 SDValue ShAmt = Op.getOperand(2);
8667 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8668 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8670 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8671 DAG.getConstant(VTBits - 1, MVT::i8));
8672 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8673 DAG.getConstant(VTBits - 1, MVT::i8))
8674 : DAG.getConstant(0, VT);
8677 if (Op.getOpcode() == ISD::SHL_PARTS) {
8678 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8679 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8681 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8682 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8685 // If the shift amount is larger or equal than the width of a part we can't
8686 // rely on the results of shld/shrd. Insert a test and select the appropriate
8687 // values for large shift amounts.
8688 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8689 DAG.getConstant(VTBits, MVT::i8));
8690 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8691 AndNode, DAG.getConstant(0, MVT::i8));
8694 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8695 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8696 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8698 if (Op.getOpcode() == ISD::SHL_PARTS) {
8699 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8700 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8702 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8703 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8706 SDValue Ops[2] = { Lo, Hi };
8707 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8710 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8711 SelectionDAG &DAG) const {
8712 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8714 if (SrcVT.isVector())
8717 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8718 "Unknown SINT_TO_FP to lower!");
8720 // These are really Legal; return the operand so the caller accepts it as
8722 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8724 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8725 Subtarget->is64Bit()) {
8730 unsigned Size = SrcVT.getSizeInBits()/8;
8731 MachineFunction &MF = DAG.getMachineFunction();
8732 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8733 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8734 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8736 MachinePointerInfo::getFixedStack(SSFI),
8738 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8741 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8743 SelectionDAG &DAG) const {
8747 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8749 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8751 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8753 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8755 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8756 MachineMemOperand *MMO;
8758 int SSFI = FI->getIndex();
8760 DAG.getMachineFunction()
8761 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8762 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8764 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8765 StackSlot = StackSlot.getOperand(1);
8767 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8768 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8770 Tys, Ops, array_lengthof(Ops),
8774 Chain = Result.getValue(1);
8775 SDValue InFlag = Result.getValue(2);
8777 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8778 // shouldn't be necessary except that RFP cannot be live across
8779 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8780 MachineFunction &MF = DAG.getMachineFunction();
8781 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8782 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8783 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8784 Tys = DAG.getVTList(MVT::Other);
8786 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8788 MachineMemOperand *MMO =
8789 DAG.getMachineFunction()
8790 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8791 MachineMemOperand::MOStore, SSFISize, SSFISize);
8793 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8794 Ops, array_lengthof(Ops),
8795 Op.getValueType(), MMO);
8796 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8797 MachinePointerInfo::getFixedStack(SSFI),
8798 false, false, false, 0);
8804 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8805 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8806 SelectionDAG &DAG) const {
8807 // This algorithm is not obvious. Here it is what we're trying to output:
8810 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8811 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8815 pshufd $0x4e, %xmm0, %xmm1
8821 LLVMContext *Context = DAG.getContext();
8823 // Build some magic constants.
8824 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8825 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8826 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8828 SmallVector<Constant*,2> CV1;
8830 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8831 APInt(64, 0x4330000000000000ULL))));
8833 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8834 APInt(64, 0x4530000000000000ULL))));
8835 Constant *C1 = ConstantVector::get(CV1);
8836 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8838 // Load the 64-bit value into an XMM register.
8839 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8841 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8842 MachinePointerInfo::getConstantPool(),
8843 false, false, false, 16);
8844 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8845 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8848 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8849 MachinePointerInfo::getConstantPool(),
8850 false, false, false, 16);
8851 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8852 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8855 if (Subtarget->hasSSE3()) {
8856 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8857 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8859 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8860 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8862 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8863 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8867 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8868 DAG.getIntPtrConstant(0));
8871 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8872 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8873 SelectionDAG &DAG) const {
8875 // FP constant to bias correct the final result.
8876 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8879 // Load the 32-bit value into an XMM register.
8880 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8883 // Zero out the upper parts of the register.
8884 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8886 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8887 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8888 DAG.getIntPtrConstant(0));
8890 // Or the load with the bias.
8891 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8892 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8893 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8895 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8896 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8897 MVT::v2f64, Bias)));
8898 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8899 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8900 DAG.getIntPtrConstant(0));
8902 // Subtract the bias.
8903 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8905 // Handle final rounding.
8906 EVT DestVT = Op.getValueType();
8908 if (DestVT.bitsLT(MVT::f64))
8909 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8910 DAG.getIntPtrConstant(0));
8911 if (DestVT.bitsGT(MVT::f64))
8912 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8914 // Handle final rounding.
8918 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8919 SelectionDAG &DAG) const {
8920 SDValue N0 = Op.getOperand(0);
8921 MVT SVT = N0.getSimpleValueType();
8924 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8925 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8926 "Custom UINT_TO_FP is not supported!");
8928 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8929 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8930 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8933 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8934 SelectionDAG &DAG) const {
8935 SDValue N0 = Op.getOperand(0);
8938 if (Op.getValueType().isVector())
8939 return lowerUINT_TO_FP_vec(Op, DAG);
8941 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8942 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8943 // the optimization here.
8944 if (DAG.SignBitIsZero(N0))
8945 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8947 MVT SrcVT = N0.getSimpleValueType();
8948 MVT DstVT = Op.getSimpleValueType();
8949 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8950 return LowerUINT_TO_FP_i64(Op, DAG);
8951 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8952 return LowerUINT_TO_FP_i32(Op, DAG);
8953 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8956 // Make a 64-bit buffer, and use it to build an FILD.
8957 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8958 if (SrcVT == MVT::i32) {
8959 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8960 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8961 getPointerTy(), StackSlot, WordOff);
8962 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8963 StackSlot, MachinePointerInfo(),
8965 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8966 OffsetSlot, MachinePointerInfo(),
8968 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8972 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8973 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8974 StackSlot, MachinePointerInfo(),
8976 // For i64 source, we need to add the appropriate power of 2 if the input
8977 // was negative. This is the same as the optimization in
8978 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8979 // we must be careful to do the computation in x87 extended precision, not
8980 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8981 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8982 MachineMemOperand *MMO =
8983 DAG.getMachineFunction()
8984 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8985 MachineMemOperand::MOLoad, 8, 8);
8987 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8988 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8989 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8990 array_lengthof(Ops), MVT::i64, MMO);
8992 APInt FF(32, 0x5F800000ULL);
8994 // Check whether the sign bit is set.
8995 SDValue SignSet = DAG.getSetCC(dl,
8996 getSetCCResultType(*DAG.getContext(), MVT::i64),
8997 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9000 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9001 SDValue FudgePtr = DAG.getConstantPool(
9002 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9005 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9006 SDValue Zero = DAG.getIntPtrConstant(0);
9007 SDValue Four = DAG.getIntPtrConstant(4);
9008 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9010 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9012 // Load the value out, extending it from f32 to f80.
9013 // FIXME: Avoid the extend by constructing the right constant pool?
9014 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9015 FudgePtr, MachinePointerInfo::getConstantPool(),
9016 MVT::f32, false, false, 4);
9017 // Extend everything to 80 bits to force it to be done on x87.
9018 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9019 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9022 std::pair<SDValue,SDValue>
9023 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9024 bool IsSigned, bool IsReplace) const {
9027 EVT DstTy = Op.getValueType();
9029 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9030 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9034 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9035 DstTy.getSimpleVT() >= MVT::i16 &&
9036 "Unknown FP_TO_INT to lower!");
9038 // These are really Legal.
9039 if (DstTy == MVT::i32 &&
9040 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9041 return std::make_pair(SDValue(), SDValue());
9042 if (Subtarget->is64Bit() &&
9043 DstTy == MVT::i64 &&
9044 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9045 return std::make_pair(SDValue(), SDValue());
9047 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9048 // stack slot, or into the FTOL runtime function.
9049 MachineFunction &MF = DAG.getMachineFunction();
9050 unsigned MemSize = DstTy.getSizeInBits()/8;
9051 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9052 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9055 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9056 Opc = X86ISD::WIN_FTOL;
9058 switch (DstTy.getSimpleVT().SimpleTy) {
9059 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9060 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9061 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9062 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9065 SDValue Chain = DAG.getEntryNode();
9066 SDValue Value = Op.getOperand(0);
9067 EVT TheVT = Op.getOperand(0).getValueType();
9068 // FIXME This causes a redundant load/store if the SSE-class value is already
9069 // in memory, such as if it is on the callstack.
9070 if (isScalarFPTypeInSSEReg(TheVT)) {
9071 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9072 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9073 MachinePointerInfo::getFixedStack(SSFI),
9075 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9077 Chain, StackSlot, DAG.getValueType(TheVT)
9080 MachineMemOperand *MMO =
9081 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9082 MachineMemOperand::MOLoad, MemSize, MemSize);
9083 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9084 array_lengthof(Ops), DstTy, MMO);
9085 Chain = Value.getValue(1);
9086 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9087 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9090 MachineMemOperand *MMO =
9091 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9092 MachineMemOperand::MOStore, MemSize, MemSize);
9094 if (Opc != X86ISD::WIN_FTOL) {
9095 // Build the FP_TO_INT*_IN_MEM
9096 SDValue Ops[] = { Chain, Value, StackSlot };
9097 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9098 Ops, array_lengthof(Ops), DstTy,
9100 return std::make_pair(FIST, StackSlot);
9102 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9103 DAG.getVTList(MVT::Other, MVT::Glue),
9105 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9106 MVT::i32, ftol.getValue(1));
9107 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9108 MVT::i32, eax.getValue(2));
9109 SDValue Ops[] = { eax, edx };
9110 SDValue pair = IsReplace
9111 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
9112 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9113 return std::make_pair(pair, SDValue());
9117 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9118 const X86Subtarget *Subtarget) {
9119 MVT VT = Op->getSimpleValueType(0);
9120 SDValue In = Op->getOperand(0);
9121 MVT InVT = In.getSimpleValueType();
9124 // Optimize vectors in AVX mode:
9127 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9128 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9129 // Concat upper and lower parts.
9132 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9133 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9134 // Concat upper and lower parts.
9137 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9138 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9139 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9142 if (Subtarget->hasInt256())
9143 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9145 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9146 SDValue Undef = DAG.getUNDEF(InVT);
9147 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9148 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9149 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9151 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9152 VT.getVectorNumElements()/2);
9154 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9155 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9157 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9160 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9161 SelectionDAG &DAG) {
9162 MVT VT = Op->getSimpleValueType(0);
9163 SDValue In = Op->getOperand(0);
9164 MVT InVT = In.getSimpleValueType();
9166 unsigned int NumElts = VT.getVectorNumElements();
9167 if (NumElts != 8 && NumElts != 16)
9170 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9171 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9173 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9174 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9175 // Now we have only mask extension
9176 assert(InVT.getVectorElementType() == MVT::i1);
9177 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9178 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9179 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9180 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9181 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9182 MachinePointerInfo::getConstantPool(),
9183 false, false, false, Alignment);
9185 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9186 if (VT.is512BitVector())
9188 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9191 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9192 SelectionDAG &DAG) {
9193 if (Subtarget->hasFp256()) {
9194 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9202 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9203 SelectionDAG &DAG) {
9205 MVT VT = Op.getSimpleValueType();
9206 SDValue In = Op.getOperand(0);
9207 MVT SVT = In.getSimpleValueType();
9209 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9210 return LowerZERO_EXTEND_AVX512(Op, DAG);
9212 if (Subtarget->hasFp256()) {
9213 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9218 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9219 VT.getVectorNumElements() != SVT.getVectorNumElements());
9223 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9225 MVT VT = Op.getSimpleValueType();
9226 SDValue In = Op.getOperand(0);
9227 MVT InVT = In.getSimpleValueType();
9229 if (VT == MVT::i1) {
9230 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9231 "Invalid scalar TRUNCATE operation");
9232 if (InVT == MVT::i32)
9234 if (InVT.getSizeInBits() == 64)
9235 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9236 else if (InVT.getSizeInBits() < 32)
9237 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9238 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9240 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9241 "Invalid TRUNCATE operation");
9243 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9244 if (VT.getVectorElementType().getSizeInBits() >=8)
9245 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9247 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9248 unsigned NumElts = InVT.getVectorNumElements();
9249 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9250 if (InVT.getSizeInBits() < 512) {
9251 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9252 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9256 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9257 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9258 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9259 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9260 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9261 MachinePointerInfo::getConstantPool(),
9262 false, false, false, Alignment);
9263 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9264 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9265 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9268 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9269 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9270 if (Subtarget->hasInt256()) {
9271 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9272 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9273 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9275 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9276 DAG.getIntPtrConstant(0));
9279 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9280 DAG.getIntPtrConstant(0));
9281 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9282 DAG.getIntPtrConstant(2));
9283 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9284 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9285 static const int ShufMask[] = {0, 2, 4, 6};
9286 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9289 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9290 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9291 if (Subtarget->hasInt256()) {
9292 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9294 SmallVector<SDValue,32> pshufbMask;
9295 for (unsigned i = 0; i < 2; ++i) {
9296 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9297 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9298 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9299 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9300 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9301 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9302 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9303 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9304 for (unsigned j = 0; j < 8; ++j)
9305 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9307 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9308 &pshufbMask[0], 32);
9309 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9310 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9312 static const int ShufMask[] = {0, 2, -1, -1};
9313 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9315 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9316 DAG.getIntPtrConstant(0));
9317 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9320 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9321 DAG.getIntPtrConstant(0));
9323 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9324 DAG.getIntPtrConstant(4));
9326 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9327 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9330 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9331 -1, -1, -1, -1, -1, -1, -1, -1};
9333 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9334 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9335 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9337 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9338 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9340 // The MOVLHPS Mask:
9341 static const int ShufMask2[] = {0, 1, 4, 5};
9342 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9343 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9346 // Handle truncation of V256 to V128 using shuffles.
9347 if (!VT.is128BitVector() || !InVT.is256BitVector())
9350 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9352 unsigned NumElems = VT.getVectorNumElements();
9353 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9355 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9356 // Prepare truncation shuffle mask
9357 for (unsigned i = 0; i != NumElems; ++i)
9359 SDValue V = DAG.getVectorShuffle(NVT, DL,
9360 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9361 DAG.getUNDEF(NVT), &MaskVec[0]);
9362 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9363 DAG.getIntPtrConstant(0));
9366 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9367 SelectionDAG &DAG) const {
9368 assert(!Op.getSimpleValueType().isVector());
9370 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9371 /*IsSigned=*/ true, /*IsReplace=*/ false);
9372 SDValue FIST = Vals.first, StackSlot = Vals.second;
9373 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9374 if (FIST.getNode() == 0) return Op;
9376 if (StackSlot.getNode())
9378 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9379 FIST, StackSlot, MachinePointerInfo(),
9380 false, false, false, 0);
9382 // The node is the result.
9386 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9387 SelectionDAG &DAG) const {
9388 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9389 /*IsSigned=*/ false, /*IsReplace=*/ false);
9390 SDValue FIST = Vals.first, StackSlot = Vals.second;
9391 assert(FIST.getNode() && "Unexpected failure");
9393 if (StackSlot.getNode())
9395 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9396 FIST, StackSlot, MachinePointerInfo(),
9397 false, false, false, 0);
9399 // The node is the result.
9403 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9405 MVT VT = Op.getSimpleValueType();
9406 SDValue In = Op.getOperand(0);
9407 MVT SVT = In.getSimpleValueType();
9409 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9411 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9412 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9413 In, DAG.getUNDEF(SVT)));
9416 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9417 LLVMContext *Context = DAG.getContext();
9419 MVT VT = Op.getSimpleValueType();
9421 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9422 if (VT.isVector()) {
9423 EltVT = VT.getVectorElementType();
9424 NumElts = VT.getVectorNumElements();
9427 if (EltVT == MVT::f64)
9428 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9429 APInt(64, ~(1ULL << 63))));
9431 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9432 APInt(32, ~(1U << 31))));
9433 C = ConstantVector::getSplat(NumElts, C);
9434 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9435 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9436 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9437 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9438 MachinePointerInfo::getConstantPool(),
9439 false, false, false, Alignment);
9440 if (VT.isVector()) {
9441 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9442 return DAG.getNode(ISD::BITCAST, dl, VT,
9443 DAG.getNode(ISD::AND, dl, ANDVT,
9444 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9446 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9448 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9451 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9452 LLVMContext *Context = DAG.getContext();
9454 MVT VT = Op.getSimpleValueType();
9456 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9457 if (VT.isVector()) {
9458 EltVT = VT.getVectorElementType();
9459 NumElts = VT.getVectorNumElements();
9462 if (EltVT == MVT::f64)
9463 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9464 APInt(64, 1ULL << 63)));
9466 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9467 APInt(32, 1U << 31)));
9468 C = ConstantVector::getSplat(NumElts, C);
9469 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9470 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9471 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9472 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9473 MachinePointerInfo::getConstantPool(),
9474 false, false, false, Alignment);
9475 if (VT.isVector()) {
9476 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9477 return DAG.getNode(ISD::BITCAST, dl, VT,
9478 DAG.getNode(ISD::XOR, dl, XORVT,
9479 DAG.getNode(ISD::BITCAST, dl, XORVT,
9481 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9484 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9487 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9488 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9489 LLVMContext *Context = DAG.getContext();
9490 SDValue Op0 = Op.getOperand(0);
9491 SDValue Op1 = Op.getOperand(1);
9493 MVT VT = Op.getSimpleValueType();
9494 MVT SrcVT = Op1.getSimpleValueType();
9496 // If second operand is smaller, extend it first.
9497 if (SrcVT.bitsLT(VT)) {
9498 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9501 // And if it is bigger, shrink it first.
9502 if (SrcVT.bitsGT(VT)) {
9503 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9507 // At this point the operands and the result should have the same
9508 // type, and that won't be f80 since that is not custom lowered.
9510 // First get the sign bit of second operand.
9511 SmallVector<Constant*,4> CV;
9512 if (SrcVT == MVT::f64) {
9513 const fltSemantics &Sem = APFloat::IEEEdouble;
9514 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9515 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9517 const fltSemantics &Sem = APFloat::IEEEsingle;
9518 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9519 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9520 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9521 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9523 Constant *C = ConstantVector::get(CV);
9524 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9525 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9526 MachinePointerInfo::getConstantPool(),
9527 false, false, false, 16);
9528 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9530 // Shift sign bit right or left if the two operands have different types.
9531 if (SrcVT.bitsGT(VT)) {
9532 // Op0 is MVT::f32, Op1 is MVT::f64.
9533 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9534 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9535 DAG.getConstant(32, MVT::i32));
9536 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9537 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9538 DAG.getIntPtrConstant(0));
9541 // Clear first operand sign bit.
9543 if (VT == MVT::f64) {
9544 const fltSemantics &Sem = APFloat::IEEEdouble;
9545 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9546 APInt(64, ~(1ULL << 63)))));
9547 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9549 const fltSemantics &Sem = APFloat::IEEEsingle;
9550 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9551 APInt(32, ~(1U << 31)))));
9552 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9553 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9554 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9556 C = ConstantVector::get(CV);
9557 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9558 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9559 MachinePointerInfo::getConstantPool(),
9560 false, false, false, 16);
9561 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9563 // Or the value with the sign bit.
9564 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9567 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9568 SDValue N0 = Op.getOperand(0);
9570 MVT VT = Op.getSimpleValueType();
9572 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9573 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9574 DAG.getConstant(1, VT));
9575 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9578 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9580 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9581 SelectionDAG &DAG) {
9582 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9584 if (!Subtarget->hasSSE41())
9587 if (!Op->hasOneUse())
9590 SDNode *N = Op.getNode();
9593 SmallVector<SDValue, 8> Opnds;
9594 DenseMap<SDValue, unsigned> VecInMap;
9595 SmallVector<SDValue, 8> VecIns;
9596 EVT VT = MVT::Other;
9598 // Recognize a special case where a vector is casted into wide integer to
9600 Opnds.push_back(N->getOperand(0));
9601 Opnds.push_back(N->getOperand(1));
9603 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9604 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9605 // BFS traverse all OR'd operands.
9606 if (I->getOpcode() == ISD::OR) {
9607 Opnds.push_back(I->getOperand(0));
9608 Opnds.push_back(I->getOperand(1));
9609 // Re-evaluate the number of nodes to be traversed.
9610 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9614 // Quit if a non-EXTRACT_VECTOR_ELT
9615 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9618 // Quit if without a constant index.
9619 SDValue Idx = I->getOperand(1);
9620 if (!isa<ConstantSDNode>(Idx))
9623 SDValue ExtractedFromVec = I->getOperand(0);
9624 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9625 if (M == VecInMap.end()) {
9626 VT = ExtractedFromVec.getValueType();
9627 // Quit if not 128/256-bit vector.
9628 if (!VT.is128BitVector() && !VT.is256BitVector())
9630 // Quit if not the same type.
9631 if (VecInMap.begin() != VecInMap.end() &&
9632 VT != VecInMap.begin()->first.getValueType())
9634 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9635 VecIns.push_back(ExtractedFromVec);
9637 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9640 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9641 "Not extracted from 128-/256-bit vector.");
9643 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9645 for (DenseMap<SDValue, unsigned>::const_iterator
9646 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9647 // Quit if not all elements are used.
9648 if (I->second != FullMask)
9652 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9654 // Cast all vectors into TestVT for PTEST.
9655 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9656 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9658 // If more than one full vectors are evaluated, OR them first before PTEST.
9659 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9660 // Each iteration will OR 2 nodes and append the result until there is only
9661 // 1 node left, i.e. the final OR'd value of all vectors.
9662 SDValue LHS = VecIns[Slot];
9663 SDValue RHS = VecIns[Slot + 1];
9664 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9667 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9668 VecIns.back(), VecIns.back());
9671 /// Emit nodes that will be selected as "test Op0,Op0", or something
9673 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9674 SelectionDAG &DAG) const {
9675 if (Op.getValueType() == MVT::i1)
9676 // KORTEST instruction should be selected
9677 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9678 DAG.getConstant(0, Op.getValueType()));
9680 // CF and OF aren't always set the way we want. Determine which
9681 // of these we need.
9682 bool NeedCF = false;
9683 bool NeedOF = false;
9686 case X86::COND_A: case X86::COND_AE:
9687 case X86::COND_B: case X86::COND_BE:
9690 case X86::COND_G: case X86::COND_GE:
9691 case X86::COND_L: case X86::COND_LE:
9692 case X86::COND_O: case X86::COND_NO:
9696 // See if we can use the EFLAGS value from the operand instead of
9697 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9698 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9699 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9700 // Emit a CMP with 0, which is the TEST pattern.
9701 //if (Op.getValueType() == MVT::i1)
9702 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9703 // DAG.getConstant(0, MVT::i1));
9704 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9705 DAG.getConstant(0, Op.getValueType()));
9707 unsigned Opcode = 0;
9708 unsigned NumOperands = 0;
9710 // Truncate operations may prevent the merge of the SETCC instruction
9711 // and the arithmetic instruction before it. Attempt to truncate the operands
9712 // of the arithmetic instruction and use a reduced bit-width instruction.
9713 bool NeedTruncation = false;
9714 SDValue ArithOp = Op;
9715 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9716 SDValue Arith = Op->getOperand(0);
9717 // Both the trunc and the arithmetic op need to have one user each.
9718 if (Arith->hasOneUse())
9719 switch (Arith.getOpcode()) {
9726 NeedTruncation = true;
9732 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9733 // which may be the result of a CAST. We use the variable 'Op', which is the
9734 // non-casted variable when we check for possible users.
9735 switch (ArithOp.getOpcode()) {
9737 // Due to an isel shortcoming, be conservative if this add is likely to be
9738 // selected as part of a load-modify-store instruction. When the root node
9739 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9740 // uses of other nodes in the match, such as the ADD in this case. This
9741 // leads to the ADD being left around and reselected, with the result being
9742 // two adds in the output. Alas, even if none our users are stores, that
9743 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9744 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9745 // climbing the DAG back to the root, and it doesn't seem to be worth the
9747 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9748 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9749 if (UI->getOpcode() != ISD::CopyToReg &&
9750 UI->getOpcode() != ISD::SETCC &&
9751 UI->getOpcode() != ISD::STORE)
9754 if (ConstantSDNode *C =
9755 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9756 // An add of one will be selected as an INC.
9757 if (C->getAPIntValue() == 1) {
9758 Opcode = X86ISD::INC;
9763 // An add of negative one (subtract of one) will be selected as a DEC.
9764 if (C->getAPIntValue().isAllOnesValue()) {
9765 Opcode = X86ISD::DEC;
9771 // Otherwise use a regular EFLAGS-setting add.
9772 Opcode = X86ISD::ADD;
9776 // If the primary and result isn't used, don't bother using X86ISD::AND,
9777 // because a TEST instruction will be better.
9778 bool NonFlagUse = false;
9779 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9780 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9782 unsigned UOpNo = UI.getOperandNo();
9783 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9784 // Look pass truncate.
9785 UOpNo = User->use_begin().getOperandNo();
9786 User = *User->use_begin();
9789 if (User->getOpcode() != ISD::BRCOND &&
9790 User->getOpcode() != ISD::SETCC &&
9791 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9804 // Due to the ISEL shortcoming noted above, be conservative if this op is
9805 // likely to be selected as part of a load-modify-store instruction.
9806 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9807 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9808 if (UI->getOpcode() == ISD::STORE)
9811 // Otherwise use a regular EFLAGS-setting instruction.
9812 switch (ArithOp.getOpcode()) {
9813 default: llvm_unreachable("unexpected operator!");
9814 case ISD::SUB: Opcode = X86ISD::SUB; break;
9815 case ISD::XOR: Opcode = X86ISD::XOR; break;
9816 case ISD::AND: Opcode = X86ISD::AND; break;
9818 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9819 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9820 if (EFLAGS.getNode())
9823 Opcode = X86ISD::OR;
9837 return SDValue(Op.getNode(), 1);
9843 // If we found that truncation is beneficial, perform the truncation and
9845 if (NeedTruncation) {
9846 EVT VT = Op.getValueType();
9847 SDValue WideVal = Op->getOperand(0);
9848 EVT WideVT = WideVal.getValueType();
9849 unsigned ConvertedOp = 0;
9850 // Use a target machine opcode to prevent further DAGCombine
9851 // optimizations that may separate the arithmetic operations
9852 // from the setcc node.
9853 switch (WideVal.getOpcode()) {
9855 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9856 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9857 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9858 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9859 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9863 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9864 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9865 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9866 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9867 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9873 // Emit a CMP with 0, which is the TEST pattern.
9874 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9875 DAG.getConstant(0, Op.getValueType()));
9877 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9878 SmallVector<SDValue, 4> Ops;
9879 for (unsigned i = 0; i != NumOperands; ++i)
9880 Ops.push_back(Op.getOperand(i));
9882 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9883 DAG.ReplaceAllUsesWith(Op, New);
9884 return SDValue(New.getNode(), 1);
9887 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9889 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9890 SDLoc dl, SelectionDAG &DAG) const {
9891 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9892 if (C->getAPIntValue() == 0)
9893 return EmitTest(Op0, X86CC, dl, DAG);
9895 if (Op0.getValueType() == MVT::i1)
9896 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
9899 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9900 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9901 // Do the comparison at i32 if it's smaller, besides the Atom case.
9902 // This avoids subregister aliasing issues. Keep the smaller reference
9903 // if we're optimizing for size, however, as that'll allow better folding
9904 // of memory operations.
9905 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9906 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9907 AttributeSet::FunctionIndex, Attribute::MinSize) &&
9908 !Subtarget->isAtom()) {
9910 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9911 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9912 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9914 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9915 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9916 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9918 return SDValue(Sub.getNode(), 1);
9920 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9923 /// Convert a comparison if required by the subtarget.
9924 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9925 SelectionDAG &DAG) const {
9926 // If the subtarget does not support the FUCOMI instruction, floating-point
9927 // comparisons have to be converted.
9928 if (Subtarget->hasCMov() ||
9929 Cmp.getOpcode() != X86ISD::CMP ||
9930 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9931 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9934 // The instruction selector will select an FUCOM instruction instead of
9935 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9936 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9937 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9939 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9940 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9941 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9942 DAG.getConstant(8, MVT::i8));
9943 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9944 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9947 static bool isAllOnes(SDValue V) {
9948 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9949 return C && C->isAllOnesValue();
9952 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9953 /// if it's possible.
9954 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9955 SDLoc dl, SelectionDAG &DAG) const {
9956 SDValue Op0 = And.getOperand(0);
9957 SDValue Op1 = And.getOperand(1);
9958 if (Op0.getOpcode() == ISD::TRUNCATE)
9959 Op0 = Op0.getOperand(0);
9960 if (Op1.getOpcode() == ISD::TRUNCATE)
9961 Op1 = Op1.getOperand(0);
9964 if (Op1.getOpcode() == ISD::SHL)
9965 std::swap(Op0, Op1);
9966 if (Op0.getOpcode() == ISD::SHL) {
9967 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9968 if (And00C->getZExtValue() == 1) {
9969 // If we looked past a truncate, check that it's only truncating away
9971 unsigned BitWidth = Op0.getValueSizeInBits();
9972 unsigned AndBitWidth = And.getValueSizeInBits();
9973 if (BitWidth > AndBitWidth) {
9975 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9976 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9980 RHS = Op0.getOperand(1);
9982 } else if (Op1.getOpcode() == ISD::Constant) {
9983 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9984 uint64_t AndRHSVal = AndRHS->getZExtValue();
9985 SDValue AndLHS = Op0;
9987 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9988 LHS = AndLHS.getOperand(0);
9989 RHS = AndLHS.getOperand(1);
9992 // Use BT if the immediate can't be encoded in a TEST instruction.
9993 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9995 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9999 if (LHS.getNode()) {
10000 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10001 // instruction. Since the shift amount is in-range-or-undefined, we know
10002 // that doing a bittest on the i32 value is ok. We extend to i32 because
10003 // the encoding for the i16 version is larger than the i32 version.
10004 // Also promote i16 to i32 for performance / code size reason.
10005 if (LHS.getValueType() == MVT::i8 ||
10006 LHS.getValueType() == MVT::i16)
10007 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10009 // If the operand types disagree, extend the shift amount to match. Since
10010 // BT ignores high bits (like shifts) we can use anyextend.
10011 if (LHS.getValueType() != RHS.getValueType())
10012 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10014 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10015 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10016 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10017 DAG.getConstant(Cond, MVT::i8), BT);
10023 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10025 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10030 // SSE Condition code mapping:
10039 switch (SetCCOpcode) {
10040 default: llvm_unreachable("Unexpected SETCC condition");
10042 case ISD::SETEQ: SSECC = 0; break;
10044 case ISD::SETGT: Swap = true; // Fallthrough
10046 case ISD::SETOLT: SSECC = 1; break;
10048 case ISD::SETGE: Swap = true; // Fallthrough
10050 case ISD::SETOLE: SSECC = 2; break;
10051 case ISD::SETUO: SSECC = 3; break;
10053 case ISD::SETNE: SSECC = 4; break;
10054 case ISD::SETULE: Swap = true; // Fallthrough
10055 case ISD::SETUGE: SSECC = 5; break;
10056 case ISD::SETULT: Swap = true; // Fallthrough
10057 case ISD::SETUGT: SSECC = 6; break;
10058 case ISD::SETO: SSECC = 7; break;
10060 case ISD::SETONE: SSECC = 8; break;
10063 std::swap(Op0, Op1);
10068 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10069 // ones, and then concatenate the result back.
10070 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10071 MVT VT = Op.getSimpleValueType();
10073 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10074 "Unsupported value type for operation");
10076 unsigned NumElems = VT.getVectorNumElements();
10078 SDValue CC = Op.getOperand(2);
10080 // Extract the LHS vectors
10081 SDValue LHS = Op.getOperand(0);
10082 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10083 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10085 // Extract the RHS vectors
10086 SDValue RHS = Op.getOperand(1);
10087 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10088 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10090 // Issue the operation on the smaller types and concatenate the result back
10091 MVT EltVT = VT.getVectorElementType();
10092 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10093 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10094 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10095 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10098 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10099 const X86Subtarget *Subtarget) {
10100 SDValue Op0 = Op.getOperand(0);
10101 SDValue Op1 = Op.getOperand(1);
10102 SDValue CC = Op.getOperand(2);
10103 MVT VT = Op.getSimpleValueType();
10106 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10107 Op.getValueType().getScalarType() == MVT::i1 &&
10108 "Cannot set masked compare for this operation");
10110 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10112 bool Unsigned = false;
10115 switch (SetCCOpcode) {
10116 default: llvm_unreachable("Unexpected SETCC condition");
10117 case ISD::SETNE: SSECC = 4; break;
10118 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10119 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10120 case ISD::SETLT: Swap = true; //fall-through
10121 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10122 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10123 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10124 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10125 case ISD::SETULE: Unsigned = true; //fall-through
10126 case ISD::SETLE: SSECC = 2; break;
10130 std::swap(Op0, Op1);
10132 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10133 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10134 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10135 DAG.getConstant(SSECC, MVT::i8));
10138 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10139 /// operand \p Op1. If non-trivial (for example because it's not constant)
10140 /// return an empty value.
10141 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10143 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10147 MVT VT = Op1.getSimpleValueType();
10148 MVT EVT = VT.getVectorElementType();
10149 unsigned n = VT.getVectorNumElements();
10150 SmallVector<SDValue, 8> ULTOp1;
10152 for (unsigned i = 0; i < n; ++i) {
10153 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10154 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10157 // Avoid underflow.
10158 APInt Val = Elt->getAPIntValue();
10162 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10165 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1.data(), ULTOp1.size());
10168 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10169 SelectionDAG &DAG) {
10170 SDValue Op0 = Op.getOperand(0);
10171 SDValue Op1 = Op.getOperand(1);
10172 SDValue CC = Op.getOperand(2);
10173 MVT VT = Op.getSimpleValueType();
10174 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10175 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10180 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10181 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10184 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10185 unsigned Opc = X86ISD::CMPP;
10186 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10187 assert(VT.getVectorNumElements() <= 16);
10188 Opc = X86ISD::CMPM;
10190 // In the two special cases we can't handle, emit two comparisons.
10193 unsigned CombineOpc;
10194 if (SetCCOpcode == ISD::SETUEQ) {
10195 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10197 assert(SetCCOpcode == ISD::SETONE);
10198 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10201 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10202 DAG.getConstant(CC0, MVT::i8));
10203 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10204 DAG.getConstant(CC1, MVT::i8));
10205 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10207 // Handle all other FP comparisons here.
10208 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10209 DAG.getConstant(SSECC, MVT::i8));
10212 // Break 256-bit integer vector compare into smaller ones.
10213 if (VT.is256BitVector() && !Subtarget->hasInt256())
10214 return Lower256IntVSETCC(Op, DAG);
10216 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10217 EVT OpVT = Op1.getValueType();
10218 if (Subtarget->hasAVX512()) {
10219 if (Op1.getValueType().is512BitVector() ||
10220 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10221 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10223 // In AVX-512 architecture setcc returns mask with i1 elements,
10224 // But there is no compare instruction for i8 and i16 elements.
10225 // We are not talking about 512-bit operands in this case, these
10226 // types are illegal.
10228 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10229 OpVT.getVectorElementType().getSizeInBits() >= 8))
10230 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10231 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10234 // We are handling one of the integer comparisons here. Since SSE only has
10235 // GT and EQ comparisons for integer, swapping operands and multiple
10236 // operations may be required for some comparisons.
10238 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10239 bool Subus = false;
10241 switch (SetCCOpcode) {
10242 default: llvm_unreachable("Unexpected SETCC condition");
10243 case ISD::SETNE: Invert = true;
10244 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10245 case ISD::SETLT: Swap = true;
10246 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10247 case ISD::SETGE: Swap = true;
10248 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10249 Invert = true; break;
10250 case ISD::SETULT: Swap = true;
10251 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10252 FlipSigns = true; break;
10253 case ISD::SETUGE: Swap = true;
10254 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10255 FlipSigns = true; Invert = true; break;
10258 // Special case: Use min/max operations for SETULE/SETUGE
10259 MVT VET = VT.getVectorElementType();
10261 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10262 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10265 switch (SetCCOpcode) {
10267 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10268 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10271 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10274 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10275 if (!MinMax && hasSubus) {
10276 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10278 // t = psubus Op0, Op1
10279 // pcmpeq t, <0..0>
10280 switch (SetCCOpcode) {
10282 case ISD::SETULT: {
10283 // If the comparison is against a constant we can turn this into a
10284 // setule. With psubus, setule does not require a swap. This is
10285 // beneficial because the constant in the register is no longer
10286 // destructed as the destination so it can be hoisted out of a loop.
10287 // Only do this pre-AVX since vpcmp* is no longer destructive.
10288 if (Subtarget->hasAVX())
10290 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10291 if (ULEOp1.getNode()) {
10293 Subus = true; Invert = false; Swap = false;
10297 // Psubus is better than flip-sign because it requires no inversion.
10298 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10299 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10303 Opc = X86ISD::SUBUS;
10309 std::swap(Op0, Op1);
10311 // Check that the operation in question is available (most are plain SSE2,
10312 // but PCMPGTQ and PCMPEQQ have different requirements).
10313 if (VT == MVT::v2i64) {
10314 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10315 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10317 // First cast everything to the right type.
10318 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10319 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10321 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10322 // bits of the inputs before performing those operations. The lower
10323 // compare is always unsigned.
10326 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10328 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10329 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10330 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10331 Sign, Zero, Sign, Zero);
10333 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10334 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10336 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10337 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10338 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10340 // Create masks for only the low parts/high parts of the 64 bit integers.
10341 static const int MaskHi[] = { 1, 1, 3, 3 };
10342 static const int MaskLo[] = { 0, 0, 2, 2 };
10343 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10344 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10345 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10347 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10348 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10351 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10353 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10356 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10357 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10358 // pcmpeqd + pshufd + pand.
10359 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10361 // First cast everything to the right type.
10362 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10363 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10366 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10368 // Make sure the lower and upper halves are both all-ones.
10369 static const int Mask[] = { 1, 0, 3, 2 };
10370 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10371 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10374 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10376 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10380 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10381 // bits of the inputs before performing those operations.
10383 EVT EltVT = VT.getVectorElementType();
10384 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10385 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10386 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10389 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10391 // If the logical-not of the result is required, perform that now.
10393 Result = DAG.getNOT(dl, Result, VT);
10396 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10399 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10400 getZeroVector(VT, Subtarget, DAG, dl));
10405 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10407 MVT VT = Op.getSimpleValueType();
10409 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10411 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10412 && "SetCC type must be 8-bit or 1-bit integer");
10413 SDValue Op0 = Op.getOperand(0);
10414 SDValue Op1 = Op.getOperand(1);
10416 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10418 // Optimize to BT if possible.
10419 // Lower (X & (1 << N)) == 0 to BT(X, N).
10420 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10421 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10422 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10423 Op1.getOpcode() == ISD::Constant &&
10424 cast<ConstantSDNode>(Op1)->isNullValue() &&
10425 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10426 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10427 if (NewSetCC.getNode())
10431 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10433 if (Op1.getOpcode() == ISD::Constant &&
10434 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10435 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10436 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10438 // If the input is a setcc, then reuse the input setcc or use a new one with
10439 // the inverted condition.
10440 if (Op0.getOpcode() == X86ISD::SETCC) {
10441 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10442 bool Invert = (CC == ISD::SETNE) ^
10443 cast<ConstantSDNode>(Op1)->isNullValue();
10447 CCode = X86::GetOppositeBranchCondition(CCode);
10448 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10449 DAG.getConstant(CCode, MVT::i8),
10450 Op0.getOperand(1));
10452 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10456 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10457 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10458 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10460 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10461 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10464 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10465 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10466 if (X86CC == X86::COND_INVALID)
10469 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10470 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10471 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10472 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10474 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10478 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10479 static bool isX86LogicalCmp(SDValue Op) {
10480 unsigned Opc = Op.getNode()->getOpcode();
10481 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10482 Opc == X86ISD::SAHF)
10484 if (Op.getResNo() == 1 &&
10485 (Opc == X86ISD::ADD ||
10486 Opc == X86ISD::SUB ||
10487 Opc == X86ISD::ADC ||
10488 Opc == X86ISD::SBB ||
10489 Opc == X86ISD::SMUL ||
10490 Opc == X86ISD::UMUL ||
10491 Opc == X86ISD::INC ||
10492 Opc == X86ISD::DEC ||
10493 Opc == X86ISD::OR ||
10494 Opc == X86ISD::XOR ||
10495 Opc == X86ISD::AND))
10498 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10504 static bool isZero(SDValue V) {
10505 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10506 return C && C->isNullValue();
10509 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10510 if (V.getOpcode() != ISD::TRUNCATE)
10513 SDValue VOp0 = V.getOperand(0);
10514 unsigned InBits = VOp0.getValueSizeInBits();
10515 unsigned Bits = V.getValueSizeInBits();
10516 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10519 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10520 bool addTest = true;
10521 SDValue Cond = Op.getOperand(0);
10522 SDValue Op1 = Op.getOperand(1);
10523 SDValue Op2 = Op.getOperand(2);
10525 EVT VT = Op1.getValueType();
10528 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10529 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10530 // sequence later on.
10531 if (Cond.getOpcode() == ISD::SETCC &&
10532 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10533 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10534 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10535 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10536 int SSECC = translateX86FSETCC(
10537 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10540 if (Subtarget->hasAVX512()) {
10541 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10542 DAG.getConstant(SSECC, MVT::i8));
10543 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10545 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10546 DAG.getConstant(SSECC, MVT::i8));
10547 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10548 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10549 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10553 if (Cond.getOpcode() == ISD::SETCC) {
10554 SDValue NewCond = LowerSETCC(Cond, DAG);
10555 if (NewCond.getNode())
10559 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10560 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10561 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10562 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10563 if (Cond.getOpcode() == X86ISD::SETCC &&
10564 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10565 isZero(Cond.getOperand(1).getOperand(1))) {
10566 SDValue Cmp = Cond.getOperand(1);
10568 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10570 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10571 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10572 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10574 SDValue CmpOp0 = Cmp.getOperand(0);
10575 // Apply further optimizations for special cases
10576 // (select (x != 0), -1, 0) -> neg & sbb
10577 // (select (x == 0), 0, -1) -> neg & sbb
10578 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10579 if (YC->isNullValue() &&
10580 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10581 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10582 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10583 DAG.getConstant(0, CmpOp0.getValueType()),
10585 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10586 DAG.getConstant(X86::COND_B, MVT::i8),
10587 SDValue(Neg.getNode(), 1));
10591 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10592 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10593 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10595 SDValue Res = // Res = 0 or -1.
10596 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10597 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10599 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10600 Res = DAG.getNOT(DL, Res, Res.getValueType());
10602 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10603 if (N2C == 0 || !N2C->isNullValue())
10604 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10609 // Look past (and (setcc_carry (cmp ...)), 1).
10610 if (Cond.getOpcode() == ISD::AND &&
10611 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10612 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10613 if (C && C->getAPIntValue() == 1)
10614 Cond = Cond.getOperand(0);
10617 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10618 // setting operand in place of the X86ISD::SETCC.
10619 unsigned CondOpcode = Cond.getOpcode();
10620 if (CondOpcode == X86ISD::SETCC ||
10621 CondOpcode == X86ISD::SETCC_CARRY) {
10622 CC = Cond.getOperand(0);
10624 SDValue Cmp = Cond.getOperand(1);
10625 unsigned Opc = Cmp.getOpcode();
10626 MVT VT = Op.getSimpleValueType();
10628 bool IllegalFPCMov = false;
10629 if (VT.isFloatingPoint() && !VT.isVector() &&
10630 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10631 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10633 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10634 Opc == X86ISD::BT) { // FIXME
10638 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10639 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10640 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10641 Cond.getOperand(0).getValueType() != MVT::i8)) {
10642 SDValue LHS = Cond.getOperand(0);
10643 SDValue RHS = Cond.getOperand(1);
10644 unsigned X86Opcode;
10647 switch (CondOpcode) {
10648 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10649 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10650 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10651 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10652 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10653 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10654 default: llvm_unreachable("unexpected overflowing operator");
10656 if (CondOpcode == ISD::UMULO)
10657 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10660 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10662 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10664 if (CondOpcode == ISD::UMULO)
10665 Cond = X86Op.getValue(2);
10667 Cond = X86Op.getValue(1);
10669 CC = DAG.getConstant(X86Cond, MVT::i8);
10674 // Look pass the truncate if the high bits are known zero.
10675 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10676 Cond = Cond.getOperand(0);
10678 // We know the result of AND is compared against zero. Try to match
10680 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10681 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10682 if (NewSetCC.getNode()) {
10683 CC = NewSetCC.getOperand(0);
10684 Cond = NewSetCC.getOperand(1);
10691 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10692 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10695 // a < b ? -1 : 0 -> RES = ~setcc_carry
10696 // a < b ? 0 : -1 -> RES = setcc_carry
10697 // a >= b ? -1 : 0 -> RES = setcc_carry
10698 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10699 if (Cond.getOpcode() == X86ISD::SUB) {
10700 Cond = ConvertCmpIfNecessary(Cond, DAG);
10701 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10703 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10704 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10705 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10706 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10707 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10708 return DAG.getNOT(DL, Res, Res.getValueType());
10713 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10714 // widen the cmov and push the truncate through. This avoids introducing a new
10715 // branch during isel and doesn't add any extensions.
10716 if (Op.getValueType() == MVT::i8 &&
10717 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10718 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10719 if (T1.getValueType() == T2.getValueType() &&
10720 // Blacklist CopyFromReg to avoid partial register stalls.
10721 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10722 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10723 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10724 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10728 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10729 // condition is true.
10730 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10731 SDValue Ops[] = { Op2, Op1, CC, Cond };
10732 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10735 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10736 MVT VT = Op->getSimpleValueType(0);
10737 SDValue In = Op->getOperand(0);
10738 MVT InVT = In.getSimpleValueType();
10741 unsigned int NumElts = VT.getVectorNumElements();
10742 if (NumElts != 8 && NumElts != 16)
10745 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10746 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10748 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10749 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10751 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10752 Constant *C = ConstantInt::get(*DAG.getContext(),
10753 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10755 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10756 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10757 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10758 MachinePointerInfo::getConstantPool(),
10759 false, false, false, Alignment);
10760 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10761 if (VT.is512BitVector())
10763 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10766 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10767 SelectionDAG &DAG) {
10768 MVT VT = Op->getSimpleValueType(0);
10769 SDValue In = Op->getOperand(0);
10770 MVT InVT = In.getSimpleValueType();
10773 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10774 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10776 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10777 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10778 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10781 if (Subtarget->hasInt256())
10782 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10784 // Optimize vectors in AVX mode
10785 // Sign extend v8i16 to v8i32 and
10788 // Divide input vector into two parts
10789 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10790 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10791 // concat the vectors to original VT
10793 unsigned NumElems = InVT.getVectorNumElements();
10794 SDValue Undef = DAG.getUNDEF(InVT);
10796 SmallVector<int,8> ShufMask1(NumElems, -1);
10797 for (unsigned i = 0; i != NumElems/2; ++i)
10800 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10802 SmallVector<int,8> ShufMask2(NumElems, -1);
10803 for (unsigned i = 0; i != NumElems/2; ++i)
10804 ShufMask2[i] = i + NumElems/2;
10806 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10808 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10809 VT.getVectorNumElements()/2);
10811 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10812 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10814 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10817 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10818 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10819 // from the AND / OR.
10820 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10821 Opc = Op.getOpcode();
10822 if (Opc != ISD::OR && Opc != ISD::AND)
10824 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10825 Op.getOperand(0).hasOneUse() &&
10826 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10827 Op.getOperand(1).hasOneUse());
10830 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10831 // 1 and that the SETCC node has a single use.
10832 static bool isXor1OfSetCC(SDValue Op) {
10833 if (Op.getOpcode() != ISD::XOR)
10835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10836 if (N1C && N1C->getAPIntValue() == 1) {
10837 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10838 Op.getOperand(0).hasOneUse();
10843 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10844 bool addTest = true;
10845 SDValue Chain = Op.getOperand(0);
10846 SDValue Cond = Op.getOperand(1);
10847 SDValue Dest = Op.getOperand(2);
10850 bool Inverted = false;
10852 if (Cond.getOpcode() == ISD::SETCC) {
10853 // Check for setcc([su]{add,sub,mul}o == 0).
10854 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10855 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10856 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10857 Cond.getOperand(0).getResNo() == 1 &&
10858 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10859 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10860 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10861 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10862 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10863 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10865 Cond = Cond.getOperand(0);
10867 SDValue NewCond = LowerSETCC(Cond, DAG);
10868 if (NewCond.getNode())
10873 // FIXME: LowerXALUO doesn't handle these!!
10874 else if (Cond.getOpcode() == X86ISD::ADD ||
10875 Cond.getOpcode() == X86ISD::SUB ||
10876 Cond.getOpcode() == X86ISD::SMUL ||
10877 Cond.getOpcode() == X86ISD::UMUL)
10878 Cond = LowerXALUO(Cond, DAG);
10881 // Look pass (and (setcc_carry (cmp ...)), 1).
10882 if (Cond.getOpcode() == ISD::AND &&
10883 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10884 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10885 if (C && C->getAPIntValue() == 1)
10886 Cond = Cond.getOperand(0);
10889 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10890 // setting operand in place of the X86ISD::SETCC.
10891 unsigned CondOpcode = Cond.getOpcode();
10892 if (CondOpcode == X86ISD::SETCC ||
10893 CondOpcode == X86ISD::SETCC_CARRY) {
10894 CC = Cond.getOperand(0);
10896 SDValue Cmp = Cond.getOperand(1);
10897 unsigned Opc = Cmp.getOpcode();
10898 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10899 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10903 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10907 // These can only come from an arithmetic instruction with overflow,
10908 // e.g. SADDO, UADDO.
10909 Cond = Cond.getNode()->getOperand(1);
10915 CondOpcode = Cond.getOpcode();
10916 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10917 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10918 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10919 Cond.getOperand(0).getValueType() != MVT::i8)) {
10920 SDValue LHS = Cond.getOperand(0);
10921 SDValue RHS = Cond.getOperand(1);
10922 unsigned X86Opcode;
10925 // Keep this in sync with LowerXALUO, otherwise we might create redundant
10926 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
10928 switch (CondOpcode) {
10929 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10931 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10933 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
10936 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10937 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10939 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10941 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
10944 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10945 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10946 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10947 default: llvm_unreachable("unexpected overflowing operator");
10950 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10951 if (CondOpcode == ISD::UMULO)
10952 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10955 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10957 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10959 if (CondOpcode == ISD::UMULO)
10960 Cond = X86Op.getValue(2);
10962 Cond = X86Op.getValue(1);
10964 CC = DAG.getConstant(X86Cond, MVT::i8);
10968 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10969 SDValue Cmp = Cond.getOperand(0).getOperand(1);
10970 if (CondOpc == ISD::OR) {
10971 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10972 // two branches instead of an explicit OR instruction with a
10974 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10975 isX86LogicalCmp(Cmp)) {
10976 CC = Cond.getOperand(0).getOperand(0);
10977 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10978 Chain, Dest, CC, Cmp);
10979 CC = Cond.getOperand(1).getOperand(0);
10983 } else { // ISD::AND
10984 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10985 // two branches instead of an explicit AND instruction with a
10986 // separate test. However, we only do this if this block doesn't
10987 // have a fall-through edge, because this requires an explicit
10988 // jmp when the condition is false.
10989 if (Cmp == Cond.getOperand(1).getOperand(1) &&
10990 isX86LogicalCmp(Cmp) &&
10991 Op.getNode()->hasOneUse()) {
10992 X86::CondCode CCode =
10993 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10994 CCode = X86::GetOppositeBranchCondition(CCode);
10995 CC = DAG.getConstant(CCode, MVT::i8);
10996 SDNode *User = *Op.getNode()->use_begin();
10997 // Look for an unconditional branch following this conditional branch.
10998 // We need this because we need to reverse the successors in order
10999 // to implement FCMP_OEQ.
11000 if (User->getOpcode() == ISD::BR) {
11001 SDValue FalseBB = User->getOperand(1);
11003 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11004 assert(NewBR == User);
11008 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11009 Chain, Dest, CC, Cmp);
11010 X86::CondCode CCode =
11011 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11012 CCode = X86::GetOppositeBranchCondition(CCode);
11013 CC = DAG.getConstant(CCode, MVT::i8);
11019 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11020 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11021 // It should be transformed during dag combiner except when the condition
11022 // is set by a arithmetics with overflow node.
11023 X86::CondCode CCode =
11024 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11025 CCode = X86::GetOppositeBranchCondition(CCode);
11026 CC = DAG.getConstant(CCode, MVT::i8);
11027 Cond = Cond.getOperand(0).getOperand(1);
11029 } else if (Cond.getOpcode() == ISD::SETCC &&
11030 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11031 // For FCMP_OEQ, we can emit
11032 // two branches instead of an explicit AND instruction with a
11033 // separate test. However, we only do this if this block doesn't
11034 // have a fall-through edge, because this requires an explicit
11035 // jmp when the condition is false.
11036 if (Op.getNode()->hasOneUse()) {
11037 SDNode *User = *Op.getNode()->use_begin();
11038 // Look for an unconditional branch following this conditional branch.
11039 // We need this because we need to reverse the successors in order
11040 // to implement FCMP_OEQ.
11041 if (User->getOpcode() == ISD::BR) {
11042 SDValue FalseBB = User->getOperand(1);
11044 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11045 assert(NewBR == User);
11049 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11050 Cond.getOperand(0), Cond.getOperand(1));
11051 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11052 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11053 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11054 Chain, Dest, CC, Cmp);
11055 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11060 } else if (Cond.getOpcode() == ISD::SETCC &&
11061 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11062 // For FCMP_UNE, we can emit
11063 // two branches instead of an explicit AND instruction with a
11064 // separate test. However, we only do this if this block doesn't
11065 // have a fall-through edge, because this requires an explicit
11066 // jmp when the condition is false.
11067 if (Op.getNode()->hasOneUse()) {
11068 SDNode *User = *Op.getNode()->use_begin();
11069 // Look for an unconditional branch following this conditional branch.
11070 // We need this because we need to reverse the successors in order
11071 // to implement FCMP_UNE.
11072 if (User->getOpcode() == ISD::BR) {
11073 SDValue FalseBB = User->getOperand(1);
11075 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11076 assert(NewBR == User);
11079 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11080 Cond.getOperand(0), Cond.getOperand(1));
11081 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11082 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11083 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11084 Chain, Dest, CC, Cmp);
11085 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11095 // Look pass the truncate if the high bits are known zero.
11096 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11097 Cond = Cond.getOperand(0);
11099 // We know the result of AND is compared against zero. Try to match
11101 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11102 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11103 if (NewSetCC.getNode()) {
11104 CC = NewSetCC.getOperand(0);
11105 Cond = NewSetCC.getOperand(1);
11112 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11113 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11115 Cond = ConvertCmpIfNecessary(Cond, DAG);
11116 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11117 Chain, Dest, CC, Cond);
11120 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11121 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11122 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11123 // that the guard pages used by the OS virtual memory manager are allocated in
11124 // correct sequence.
11126 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11127 SelectionDAG &DAG) const {
11128 MachineFunction &MF = DAG.getMachineFunction();
11129 bool SplitStack = MF.shouldSplitStack();
11130 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11135 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11136 SDNode* Node = Op.getNode();
11138 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11139 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11140 " not tell us which reg is the stack pointer!");
11141 EVT VT = Node->getValueType(0);
11142 SDValue Tmp1 = SDValue(Node, 0);
11143 SDValue Tmp2 = SDValue(Node, 1);
11144 SDValue Tmp3 = Node->getOperand(2);
11145 SDValue Chain = Tmp1.getOperand(0);
11147 // Chain the dynamic stack allocation so that it doesn't modify the stack
11148 // pointer when other instructions are using the stack.
11149 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11152 SDValue Size = Tmp2.getOperand(1);
11153 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11154 Chain = SP.getValue(1);
11155 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11156 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11157 unsigned StackAlign = TFI.getStackAlignment();
11158 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11159 if (Align > StackAlign)
11160 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11161 DAG.getConstant(-(uint64_t)Align, VT));
11162 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11164 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11165 DAG.getIntPtrConstant(0, true), SDValue(),
11168 SDValue Ops[2] = { Tmp1, Tmp2 };
11169 return DAG.getMergeValues(Ops, 2, dl);
11173 SDValue Chain = Op.getOperand(0);
11174 SDValue Size = Op.getOperand(1);
11175 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11176 EVT VT = Op.getNode()->getValueType(0);
11178 bool Is64Bit = Subtarget->is64Bit();
11179 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11182 MachineRegisterInfo &MRI = MF.getRegInfo();
11185 // The 64 bit implementation of segmented stacks needs to clobber both r10
11186 // r11. This makes it impossible to use it along with nested parameters.
11187 const Function *F = MF.getFunction();
11189 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11191 if (I->hasNestAttr())
11192 report_fatal_error("Cannot use segmented stacks with functions that "
11193 "have nested arguments.");
11196 const TargetRegisterClass *AddrRegClass =
11197 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11198 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11199 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11200 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11201 DAG.getRegister(Vreg, SPTy));
11202 SDValue Ops1[2] = { Value, Chain };
11203 return DAG.getMergeValues(Ops1, 2, dl);
11206 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11208 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11209 Flag = Chain.getValue(1);
11210 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11212 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11214 const X86RegisterInfo *RegInfo =
11215 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11216 unsigned SPReg = RegInfo->getStackRegister();
11217 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11218 Chain = SP.getValue(1);
11221 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11222 DAG.getConstant(-(uint64_t)Align, VT));
11223 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11226 SDValue Ops1[2] = { SP, Chain };
11227 return DAG.getMergeValues(Ops1, 2, dl);
11231 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11232 MachineFunction &MF = DAG.getMachineFunction();
11233 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11235 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11238 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11239 // vastart just stores the address of the VarArgsFrameIndex slot into the
11240 // memory location argument.
11241 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11243 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11244 MachinePointerInfo(SV), false, false, 0);
11248 // gp_offset (0 - 6 * 8)
11249 // fp_offset (48 - 48 + 8 * 16)
11250 // overflow_arg_area (point to parameters coming in memory).
11252 SmallVector<SDValue, 8> MemOps;
11253 SDValue FIN = Op.getOperand(1);
11255 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11256 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11258 FIN, MachinePointerInfo(SV), false, false, 0);
11259 MemOps.push_back(Store);
11262 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11263 FIN, DAG.getIntPtrConstant(4));
11264 Store = DAG.getStore(Op.getOperand(0), DL,
11265 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11267 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11268 MemOps.push_back(Store);
11270 // Store ptr to overflow_arg_area
11271 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11272 FIN, DAG.getIntPtrConstant(4));
11273 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11275 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11276 MachinePointerInfo(SV, 8),
11278 MemOps.push_back(Store);
11280 // Store ptr to reg_save_area.
11281 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11282 FIN, DAG.getIntPtrConstant(8));
11283 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11285 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11286 MachinePointerInfo(SV, 16), false, false, 0);
11287 MemOps.push_back(Store);
11288 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11289 &MemOps[0], MemOps.size());
11292 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11293 assert(Subtarget->is64Bit() &&
11294 "LowerVAARG only handles 64-bit va_arg!");
11295 assert((Subtarget->isTargetLinux() ||
11296 Subtarget->isTargetDarwin()) &&
11297 "Unhandled target in LowerVAARG");
11298 assert(Op.getNode()->getNumOperands() == 4);
11299 SDValue Chain = Op.getOperand(0);
11300 SDValue SrcPtr = Op.getOperand(1);
11301 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11302 unsigned Align = Op.getConstantOperandVal(3);
11305 EVT ArgVT = Op.getNode()->getValueType(0);
11306 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11307 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11310 // Decide which area this value should be read from.
11311 // TODO: Implement the AMD64 ABI in its entirety. This simple
11312 // selection mechanism works only for the basic types.
11313 if (ArgVT == MVT::f80) {
11314 llvm_unreachable("va_arg for f80 not yet implemented");
11315 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11316 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11317 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11318 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11320 llvm_unreachable("Unhandled argument type in LowerVAARG");
11323 if (ArgMode == 2) {
11324 // Sanity Check: Make sure using fp_offset makes sense.
11325 assert(!getTargetMachine().Options.UseSoftFloat &&
11326 !(DAG.getMachineFunction()
11327 .getFunction()->getAttributes()
11328 .hasAttribute(AttributeSet::FunctionIndex,
11329 Attribute::NoImplicitFloat)) &&
11330 Subtarget->hasSSE1());
11333 // Insert VAARG_64 node into the DAG
11334 // VAARG_64 returns two values: Variable Argument Address, Chain
11335 SmallVector<SDValue, 11> InstOps;
11336 InstOps.push_back(Chain);
11337 InstOps.push_back(SrcPtr);
11338 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11339 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11340 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11341 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11342 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11343 VTs, &InstOps[0], InstOps.size(),
11345 MachinePointerInfo(SV),
11347 /*Volatile=*/false,
11349 /*WriteMem=*/true);
11350 Chain = VAARG.getValue(1);
11352 // Load the next argument and return it
11353 return DAG.getLoad(ArgVT, dl,
11356 MachinePointerInfo(),
11357 false, false, false, 0);
11360 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11361 SelectionDAG &DAG) {
11362 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11363 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11364 SDValue Chain = Op.getOperand(0);
11365 SDValue DstPtr = Op.getOperand(1);
11366 SDValue SrcPtr = Op.getOperand(2);
11367 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11368 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11371 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11372 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11374 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11377 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11378 // amount is a constant. Takes immediate version of shift as input.
11379 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11380 SDValue SrcOp, uint64_t ShiftAmt,
11381 SelectionDAG &DAG) {
11382 MVT ElementType = VT.getVectorElementType();
11384 // Check for ShiftAmt >= element width
11385 if (ShiftAmt >= ElementType.getSizeInBits()) {
11386 if (Opc == X86ISD::VSRAI)
11387 ShiftAmt = ElementType.getSizeInBits() - 1;
11389 return DAG.getConstant(0, VT);
11392 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11393 && "Unknown target vector shift-by-constant node");
11395 // Fold this packed vector shift into a build vector if SrcOp is a
11396 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11397 if (VT == SrcOp.getSimpleValueType() &&
11398 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11399 SmallVector<SDValue, 8> Elts;
11400 unsigned NumElts = SrcOp->getNumOperands();
11401 ConstantSDNode *ND;
11404 default: llvm_unreachable(0);
11405 case X86ISD::VSHLI:
11406 for (unsigned i=0; i!=NumElts; ++i) {
11407 SDValue CurrentOp = SrcOp->getOperand(i);
11408 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11409 Elts.push_back(CurrentOp);
11412 ND = cast<ConstantSDNode>(CurrentOp);
11413 const APInt &C = ND->getAPIntValue();
11414 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11417 case X86ISD::VSRLI:
11418 for (unsigned i=0; i!=NumElts; ++i) {
11419 SDValue CurrentOp = SrcOp->getOperand(i);
11420 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11421 Elts.push_back(CurrentOp);
11424 ND = cast<ConstantSDNode>(CurrentOp);
11425 const APInt &C = ND->getAPIntValue();
11426 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11429 case X86ISD::VSRAI:
11430 for (unsigned i=0; i!=NumElts; ++i) {
11431 SDValue CurrentOp = SrcOp->getOperand(i);
11432 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11433 Elts.push_back(CurrentOp);
11436 ND = cast<ConstantSDNode>(CurrentOp);
11437 const APInt &C = ND->getAPIntValue();
11438 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11443 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11446 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11449 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11450 // may or may not be a constant. Takes immediate version of shift as input.
11451 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11452 SDValue SrcOp, SDValue ShAmt,
11453 SelectionDAG &DAG) {
11454 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11456 // Catch shift-by-constant.
11457 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11458 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11459 CShAmt->getZExtValue(), DAG);
11461 // Change opcode to non-immediate version
11463 default: llvm_unreachable("Unknown target vector shift node");
11464 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11465 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11466 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11469 // Need to build a vector containing shift amount
11470 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11473 ShOps[1] = DAG.getConstant(0, MVT::i32);
11474 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11475 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11477 // The return type has to be a 128-bit type with the same element
11478 // type as the input type.
11479 MVT EltVT = VT.getVectorElementType();
11480 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11482 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11483 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11486 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11488 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11490 default: return SDValue(); // Don't custom lower most intrinsics.
11491 // Comparison intrinsics.
11492 case Intrinsic::x86_sse_comieq_ss:
11493 case Intrinsic::x86_sse_comilt_ss:
11494 case Intrinsic::x86_sse_comile_ss:
11495 case Intrinsic::x86_sse_comigt_ss:
11496 case Intrinsic::x86_sse_comige_ss:
11497 case Intrinsic::x86_sse_comineq_ss:
11498 case Intrinsic::x86_sse_ucomieq_ss:
11499 case Intrinsic::x86_sse_ucomilt_ss:
11500 case Intrinsic::x86_sse_ucomile_ss:
11501 case Intrinsic::x86_sse_ucomigt_ss:
11502 case Intrinsic::x86_sse_ucomige_ss:
11503 case Intrinsic::x86_sse_ucomineq_ss:
11504 case Intrinsic::x86_sse2_comieq_sd:
11505 case Intrinsic::x86_sse2_comilt_sd:
11506 case Intrinsic::x86_sse2_comile_sd:
11507 case Intrinsic::x86_sse2_comigt_sd:
11508 case Intrinsic::x86_sse2_comige_sd:
11509 case Intrinsic::x86_sse2_comineq_sd:
11510 case Intrinsic::x86_sse2_ucomieq_sd:
11511 case Intrinsic::x86_sse2_ucomilt_sd:
11512 case Intrinsic::x86_sse2_ucomile_sd:
11513 case Intrinsic::x86_sse2_ucomigt_sd:
11514 case Intrinsic::x86_sse2_ucomige_sd:
11515 case Intrinsic::x86_sse2_ucomineq_sd: {
11519 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11520 case Intrinsic::x86_sse_comieq_ss:
11521 case Intrinsic::x86_sse2_comieq_sd:
11522 Opc = X86ISD::COMI;
11525 case Intrinsic::x86_sse_comilt_ss:
11526 case Intrinsic::x86_sse2_comilt_sd:
11527 Opc = X86ISD::COMI;
11530 case Intrinsic::x86_sse_comile_ss:
11531 case Intrinsic::x86_sse2_comile_sd:
11532 Opc = X86ISD::COMI;
11535 case Intrinsic::x86_sse_comigt_ss:
11536 case Intrinsic::x86_sse2_comigt_sd:
11537 Opc = X86ISD::COMI;
11540 case Intrinsic::x86_sse_comige_ss:
11541 case Intrinsic::x86_sse2_comige_sd:
11542 Opc = X86ISD::COMI;
11545 case Intrinsic::x86_sse_comineq_ss:
11546 case Intrinsic::x86_sse2_comineq_sd:
11547 Opc = X86ISD::COMI;
11550 case Intrinsic::x86_sse_ucomieq_ss:
11551 case Intrinsic::x86_sse2_ucomieq_sd:
11552 Opc = X86ISD::UCOMI;
11555 case Intrinsic::x86_sse_ucomilt_ss:
11556 case Intrinsic::x86_sse2_ucomilt_sd:
11557 Opc = X86ISD::UCOMI;
11560 case Intrinsic::x86_sse_ucomile_ss:
11561 case Intrinsic::x86_sse2_ucomile_sd:
11562 Opc = X86ISD::UCOMI;
11565 case Intrinsic::x86_sse_ucomigt_ss:
11566 case Intrinsic::x86_sse2_ucomigt_sd:
11567 Opc = X86ISD::UCOMI;
11570 case Intrinsic::x86_sse_ucomige_ss:
11571 case Intrinsic::x86_sse2_ucomige_sd:
11572 Opc = X86ISD::UCOMI;
11575 case Intrinsic::x86_sse_ucomineq_ss:
11576 case Intrinsic::x86_sse2_ucomineq_sd:
11577 Opc = X86ISD::UCOMI;
11582 SDValue LHS = Op.getOperand(1);
11583 SDValue RHS = Op.getOperand(2);
11584 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11585 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11586 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11587 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11588 DAG.getConstant(X86CC, MVT::i8), Cond);
11589 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11592 // Arithmetic intrinsics.
11593 case Intrinsic::x86_sse2_pmulu_dq:
11594 case Intrinsic::x86_avx2_pmulu_dq:
11595 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11596 Op.getOperand(1), Op.getOperand(2));
11598 // SSE2/AVX2 sub with unsigned saturation intrinsics
11599 case Intrinsic::x86_sse2_psubus_b:
11600 case Intrinsic::x86_sse2_psubus_w:
11601 case Intrinsic::x86_avx2_psubus_b:
11602 case Intrinsic::x86_avx2_psubus_w:
11603 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11604 Op.getOperand(1), Op.getOperand(2));
11606 // SSE3/AVX horizontal add/sub intrinsics
11607 case Intrinsic::x86_sse3_hadd_ps:
11608 case Intrinsic::x86_sse3_hadd_pd:
11609 case Intrinsic::x86_avx_hadd_ps_256:
11610 case Intrinsic::x86_avx_hadd_pd_256:
11611 case Intrinsic::x86_sse3_hsub_ps:
11612 case Intrinsic::x86_sse3_hsub_pd:
11613 case Intrinsic::x86_avx_hsub_ps_256:
11614 case Intrinsic::x86_avx_hsub_pd_256:
11615 case Intrinsic::x86_ssse3_phadd_w_128:
11616 case Intrinsic::x86_ssse3_phadd_d_128:
11617 case Intrinsic::x86_avx2_phadd_w:
11618 case Intrinsic::x86_avx2_phadd_d:
11619 case Intrinsic::x86_ssse3_phsub_w_128:
11620 case Intrinsic::x86_ssse3_phsub_d_128:
11621 case Intrinsic::x86_avx2_phsub_w:
11622 case Intrinsic::x86_avx2_phsub_d: {
11625 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11626 case Intrinsic::x86_sse3_hadd_ps:
11627 case Intrinsic::x86_sse3_hadd_pd:
11628 case Intrinsic::x86_avx_hadd_ps_256:
11629 case Intrinsic::x86_avx_hadd_pd_256:
11630 Opcode = X86ISD::FHADD;
11632 case Intrinsic::x86_sse3_hsub_ps:
11633 case Intrinsic::x86_sse3_hsub_pd:
11634 case Intrinsic::x86_avx_hsub_ps_256:
11635 case Intrinsic::x86_avx_hsub_pd_256:
11636 Opcode = X86ISD::FHSUB;
11638 case Intrinsic::x86_ssse3_phadd_w_128:
11639 case Intrinsic::x86_ssse3_phadd_d_128:
11640 case Intrinsic::x86_avx2_phadd_w:
11641 case Intrinsic::x86_avx2_phadd_d:
11642 Opcode = X86ISD::HADD;
11644 case Intrinsic::x86_ssse3_phsub_w_128:
11645 case Intrinsic::x86_ssse3_phsub_d_128:
11646 case Intrinsic::x86_avx2_phsub_w:
11647 case Intrinsic::x86_avx2_phsub_d:
11648 Opcode = X86ISD::HSUB;
11651 return DAG.getNode(Opcode, dl, Op.getValueType(),
11652 Op.getOperand(1), Op.getOperand(2));
11655 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11656 case Intrinsic::x86_sse2_pmaxu_b:
11657 case Intrinsic::x86_sse41_pmaxuw:
11658 case Intrinsic::x86_sse41_pmaxud:
11659 case Intrinsic::x86_avx2_pmaxu_b:
11660 case Intrinsic::x86_avx2_pmaxu_w:
11661 case Intrinsic::x86_avx2_pmaxu_d:
11662 case Intrinsic::x86_sse2_pminu_b:
11663 case Intrinsic::x86_sse41_pminuw:
11664 case Intrinsic::x86_sse41_pminud:
11665 case Intrinsic::x86_avx2_pminu_b:
11666 case Intrinsic::x86_avx2_pminu_w:
11667 case Intrinsic::x86_avx2_pminu_d:
11668 case Intrinsic::x86_sse41_pmaxsb:
11669 case Intrinsic::x86_sse2_pmaxs_w:
11670 case Intrinsic::x86_sse41_pmaxsd:
11671 case Intrinsic::x86_avx2_pmaxs_b:
11672 case Intrinsic::x86_avx2_pmaxs_w:
11673 case Intrinsic::x86_avx2_pmaxs_d:
11674 case Intrinsic::x86_sse41_pminsb:
11675 case Intrinsic::x86_sse2_pmins_w:
11676 case Intrinsic::x86_sse41_pminsd:
11677 case Intrinsic::x86_avx2_pmins_b:
11678 case Intrinsic::x86_avx2_pmins_w:
11679 case Intrinsic::x86_avx2_pmins_d: {
11682 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11683 case Intrinsic::x86_sse2_pmaxu_b:
11684 case Intrinsic::x86_sse41_pmaxuw:
11685 case Intrinsic::x86_sse41_pmaxud:
11686 case Intrinsic::x86_avx2_pmaxu_b:
11687 case Intrinsic::x86_avx2_pmaxu_w:
11688 case Intrinsic::x86_avx2_pmaxu_d:
11689 Opcode = X86ISD::UMAX;
11691 case Intrinsic::x86_sse2_pminu_b:
11692 case Intrinsic::x86_sse41_pminuw:
11693 case Intrinsic::x86_sse41_pminud:
11694 case Intrinsic::x86_avx2_pminu_b:
11695 case Intrinsic::x86_avx2_pminu_w:
11696 case Intrinsic::x86_avx2_pminu_d:
11697 Opcode = X86ISD::UMIN;
11699 case Intrinsic::x86_sse41_pmaxsb:
11700 case Intrinsic::x86_sse2_pmaxs_w:
11701 case Intrinsic::x86_sse41_pmaxsd:
11702 case Intrinsic::x86_avx2_pmaxs_b:
11703 case Intrinsic::x86_avx2_pmaxs_w:
11704 case Intrinsic::x86_avx2_pmaxs_d:
11705 Opcode = X86ISD::SMAX;
11707 case Intrinsic::x86_sse41_pminsb:
11708 case Intrinsic::x86_sse2_pmins_w:
11709 case Intrinsic::x86_sse41_pminsd:
11710 case Intrinsic::x86_avx2_pmins_b:
11711 case Intrinsic::x86_avx2_pmins_w:
11712 case Intrinsic::x86_avx2_pmins_d:
11713 Opcode = X86ISD::SMIN;
11716 return DAG.getNode(Opcode, dl, Op.getValueType(),
11717 Op.getOperand(1), Op.getOperand(2));
11720 // SSE/SSE2/AVX floating point max/min intrinsics.
11721 case Intrinsic::x86_sse_max_ps:
11722 case Intrinsic::x86_sse2_max_pd:
11723 case Intrinsic::x86_avx_max_ps_256:
11724 case Intrinsic::x86_avx_max_pd_256:
11725 case Intrinsic::x86_sse_min_ps:
11726 case Intrinsic::x86_sse2_min_pd:
11727 case Intrinsic::x86_avx_min_ps_256:
11728 case Intrinsic::x86_avx_min_pd_256: {
11731 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11732 case Intrinsic::x86_sse_max_ps:
11733 case Intrinsic::x86_sse2_max_pd:
11734 case Intrinsic::x86_avx_max_ps_256:
11735 case Intrinsic::x86_avx_max_pd_256:
11736 Opcode = X86ISD::FMAX;
11738 case Intrinsic::x86_sse_min_ps:
11739 case Intrinsic::x86_sse2_min_pd:
11740 case Intrinsic::x86_avx_min_ps_256:
11741 case Intrinsic::x86_avx_min_pd_256:
11742 Opcode = X86ISD::FMIN;
11745 return DAG.getNode(Opcode, dl, Op.getValueType(),
11746 Op.getOperand(1), Op.getOperand(2));
11749 // AVX2 variable shift intrinsics
11750 case Intrinsic::x86_avx2_psllv_d:
11751 case Intrinsic::x86_avx2_psllv_q:
11752 case Intrinsic::x86_avx2_psllv_d_256:
11753 case Intrinsic::x86_avx2_psllv_q_256:
11754 case Intrinsic::x86_avx2_psrlv_d:
11755 case Intrinsic::x86_avx2_psrlv_q:
11756 case Intrinsic::x86_avx2_psrlv_d_256:
11757 case Intrinsic::x86_avx2_psrlv_q_256:
11758 case Intrinsic::x86_avx2_psrav_d:
11759 case Intrinsic::x86_avx2_psrav_d_256: {
11762 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11763 case Intrinsic::x86_avx2_psllv_d:
11764 case Intrinsic::x86_avx2_psllv_q:
11765 case Intrinsic::x86_avx2_psllv_d_256:
11766 case Intrinsic::x86_avx2_psllv_q_256:
11769 case Intrinsic::x86_avx2_psrlv_d:
11770 case Intrinsic::x86_avx2_psrlv_q:
11771 case Intrinsic::x86_avx2_psrlv_d_256:
11772 case Intrinsic::x86_avx2_psrlv_q_256:
11775 case Intrinsic::x86_avx2_psrav_d:
11776 case Intrinsic::x86_avx2_psrav_d_256:
11780 return DAG.getNode(Opcode, dl, Op.getValueType(),
11781 Op.getOperand(1), Op.getOperand(2));
11784 case Intrinsic::x86_ssse3_pshuf_b_128:
11785 case Intrinsic::x86_avx2_pshuf_b:
11786 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11787 Op.getOperand(1), Op.getOperand(2));
11789 case Intrinsic::x86_ssse3_psign_b_128:
11790 case Intrinsic::x86_ssse3_psign_w_128:
11791 case Intrinsic::x86_ssse3_psign_d_128:
11792 case Intrinsic::x86_avx2_psign_b:
11793 case Intrinsic::x86_avx2_psign_w:
11794 case Intrinsic::x86_avx2_psign_d:
11795 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11796 Op.getOperand(1), Op.getOperand(2));
11798 case Intrinsic::x86_sse41_insertps:
11799 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11800 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11802 case Intrinsic::x86_avx_vperm2f128_ps_256:
11803 case Intrinsic::x86_avx_vperm2f128_pd_256:
11804 case Intrinsic::x86_avx_vperm2f128_si_256:
11805 case Intrinsic::x86_avx2_vperm2i128:
11806 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11807 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11809 case Intrinsic::x86_avx2_permd:
11810 case Intrinsic::x86_avx2_permps:
11811 // Operands intentionally swapped. Mask is last operand to intrinsic,
11812 // but second operand for node/instruction.
11813 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11814 Op.getOperand(2), Op.getOperand(1));
11816 case Intrinsic::x86_sse_sqrt_ps:
11817 case Intrinsic::x86_sse2_sqrt_pd:
11818 case Intrinsic::x86_avx_sqrt_ps_256:
11819 case Intrinsic::x86_avx_sqrt_pd_256:
11820 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11822 // ptest and testp intrinsics. The intrinsic these come from are designed to
11823 // return an integer value, not just an instruction so lower it to the ptest
11824 // or testp pattern and a setcc for the result.
11825 case Intrinsic::x86_sse41_ptestz:
11826 case Intrinsic::x86_sse41_ptestc:
11827 case Intrinsic::x86_sse41_ptestnzc:
11828 case Intrinsic::x86_avx_ptestz_256:
11829 case Intrinsic::x86_avx_ptestc_256:
11830 case Intrinsic::x86_avx_ptestnzc_256:
11831 case Intrinsic::x86_avx_vtestz_ps:
11832 case Intrinsic::x86_avx_vtestc_ps:
11833 case Intrinsic::x86_avx_vtestnzc_ps:
11834 case Intrinsic::x86_avx_vtestz_pd:
11835 case Intrinsic::x86_avx_vtestc_pd:
11836 case Intrinsic::x86_avx_vtestnzc_pd:
11837 case Intrinsic::x86_avx_vtestz_ps_256:
11838 case Intrinsic::x86_avx_vtestc_ps_256:
11839 case Intrinsic::x86_avx_vtestnzc_ps_256:
11840 case Intrinsic::x86_avx_vtestz_pd_256:
11841 case Intrinsic::x86_avx_vtestc_pd_256:
11842 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11843 bool IsTestPacked = false;
11846 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11847 case Intrinsic::x86_avx_vtestz_ps:
11848 case Intrinsic::x86_avx_vtestz_pd:
11849 case Intrinsic::x86_avx_vtestz_ps_256:
11850 case Intrinsic::x86_avx_vtestz_pd_256:
11851 IsTestPacked = true; // Fallthrough
11852 case Intrinsic::x86_sse41_ptestz:
11853 case Intrinsic::x86_avx_ptestz_256:
11855 X86CC = X86::COND_E;
11857 case Intrinsic::x86_avx_vtestc_ps:
11858 case Intrinsic::x86_avx_vtestc_pd:
11859 case Intrinsic::x86_avx_vtestc_ps_256:
11860 case Intrinsic::x86_avx_vtestc_pd_256:
11861 IsTestPacked = true; // Fallthrough
11862 case Intrinsic::x86_sse41_ptestc:
11863 case Intrinsic::x86_avx_ptestc_256:
11865 X86CC = X86::COND_B;
11867 case Intrinsic::x86_avx_vtestnzc_ps:
11868 case Intrinsic::x86_avx_vtestnzc_pd:
11869 case Intrinsic::x86_avx_vtestnzc_ps_256:
11870 case Intrinsic::x86_avx_vtestnzc_pd_256:
11871 IsTestPacked = true; // Fallthrough
11872 case Intrinsic::x86_sse41_ptestnzc:
11873 case Intrinsic::x86_avx_ptestnzc_256:
11875 X86CC = X86::COND_A;
11879 SDValue LHS = Op.getOperand(1);
11880 SDValue RHS = Op.getOperand(2);
11881 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11882 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11883 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11884 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11885 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11887 case Intrinsic::x86_avx512_kortestz_w:
11888 case Intrinsic::x86_avx512_kortestc_w: {
11889 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11890 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11891 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11892 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11893 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11894 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11895 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11898 // SSE/AVX shift intrinsics
11899 case Intrinsic::x86_sse2_psll_w:
11900 case Intrinsic::x86_sse2_psll_d:
11901 case Intrinsic::x86_sse2_psll_q:
11902 case Intrinsic::x86_avx2_psll_w:
11903 case Intrinsic::x86_avx2_psll_d:
11904 case Intrinsic::x86_avx2_psll_q:
11905 case Intrinsic::x86_sse2_psrl_w:
11906 case Intrinsic::x86_sse2_psrl_d:
11907 case Intrinsic::x86_sse2_psrl_q:
11908 case Intrinsic::x86_avx2_psrl_w:
11909 case Intrinsic::x86_avx2_psrl_d:
11910 case Intrinsic::x86_avx2_psrl_q:
11911 case Intrinsic::x86_sse2_psra_w:
11912 case Intrinsic::x86_sse2_psra_d:
11913 case Intrinsic::x86_avx2_psra_w:
11914 case Intrinsic::x86_avx2_psra_d: {
11917 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11918 case Intrinsic::x86_sse2_psll_w:
11919 case Intrinsic::x86_sse2_psll_d:
11920 case Intrinsic::x86_sse2_psll_q:
11921 case Intrinsic::x86_avx2_psll_w:
11922 case Intrinsic::x86_avx2_psll_d:
11923 case Intrinsic::x86_avx2_psll_q:
11924 Opcode = X86ISD::VSHL;
11926 case Intrinsic::x86_sse2_psrl_w:
11927 case Intrinsic::x86_sse2_psrl_d:
11928 case Intrinsic::x86_sse2_psrl_q:
11929 case Intrinsic::x86_avx2_psrl_w:
11930 case Intrinsic::x86_avx2_psrl_d:
11931 case Intrinsic::x86_avx2_psrl_q:
11932 Opcode = X86ISD::VSRL;
11934 case Intrinsic::x86_sse2_psra_w:
11935 case Intrinsic::x86_sse2_psra_d:
11936 case Intrinsic::x86_avx2_psra_w:
11937 case Intrinsic::x86_avx2_psra_d:
11938 Opcode = X86ISD::VSRA;
11941 return DAG.getNode(Opcode, dl, Op.getValueType(),
11942 Op.getOperand(1), Op.getOperand(2));
11945 // SSE/AVX immediate shift intrinsics
11946 case Intrinsic::x86_sse2_pslli_w:
11947 case Intrinsic::x86_sse2_pslli_d:
11948 case Intrinsic::x86_sse2_pslli_q:
11949 case Intrinsic::x86_avx2_pslli_w:
11950 case Intrinsic::x86_avx2_pslli_d:
11951 case Intrinsic::x86_avx2_pslli_q:
11952 case Intrinsic::x86_sse2_psrli_w:
11953 case Intrinsic::x86_sse2_psrli_d:
11954 case Intrinsic::x86_sse2_psrli_q:
11955 case Intrinsic::x86_avx2_psrli_w:
11956 case Intrinsic::x86_avx2_psrli_d:
11957 case Intrinsic::x86_avx2_psrli_q:
11958 case Intrinsic::x86_sse2_psrai_w:
11959 case Intrinsic::x86_sse2_psrai_d:
11960 case Intrinsic::x86_avx2_psrai_w:
11961 case Intrinsic::x86_avx2_psrai_d: {
11964 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11965 case Intrinsic::x86_sse2_pslli_w:
11966 case Intrinsic::x86_sse2_pslli_d:
11967 case Intrinsic::x86_sse2_pslli_q:
11968 case Intrinsic::x86_avx2_pslli_w:
11969 case Intrinsic::x86_avx2_pslli_d:
11970 case Intrinsic::x86_avx2_pslli_q:
11971 Opcode = X86ISD::VSHLI;
11973 case Intrinsic::x86_sse2_psrli_w:
11974 case Intrinsic::x86_sse2_psrli_d:
11975 case Intrinsic::x86_sse2_psrli_q:
11976 case Intrinsic::x86_avx2_psrli_w:
11977 case Intrinsic::x86_avx2_psrli_d:
11978 case Intrinsic::x86_avx2_psrli_q:
11979 Opcode = X86ISD::VSRLI;
11981 case Intrinsic::x86_sse2_psrai_w:
11982 case Intrinsic::x86_sse2_psrai_d:
11983 case Intrinsic::x86_avx2_psrai_w:
11984 case Intrinsic::x86_avx2_psrai_d:
11985 Opcode = X86ISD::VSRAI;
11988 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11989 Op.getOperand(1), Op.getOperand(2), DAG);
11992 case Intrinsic::x86_sse42_pcmpistria128:
11993 case Intrinsic::x86_sse42_pcmpestria128:
11994 case Intrinsic::x86_sse42_pcmpistric128:
11995 case Intrinsic::x86_sse42_pcmpestric128:
11996 case Intrinsic::x86_sse42_pcmpistrio128:
11997 case Intrinsic::x86_sse42_pcmpestrio128:
11998 case Intrinsic::x86_sse42_pcmpistris128:
11999 case Intrinsic::x86_sse42_pcmpestris128:
12000 case Intrinsic::x86_sse42_pcmpistriz128:
12001 case Intrinsic::x86_sse42_pcmpestriz128: {
12005 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12006 case Intrinsic::x86_sse42_pcmpistria128:
12007 Opcode = X86ISD::PCMPISTRI;
12008 X86CC = X86::COND_A;
12010 case Intrinsic::x86_sse42_pcmpestria128:
12011 Opcode = X86ISD::PCMPESTRI;
12012 X86CC = X86::COND_A;
12014 case Intrinsic::x86_sse42_pcmpistric128:
12015 Opcode = X86ISD::PCMPISTRI;
12016 X86CC = X86::COND_B;
12018 case Intrinsic::x86_sse42_pcmpestric128:
12019 Opcode = X86ISD::PCMPESTRI;
12020 X86CC = X86::COND_B;
12022 case Intrinsic::x86_sse42_pcmpistrio128:
12023 Opcode = X86ISD::PCMPISTRI;
12024 X86CC = X86::COND_O;
12026 case Intrinsic::x86_sse42_pcmpestrio128:
12027 Opcode = X86ISD::PCMPESTRI;
12028 X86CC = X86::COND_O;
12030 case Intrinsic::x86_sse42_pcmpistris128:
12031 Opcode = X86ISD::PCMPISTRI;
12032 X86CC = X86::COND_S;
12034 case Intrinsic::x86_sse42_pcmpestris128:
12035 Opcode = X86ISD::PCMPESTRI;
12036 X86CC = X86::COND_S;
12038 case Intrinsic::x86_sse42_pcmpistriz128:
12039 Opcode = X86ISD::PCMPISTRI;
12040 X86CC = X86::COND_E;
12042 case Intrinsic::x86_sse42_pcmpestriz128:
12043 Opcode = X86ISD::PCMPESTRI;
12044 X86CC = X86::COND_E;
12047 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12048 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12049 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12050 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12051 DAG.getConstant(X86CC, MVT::i8),
12052 SDValue(PCMP.getNode(), 1));
12053 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12056 case Intrinsic::x86_sse42_pcmpistri128:
12057 case Intrinsic::x86_sse42_pcmpestri128: {
12059 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12060 Opcode = X86ISD::PCMPISTRI;
12062 Opcode = X86ISD::PCMPESTRI;
12064 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12065 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12066 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
12068 case Intrinsic::x86_fma_vfmadd_ps:
12069 case Intrinsic::x86_fma_vfmadd_pd:
12070 case Intrinsic::x86_fma_vfmsub_ps:
12071 case Intrinsic::x86_fma_vfmsub_pd:
12072 case Intrinsic::x86_fma_vfnmadd_ps:
12073 case Intrinsic::x86_fma_vfnmadd_pd:
12074 case Intrinsic::x86_fma_vfnmsub_ps:
12075 case Intrinsic::x86_fma_vfnmsub_pd:
12076 case Intrinsic::x86_fma_vfmaddsub_ps:
12077 case Intrinsic::x86_fma_vfmaddsub_pd:
12078 case Intrinsic::x86_fma_vfmsubadd_ps:
12079 case Intrinsic::x86_fma_vfmsubadd_pd:
12080 case Intrinsic::x86_fma_vfmadd_ps_256:
12081 case Intrinsic::x86_fma_vfmadd_pd_256:
12082 case Intrinsic::x86_fma_vfmsub_ps_256:
12083 case Intrinsic::x86_fma_vfmsub_pd_256:
12084 case Intrinsic::x86_fma_vfnmadd_ps_256:
12085 case Intrinsic::x86_fma_vfnmadd_pd_256:
12086 case Intrinsic::x86_fma_vfnmsub_ps_256:
12087 case Intrinsic::x86_fma_vfnmsub_pd_256:
12088 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12089 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12090 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12091 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12092 case Intrinsic::x86_fma_vfmadd_ps_512:
12093 case Intrinsic::x86_fma_vfmadd_pd_512:
12094 case Intrinsic::x86_fma_vfmsub_ps_512:
12095 case Intrinsic::x86_fma_vfmsub_pd_512:
12096 case Intrinsic::x86_fma_vfnmadd_ps_512:
12097 case Intrinsic::x86_fma_vfnmadd_pd_512:
12098 case Intrinsic::x86_fma_vfnmsub_ps_512:
12099 case Intrinsic::x86_fma_vfnmsub_pd_512:
12100 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12101 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12102 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12103 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12106 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12107 case Intrinsic::x86_fma_vfmadd_ps:
12108 case Intrinsic::x86_fma_vfmadd_pd:
12109 case Intrinsic::x86_fma_vfmadd_ps_256:
12110 case Intrinsic::x86_fma_vfmadd_pd_256:
12111 case Intrinsic::x86_fma_vfmadd_ps_512:
12112 case Intrinsic::x86_fma_vfmadd_pd_512:
12113 Opc = X86ISD::FMADD;
12115 case Intrinsic::x86_fma_vfmsub_ps:
12116 case Intrinsic::x86_fma_vfmsub_pd:
12117 case Intrinsic::x86_fma_vfmsub_ps_256:
12118 case Intrinsic::x86_fma_vfmsub_pd_256:
12119 case Intrinsic::x86_fma_vfmsub_ps_512:
12120 case Intrinsic::x86_fma_vfmsub_pd_512:
12121 Opc = X86ISD::FMSUB;
12123 case Intrinsic::x86_fma_vfnmadd_ps:
12124 case Intrinsic::x86_fma_vfnmadd_pd:
12125 case Intrinsic::x86_fma_vfnmadd_ps_256:
12126 case Intrinsic::x86_fma_vfnmadd_pd_256:
12127 case Intrinsic::x86_fma_vfnmadd_ps_512:
12128 case Intrinsic::x86_fma_vfnmadd_pd_512:
12129 Opc = X86ISD::FNMADD;
12131 case Intrinsic::x86_fma_vfnmsub_ps:
12132 case Intrinsic::x86_fma_vfnmsub_pd:
12133 case Intrinsic::x86_fma_vfnmsub_ps_256:
12134 case Intrinsic::x86_fma_vfnmsub_pd_256:
12135 case Intrinsic::x86_fma_vfnmsub_ps_512:
12136 case Intrinsic::x86_fma_vfnmsub_pd_512:
12137 Opc = X86ISD::FNMSUB;
12139 case Intrinsic::x86_fma_vfmaddsub_ps:
12140 case Intrinsic::x86_fma_vfmaddsub_pd:
12141 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12142 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12143 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12144 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12145 Opc = X86ISD::FMADDSUB;
12147 case Intrinsic::x86_fma_vfmsubadd_ps:
12148 case Intrinsic::x86_fma_vfmsubadd_pd:
12149 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12150 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12151 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12152 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12153 Opc = X86ISD::FMSUBADD;
12157 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12158 Op.getOperand(2), Op.getOperand(3));
12163 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12164 SDValue Base, SDValue Index,
12165 SDValue ScaleOp, SDValue Chain,
12166 const X86Subtarget * Subtarget) {
12168 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12169 assert(C && "Invalid scale type");
12170 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12171 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12172 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12173 Index.getSimpleValueType().getVectorNumElements());
12174 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12175 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12176 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12177 SDValue Segment = DAG.getRegister(0, MVT::i32);
12178 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12179 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12180 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12181 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12184 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12185 SDValue Src, SDValue Mask, SDValue Base,
12186 SDValue Index, SDValue ScaleOp, SDValue Chain,
12187 const X86Subtarget * Subtarget) {
12189 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12190 assert(C && "Invalid scale type");
12191 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12192 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12193 Index.getSimpleValueType().getVectorNumElements());
12194 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12195 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12196 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12197 SDValue Segment = DAG.getRegister(0, MVT::i32);
12198 if (Src.getOpcode() == ISD::UNDEF)
12199 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12200 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12201 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12202 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12203 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12206 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12207 SDValue Src, SDValue Base, SDValue Index,
12208 SDValue ScaleOp, SDValue Chain) {
12210 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12211 assert(C && "Invalid scale type");
12212 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12213 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12214 SDValue Segment = DAG.getRegister(0, MVT::i32);
12215 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12216 Index.getSimpleValueType().getVectorNumElements());
12217 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12218 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12219 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12220 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12221 return SDValue(Res, 1);
12224 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12225 SDValue Src, SDValue Mask, SDValue Base,
12226 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12228 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12229 assert(C && "Invalid scale type");
12230 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12231 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12232 SDValue Segment = DAG.getRegister(0, MVT::i32);
12233 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12234 Index.getSimpleValueType().getVectorNumElements());
12235 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12236 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12237 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12238 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12239 return SDValue(Res, 1);
12242 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12243 SelectionDAG &DAG) {
12245 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12247 default: return SDValue(); // Don't custom lower most intrinsics.
12249 // RDRAND/RDSEED intrinsics.
12250 case Intrinsic::x86_rdrand_16:
12251 case Intrinsic::x86_rdrand_32:
12252 case Intrinsic::x86_rdrand_64:
12253 case Intrinsic::x86_rdseed_16:
12254 case Intrinsic::x86_rdseed_32:
12255 case Intrinsic::x86_rdseed_64: {
12256 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12257 IntNo == Intrinsic::x86_rdseed_32 ||
12258 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12260 // Emit the node with the right value type.
12261 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12262 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12264 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12265 // Otherwise return the value from Rand, which is always 0, casted to i32.
12266 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12267 DAG.getConstant(1, Op->getValueType(1)),
12268 DAG.getConstant(X86::COND_B, MVT::i32),
12269 SDValue(Result.getNode(), 1) };
12270 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12271 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12272 Ops, array_lengthof(Ops));
12274 // Return { result, isValid, chain }.
12275 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12276 SDValue(Result.getNode(), 2));
12278 //int_gather(index, base, scale);
12279 case Intrinsic::x86_avx512_gather_qpd_512:
12280 case Intrinsic::x86_avx512_gather_qps_512:
12281 case Intrinsic::x86_avx512_gather_dpd_512:
12282 case Intrinsic::x86_avx512_gather_qpi_512:
12283 case Intrinsic::x86_avx512_gather_qpq_512:
12284 case Intrinsic::x86_avx512_gather_dpq_512:
12285 case Intrinsic::x86_avx512_gather_dps_512:
12286 case Intrinsic::x86_avx512_gather_dpi_512: {
12289 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12290 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12291 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12292 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12293 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12294 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12295 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12296 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12297 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12299 SDValue Chain = Op.getOperand(0);
12300 SDValue Index = Op.getOperand(2);
12301 SDValue Base = Op.getOperand(3);
12302 SDValue Scale = Op.getOperand(4);
12303 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12305 //int_gather_mask(v1, mask, index, base, scale);
12306 case Intrinsic::x86_avx512_gather_qps_mask_512:
12307 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12308 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12309 case Intrinsic::x86_avx512_gather_dps_mask_512:
12310 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12311 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12312 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12313 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12316 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12317 case Intrinsic::x86_avx512_gather_qps_mask_512:
12318 Opc = X86::VGATHERQPSZrm; break;
12319 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12320 Opc = X86::VGATHERQPDZrm; break;
12321 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12322 Opc = X86::VGATHERDPDZrm; break;
12323 case Intrinsic::x86_avx512_gather_dps_mask_512:
12324 Opc = X86::VGATHERDPSZrm; break;
12325 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12326 Opc = X86::VPGATHERQDZrm; break;
12327 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12328 Opc = X86::VPGATHERQQZrm; break;
12329 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12330 Opc = X86::VPGATHERDDZrm; break;
12331 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12332 Opc = X86::VPGATHERDQZrm; break;
12334 SDValue Chain = Op.getOperand(0);
12335 SDValue Src = Op.getOperand(2);
12336 SDValue Mask = Op.getOperand(3);
12337 SDValue Index = Op.getOperand(4);
12338 SDValue Base = Op.getOperand(5);
12339 SDValue Scale = Op.getOperand(6);
12340 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12343 //int_scatter(base, index, v1, scale);
12344 case Intrinsic::x86_avx512_scatter_qpd_512:
12345 case Intrinsic::x86_avx512_scatter_qps_512:
12346 case Intrinsic::x86_avx512_scatter_dpd_512:
12347 case Intrinsic::x86_avx512_scatter_qpi_512:
12348 case Intrinsic::x86_avx512_scatter_qpq_512:
12349 case Intrinsic::x86_avx512_scatter_dpq_512:
12350 case Intrinsic::x86_avx512_scatter_dps_512:
12351 case Intrinsic::x86_avx512_scatter_dpi_512: {
12354 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12355 case Intrinsic::x86_avx512_scatter_qpd_512:
12356 Opc = X86::VSCATTERQPDZmr; break;
12357 case Intrinsic::x86_avx512_scatter_qps_512:
12358 Opc = X86::VSCATTERQPSZmr; break;
12359 case Intrinsic::x86_avx512_scatter_dpd_512:
12360 Opc = X86::VSCATTERDPDZmr; break;
12361 case Intrinsic::x86_avx512_scatter_dps_512:
12362 Opc = X86::VSCATTERDPSZmr; break;
12363 case Intrinsic::x86_avx512_scatter_qpi_512:
12364 Opc = X86::VPSCATTERQDZmr; break;
12365 case Intrinsic::x86_avx512_scatter_qpq_512:
12366 Opc = X86::VPSCATTERQQZmr; break;
12367 case Intrinsic::x86_avx512_scatter_dpq_512:
12368 Opc = X86::VPSCATTERDQZmr; break;
12369 case Intrinsic::x86_avx512_scatter_dpi_512:
12370 Opc = X86::VPSCATTERDDZmr; break;
12372 SDValue Chain = Op.getOperand(0);
12373 SDValue Base = Op.getOperand(2);
12374 SDValue Index = Op.getOperand(3);
12375 SDValue Src = Op.getOperand(4);
12376 SDValue Scale = Op.getOperand(5);
12377 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12379 //int_scatter_mask(base, mask, index, v1, scale);
12380 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12381 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12382 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12383 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12384 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12385 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12386 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12387 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12390 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12391 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12392 Opc = X86::VSCATTERQPDZmr; break;
12393 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12394 Opc = X86::VSCATTERQPSZmr; break;
12395 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12396 Opc = X86::VSCATTERDPDZmr; break;
12397 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12398 Opc = X86::VSCATTERDPSZmr; break;
12399 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12400 Opc = X86::VPSCATTERQDZmr; break;
12401 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12402 Opc = X86::VPSCATTERQQZmr; break;
12403 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12404 Opc = X86::VPSCATTERDQZmr; break;
12405 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12406 Opc = X86::VPSCATTERDDZmr; break;
12408 SDValue Chain = Op.getOperand(0);
12409 SDValue Base = Op.getOperand(2);
12410 SDValue Mask = Op.getOperand(3);
12411 SDValue Index = Op.getOperand(4);
12412 SDValue Src = Op.getOperand(5);
12413 SDValue Scale = Op.getOperand(6);
12414 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12416 // XTEST intrinsics.
12417 case Intrinsic::x86_xtest: {
12418 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12419 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12420 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12421 DAG.getConstant(X86::COND_NE, MVT::i8),
12423 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12424 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12425 Ret, SDValue(InTrans.getNode(), 1));
12430 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12431 SelectionDAG &DAG) const {
12432 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12433 MFI->setReturnAddressIsTaken(true);
12435 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12438 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12440 EVT PtrVT = getPointerTy();
12443 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12444 const X86RegisterInfo *RegInfo =
12445 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12446 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12447 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12448 DAG.getNode(ISD::ADD, dl, PtrVT,
12449 FrameAddr, Offset),
12450 MachinePointerInfo(), false, false, false, 0);
12453 // Just load the return address.
12454 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12455 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12456 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12459 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12460 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12461 MFI->setFrameAddressIsTaken(true);
12463 EVT VT = Op.getValueType();
12464 SDLoc dl(Op); // FIXME probably not meaningful
12465 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12466 const X86RegisterInfo *RegInfo =
12467 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12468 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12469 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12470 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12471 "Invalid Frame Register!");
12472 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12474 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12475 MachinePointerInfo(),
12476 false, false, false, 0);
12480 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12481 SelectionDAG &DAG) const {
12482 const X86RegisterInfo *RegInfo =
12483 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12484 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12487 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12488 SDValue Chain = Op.getOperand(0);
12489 SDValue Offset = Op.getOperand(1);
12490 SDValue Handler = Op.getOperand(2);
12493 EVT PtrVT = getPointerTy();
12494 const X86RegisterInfo *RegInfo =
12495 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12496 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12497 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12498 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12499 "Invalid Frame Register!");
12500 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12501 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12503 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12504 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12505 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12506 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12508 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12510 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12511 DAG.getRegister(StoreAddrReg, PtrVT));
12514 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12515 SelectionDAG &DAG) const {
12517 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12518 DAG.getVTList(MVT::i32, MVT::Other),
12519 Op.getOperand(0), Op.getOperand(1));
12522 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12523 SelectionDAG &DAG) const {
12525 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12526 Op.getOperand(0), Op.getOperand(1));
12529 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12530 return Op.getOperand(0);
12533 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12534 SelectionDAG &DAG) const {
12535 SDValue Root = Op.getOperand(0);
12536 SDValue Trmp = Op.getOperand(1); // trampoline
12537 SDValue FPtr = Op.getOperand(2); // nested function
12538 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12541 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12542 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12544 if (Subtarget->is64Bit()) {
12545 SDValue OutChains[6];
12547 // Large code-model.
12548 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12549 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12551 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12552 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12554 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12556 // Load the pointer to the nested function into R11.
12557 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12558 SDValue Addr = Trmp;
12559 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12560 Addr, MachinePointerInfo(TrmpAddr),
12563 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12564 DAG.getConstant(2, MVT::i64));
12565 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12566 MachinePointerInfo(TrmpAddr, 2),
12569 // Load the 'nest' parameter value into R10.
12570 // R10 is specified in X86CallingConv.td
12571 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12572 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12573 DAG.getConstant(10, MVT::i64));
12574 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12575 Addr, MachinePointerInfo(TrmpAddr, 10),
12578 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12579 DAG.getConstant(12, MVT::i64));
12580 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12581 MachinePointerInfo(TrmpAddr, 12),
12584 // Jump to the nested function.
12585 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12586 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12587 DAG.getConstant(20, MVT::i64));
12588 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12589 Addr, MachinePointerInfo(TrmpAddr, 20),
12592 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12593 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12594 DAG.getConstant(22, MVT::i64));
12595 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12596 MachinePointerInfo(TrmpAddr, 22),
12599 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12601 const Function *Func =
12602 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12603 CallingConv::ID CC = Func->getCallingConv();
12608 llvm_unreachable("Unsupported calling convention");
12609 case CallingConv::C:
12610 case CallingConv::X86_StdCall: {
12611 // Pass 'nest' parameter in ECX.
12612 // Must be kept in sync with X86CallingConv.td
12613 NestReg = X86::ECX;
12615 // Check that ECX wasn't needed by an 'inreg' parameter.
12616 FunctionType *FTy = Func->getFunctionType();
12617 const AttributeSet &Attrs = Func->getAttributes();
12619 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12620 unsigned InRegCount = 0;
12623 for (FunctionType::param_iterator I = FTy->param_begin(),
12624 E = FTy->param_end(); I != E; ++I, ++Idx)
12625 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12626 // FIXME: should only count parameters that are lowered to integers.
12627 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12629 if (InRegCount > 2) {
12630 report_fatal_error("Nest register in use - reduce number of inreg"
12636 case CallingConv::X86_FastCall:
12637 case CallingConv::X86_ThisCall:
12638 case CallingConv::Fast:
12639 // Pass 'nest' parameter in EAX.
12640 // Must be kept in sync with X86CallingConv.td
12641 NestReg = X86::EAX;
12645 SDValue OutChains[4];
12646 SDValue Addr, Disp;
12648 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12649 DAG.getConstant(10, MVT::i32));
12650 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12652 // This is storing the opcode for MOV32ri.
12653 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12654 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12655 OutChains[0] = DAG.getStore(Root, dl,
12656 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12657 Trmp, MachinePointerInfo(TrmpAddr),
12660 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12661 DAG.getConstant(1, MVT::i32));
12662 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12663 MachinePointerInfo(TrmpAddr, 1),
12666 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12667 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12668 DAG.getConstant(5, MVT::i32));
12669 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12670 MachinePointerInfo(TrmpAddr, 5),
12673 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12674 DAG.getConstant(6, MVT::i32));
12675 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12676 MachinePointerInfo(TrmpAddr, 6),
12679 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12683 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12684 SelectionDAG &DAG) const {
12686 The rounding mode is in bits 11:10 of FPSR, and has the following
12688 00 Round to nearest
12693 FLT_ROUNDS, on the other hand, expects the following:
12700 To perform the conversion, we do:
12701 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12704 MachineFunction &MF = DAG.getMachineFunction();
12705 const TargetMachine &TM = MF.getTarget();
12706 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12707 unsigned StackAlignment = TFI.getStackAlignment();
12708 MVT VT = Op.getSimpleValueType();
12711 // Save FP Control Word to stack slot
12712 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12713 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12715 MachineMemOperand *MMO =
12716 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12717 MachineMemOperand::MOStore, 2, 2);
12719 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12720 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12721 DAG.getVTList(MVT::Other),
12722 Ops, array_lengthof(Ops), MVT::i16,
12725 // Load FP Control Word from stack slot
12726 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12727 MachinePointerInfo(), false, false, false, 0);
12729 // Transform as necessary
12731 DAG.getNode(ISD::SRL, DL, MVT::i16,
12732 DAG.getNode(ISD::AND, DL, MVT::i16,
12733 CWD, DAG.getConstant(0x800, MVT::i16)),
12734 DAG.getConstant(11, MVT::i8));
12736 DAG.getNode(ISD::SRL, DL, MVT::i16,
12737 DAG.getNode(ISD::AND, DL, MVT::i16,
12738 CWD, DAG.getConstant(0x400, MVT::i16)),
12739 DAG.getConstant(9, MVT::i8));
12742 DAG.getNode(ISD::AND, DL, MVT::i16,
12743 DAG.getNode(ISD::ADD, DL, MVT::i16,
12744 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12745 DAG.getConstant(1, MVT::i16)),
12746 DAG.getConstant(3, MVT::i16));
12748 return DAG.getNode((VT.getSizeInBits() < 16 ?
12749 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12752 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12753 MVT VT = Op.getSimpleValueType();
12755 unsigned NumBits = VT.getSizeInBits();
12758 Op = Op.getOperand(0);
12759 if (VT == MVT::i8) {
12760 // Zero extend to i32 since there is not an i8 bsr.
12762 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12765 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12766 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12767 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12769 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12772 DAG.getConstant(NumBits+NumBits-1, OpVT),
12773 DAG.getConstant(X86::COND_E, MVT::i8),
12776 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12778 // Finally xor with NumBits-1.
12779 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12782 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12786 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12787 MVT VT = Op.getSimpleValueType();
12789 unsigned NumBits = VT.getSizeInBits();
12792 Op = Op.getOperand(0);
12793 if (VT == MVT::i8) {
12794 // Zero extend to i32 since there is not an i8 bsr.
12796 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12799 // Issue a bsr (scan bits in reverse).
12800 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12801 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12803 // And xor with NumBits-1.
12804 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12807 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12811 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12812 MVT VT = Op.getSimpleValueType();
12813 unsigned NumBits = VT.getSizeInBits();
12815 Op = Op.getOperand(0);
12817 // Issue a bsf (scan bits forward) which also sets EFLAGS.
12818 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12819 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12821 // If src is zero (i.e. bsf sets ZF), returns NumBits.
12824 DAG.getConstant(NumBits, VT),
12825 DAG.getConstant(X86::COND_E, MVT::i8),
12828 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12831 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12832 // ones, and then concatenate the result back.
12833 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12834 MVT VT = Op.getSimpleValueType();
12836 assert(VT.is256BitVector() && VT.isInteger() &&
12837 "Unsupported value type for operation");
12839 unsigned NumElems = VT.getVectorNumElements();
12842 // Extract the LHS vectors
12843 SDValue LHS = Op.getOperand(0);
12844 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12845 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12847 // Extract the RHS vectors
12848 SDValue RHS = Op.getOperand(1);
12849 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12850 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12852 MVT EltVT = VT.getVectorElementType();
12853 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12855 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12856 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12857 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12860 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12861 assert(Op.getSimpleValueType().is256BitVector() &&
12862 Op.getSimpleValueType().isInteger() &&
12863 "Only handle AVX 256-bit vector integer operation");
12864 return Lower256IntArith(Op, DAG);
12867 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12868 assert(Op.getSimpleValueType().is256BitVector() &&
12869 Op.getSimpleValueType().isInteger() &&
12870 "Only handle AVX 256-bit vector integer operation");
12871 return Lower256IntArith(Op, DAG);
12874 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12875 SelectionDAG &DAG) {
12877 MVT VT = Op.getSimpleValueType();
12879 // Decompose 256-bit ops into smaller 128-bit ops.
12880 if (VT.is256BitVector() && !Subtarget->hasInt256())
12881 return Lower256IntArith(Op, DAG);
12883 SDValue A = Op.getOperand(0);
12884 SDValue B = Op.getOperand(1);
12886 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12887 if (VT == MVT::v4i32) {
12888 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12889 "Should not custom lower when pmuldq is available!");
12891 // Extract the odd parts.
12892 static const int UnpackMask[] = { 1, -1, 3, -1 };
12893 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12894 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12896 // Multiply the even parts.
12897 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12898 // Now multiply odd parts.
12899 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12901 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12902 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12904 // Merge the two vectors back together with a shuffle. This expands into 2
12906 static const int ShufMask[] = { 0, 4, 2, 6 };
12907 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12910 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12911 "Only know how to lower V2I64/V4I64/V8I64 multiply");
12913 // Ahi = psrlqi(a, 32);
12914 // Bhi = psrlqi(b, 32);
12916 // AloBlo = pmuludq(a, b);
12917 // AloBhi = pmuludq(a, Bhi);
12918 // AhiBlo = pmuludq(Ahi, b);
12920 // AloBhi = psllqi(AloBhi, 32);
12921 // AhiBlo = psllqi(AhiBlo, 32);
12922 // return AloBlo + AloBhi + AhiBlo;
12924 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12925 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12927 // Bit cast to 32-bit vectors for MULUDQ
12928 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12929 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12930 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12931 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12932 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12933 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12935 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12936 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12937 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12939 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12940 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12942 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12943 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12946 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12947 MVT VT = Op.getSimpleValueType();
12948 MVT EltTy = VT.getVectorElementType();
12949 unsigned NumElts = VT.getVectorNumElements();
12950 SDValue N0 = Op.getOperand(0);
12953 // Lower sdiv X, pow2-const.
12954 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12958 APInt SplatValue, SplatUndef;
12959 unsigned SplatBitSize;
12961 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12963 EltTy.getSizeInBits() < SplatBitSize)
12966 if ((SplatValue != 0) &&
12967 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12968 unsigned Lg2 = SplatValue.countTrailingZeros();
12969 // Splat the sign bit.
12970 SmallVector<SDValue, 16> Sz(NumElts,
12971 DAG.getConstant(EltTy.getSizeInBits() - 1,
12973 SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12974 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12976 // Add (N0 < 0) ? abs2 - 1 : 0;
12977 SmallVector<SDValue, 16> Amt(NumElts,
12978 DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12980 SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12981 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12983 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12984 SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12985 SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12986 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12989 // If we're dividing by a positive value, we're done. Otherwise, we must
12990 // negate the result.
12991 if (SplatValue.isNonNegative())
12994 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12995 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12996 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
13001 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13002 const X86Subtarget *Subtarget) {
13003 MVT VT = Op.getSimpleValueType();
13005 SDValue R = Op.getOperand(0);
13006 SDValue Amt = Op.getOperand(1);
13008 // Optimize shl/srl/sra with constant shift amount.
13009 if (isSplatVector(Amt.getNode())) {
13010 SDValue SclrAmt = Amt->getOperand(0);
13011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13012 uint64_t ShiftAmt = C->getZExtValue();
13014 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13015 (Subtarget->hasInt256() &&
13016 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13017 (Subtarget->hasAVX512() &&
13018 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13019 if (Op.getOpcode() == ISD::SHL)
13020 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13022 if (Op.getOpcode() == ISD::SRL)
13023 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13025 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13026 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13030 if (VT == MVT::v16i8) {
13031 if (Op.getOpcode() == ISD::SHL) {
13032 // Make a large shift.
13033 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13034 MVT::v8i16, R, ShiftAmt,
13036 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13037 // Zero out the rightmost bits.
13038 SmallVector<SDValue, 16> V(16,
13039 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13041 return DAG.getNode(ISD::AND, dl, VT, SHL,
13042 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13044 if (Op.getOpcode() == ISD::SRL) {
13045 // Make a large shift.
13046 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13047 MVT::v8i16, R, ShiftAmt,
13049 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13050 // Zero out the leftmost bits.
13051 SmallVector<SDValue, 16> V(16,
13052 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13054 return DAG.getNode(ISD::AND, dl, VT, SRL,
13055 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
13057 if (Op.getOpcode() == ISD::SRA) {
13058 if (ShiftAmt == 7) {
13059 // R s>> 7 === R s< 0
13060 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13061 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13064 // R s>> a === ((R u>> a) ^ m) - m
13065 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13066 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13068 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
13069 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13070 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13073 llvm_unreachable("Unknown shift opcode.");
13076 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13077 if (Op.getOpcode() == ISD::SHL) {
13078 // Make a large shift.
13079 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13080 MVT::v16i16, R, ShiftAmt,
13082 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13083 // Zero out the rightmost bits.
13084 SmallVector<SDValue, 32> V(32,
13085 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13087 return DAG.getNode(ISD::AND, dl, VT, SHL,
13088 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13090 if (Op.getOpcode() == ISD::SRL) {
13091 // Make a large shift.
13092 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13093 MVT::v16i16, R, ShiftAmt,
13095 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13096 // Zero out the leftmost bits.
13097 SmallVector<SDValue, 32> V(32,
13098 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13100 return DAG.getNode(ISD::AND, dl, VT, SRL,
13101 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
13103 if (Op.getOpcode() == ISD::SRA) {
13104 if (ShiftAmt == 7) {
13105 // R s>> 7 === R s< 0
13106 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13107 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13110 // R s>> a === ((R u>> a) ^ m) - m
13111 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13112 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13114 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
13115 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13116 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13119 llvm_unreachable("Unknown shift opcode.");
13124 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13125 if (!Subtarget->is64Bit() &&
13126 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13127 Amt.getOpcode() == ISD::BITCAST &&
13128 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13129 Amt = Amt.getOperand(0);
13130 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13131 VT.getVectorNumElements();
13132 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13133 uint64_t ShiftAmt = 0;
13134 for (unsigned i = 0; i != Ratio; ++i) {
13135 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13139 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13141 // Check remaining shift amounts.
13142 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13143 uint64_t ShAmt = 0;
13144 for (unsigned j = 0; j != Ratio; ++j) {
13145 ConstantSDNode *C =
13146 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13150 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13152 if (ShAmt != ShiftAmt)
13155 switch (Op.getOpcode()) {
13157 llvm_unreachable("Unknown shift opcode!");
13159 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13162 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13165 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13173 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13174 const X86Subtarget* Subtarget) {
13175 MVT VT = Op.getSimpleValueType();
13177 SDValue R = Op.getOperand(0);
13178 SDValue Amt = Op.getOperand(1);
13180 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13181 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13182 (Subtarget->hasInt256() &&
13183 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13184 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13185 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13187 EVT EltVT = VT.getVectorElementType();
13189 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13190 unsigned NumElts = VT.getVectorNumElements();
13192 for (i = 0; i != NumElts; ++i) {
13193 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13197 for (j = i; j != NumElts; ++j) {
13198 SDValue Arg = Amt.getOperand(j);
13199 if (Arg.getOpcode() == ISD::UNDEF) continue;
13200 if (Arg != Amt.getOperand(i))
13203 if (i != NumElts && j == NumElts)
13204 BaseShAmt = Amt.getOperand(i);
13206 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13207 Amt = Amt.getOperand(0);
13208 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13209 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13210 SDValue InVec = Amt.getOperand(0);
13211 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13212 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13214 for (; i != NumElts; ++i) {
13215 SDValue Arg = InVec.getOperand(i);
13216 if (Arg.getOpcode() == ISD::UNDEF) continue;
13220 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13221 if (ConstantSDNode *C =
13222 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13223 unsigned SplatIdx =
13224 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13225 if (C->getZExtValue() == SplatIdx)
13226 BaseShAmt = InVec.getOperand(1);
13229 if (BaseShAmt.getNode() == 0)
13230 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13231 DAG.getIntPtrConstant(0));
13235 if (BaseShAmt.getNode()) {
13236 if (EltVT.bitsGT(MVT::i32))
13237 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13238 else if (EltVT.bitsLT(MVT::i32))
13239 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13241 switch (Op.getOpcode()) {
13243 llvm_unreachable("Unknown shift opcode!");
13245 switch (VT.SimpleTy) {
13246 default: return SDValue();
13255 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13258 switch (VT.SimpleTy) {
13259 default: return SDValue();
13266 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13269 switch (VT.SimpleTy) {
13270 default: return SDValue();
13279 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13285 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13286 if (!Subtarget->is64Bit() &&
13287 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13288 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13289 Amt.getOpcode() == ISD::BITCAST &&
13290 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13291 Amt = Amt.getOperand(0);
13292 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13293 VT.getVectorNumElements();
13294 std::vector<SDValue> Vals(Ratio);
13295 for (unsigned i = 0; i != Ratio; ++i)
13296 Vals[i] = Amt.getOperand(i);
13297 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13298 for (unsigned j = 0; j != Ratio; ++j)
13299 if (Vals[j] != Amt.getOperand(i + j))
13302 switch (Op.getOpcode()) {
13304 llvm_unreachable("Unknown shift opcode!");
13306 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13308 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13310 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13317 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13318 SelectionDAG &DAG) {
13320 MVT VT = Op.getSimpleValueType();
13322 SDValue R = Op.getOperand(0);
13323 SDValue Amt = Op.getOperand(1);
13326 if (!Subtarget->hasSSE2())
13329 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13333 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13337 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13339 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13340 if (Subtarget->hasInt256()) {
13341 if (Op.getOpcode() == ISD::SRL &&
13342 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13343 VT == MVT::v4i64 || VT == MVT::v8i32))
13345 if (Op.getOpcode() == ISD::SHL &&
13346 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13347 VT == MVT::v4i64 || VT == MVT::v8i32))
13349 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13353 // If possible, lower this packed shift into a vector multiply instead of
13354 // expanding it into a sequence of scalar shifts.
13355 // Do this only if the vector shift count is a constant build_vector.
13356 if (Op.getOpcode() == ISD::SHL &&
13357 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13358 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13359 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13360 SmallVector<SDValue, 8> Elts;
13361 EVT SVT = VT.getScalarType();
13362 unsigned SVTBits = SVT.getSizeInBits();
13363 const APInt &One = APInt(SVTBits, 1);
13364 unsigned NumElems = VT.getVectorNumElements();
13366 for (unsigned i=0; i !=NumElems; ++i) {
13367 SDValue Op = Amt->getOperand(i);
13368 if (Op->getOpcode() == ISD::UNDEF) {
13369 Elts.push_back(Op);
13373 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13374 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13375 uint64_t ShAmt = C.getZExtValue();
13376 if (ShAmt >= SVTBits) {
13377 Elts.push_back(DAG.getUNDEF(SVT));
13380 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13382 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElems);
13383 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13386 // Lower SHL with variable shift amount.
13387 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13388 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13390 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13391 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13392 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13393 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13396 // If possible, lower this shift as a sequence of two shifts by
13397 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13399 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13401 // Could be rewritten as:
13402 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13404 // The advantage is that the two shifts from the example would be
13405 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13406 // the vector shift into four scalar shifts plus four pairs of vector
13408 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13409 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13410 unsigned TargetOpcode = X86ISD::MOVSS;
13411 bool CanBeSimplified;
13412 // The splat value for the first packed shift (the 'X' from the example).
13413 SDValue Amt1 = Amt->getOperand(0);
13414 // The splat value for the second packed shift (the 'Y' from the example).
13415 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13416 Amt->getOperand(2);
13418 // See if it is possible to replace this node with a sequence of
13419 // two shifts followed by a MOVSS/MOVSD
13420 if (VT == MVT::v4i32) {
13421 // Check if it is legal to use a MOVSS.
13422 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13423 Amt2 == Amt->getOperand(3);
13424 if (!CanBeSimplified) {
13425 // Otherwise, check if we can still simplify this node using a MOVSD.
13426 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13427 Amt->getOperand(2) == Amt->getOperand(3);
13428 TargetOpcode = X86ISD::MOVSD;
13429 Amt2 = Amt->getOperand(2);
13432 // Do similar checks for the case where the machine value type
13434 CanBeSimplified = Amt1 == Amt->getOperand(1);
13435 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13436 CanBeSimplified = Amt2 == Amt->getOperand(i);
13438 if (!CanBeSimplified) {
13439 TargetOpcode = X86ISD::MOVSD;
13440 CanBeSimplified = true;
13441 Amt2 = Amt->getOperand(4);
13442 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13443 CanBeSimplified = Amt1 == Amt->getOperand(i);
13444 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13445 CanBeSimplified = Amt2 == Amt->getOperand(j);
13449 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13450 isa<ConstantSDNode>(Amt2)) {
13451 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13452 EVT CastVT = MVT::v4i32;
13454 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13455 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13457 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13458 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13459 if (TargetOpcode == X86ISD::MOVSD)
13460 CastVT = MVT::v2i64;
13461 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13462 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13463 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13465 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13469 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13470 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13473 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13474 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13476 // Turn 'a' into a mask suitable for VSELECT
13477 SDValue VSelM = DAG.getConstant(0x80, VT);
13478 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13479 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13481 SDValue CM1 = DAG.getConstant(0x0f, VT);
13482 SDValue CM2 = DAG.getConstant(0x3f, VT);
13484 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13485 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13486 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13487 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13488 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13491 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13492 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13493 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13495 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13496 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13497 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13498 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13499 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13502 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13503 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13504 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13506 // return VSELECT(r, r+r, a);
13507 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13508 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13512 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13513 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13514 // solution better.
13515 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13516 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13518 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13519 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13520 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13521 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13522 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13525 // Decompose 256-bit shifts into smaller 128-bit shifts.
13526 if (VT.is256BitVector()) {
13527 unsigned NumElems = VT.getVectorNumElements();
13528 MVT EltVT = VT.getVectorElementType();
13529 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13531 // Extract the two vectors
13532 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13533 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13535 // Recreate the shift amount vectors
13536 SDValue Amt1, Amt2;
13537 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13538 // Constant shift amount
13539 SmallVector<SDValue, 4> Amt1Csts;
13540 SmallVector<SDValue, 4> Amt2Csts;
13541 for (unsigned i = 0; i != NumElems/2; ++i)
13542 Amt1Csts.push_back(Amt->getOperand(i));
13543 for (unsigned i = NumElems/2; i != NumElems; ++i)
13544 Amt2Csts.push_back(Amt->getOperand(i));
13546 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13547 &Amt1Csts[0], NumElems/2);
13548 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13549 &Amt2Csts[0], NumElems/2);
13551 // Variable shift amount
13552 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13553 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13556 // Issue new vector shifts for the smaller types
13557 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13558 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13560 // Concatenate the result back
13561 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13567 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13568 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13569 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13570 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13571 // has only one use.
13572 SDNode *N = Op.getNode();
13573 SDValue LHS = N->getOperand(0);
13574 SDValue RHS = N->getOperand(1);
13575 unsigned BaseOp = 0;
13578 switch (Op.getOpcode()) {
13579 default: llvm_unreachable("Unknown ovf instruction!");
13581 // A subtract of one will be selected as a INC. Note that INC doesn't
13582 // set CF, so we can't do this for UADDO.
13583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13585 BaseOp = X86ISD::INC;
13586 Cond = X86::COND_O;
13589 BaseOp = X86ISD::ADD;
13590 Cond = X86::COND_O;
13593 BaseOp = X86ISD::ADD;
13594 Cond = X86::COND_B;
13597 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13598 // set CF, so we can't do this for USUBO.
13599 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13601 BaseOp = X86ISD::DEC;
13602 Cond = X86::COND_O;
13605 BaseOp = X86ISD::SUB;
13606 Cond = X86::COND_O;
13609 BaseOp = X86ISD::SUB;
13610 Cond = X86::COND_B;
13613 BaseOp = X86ISD::SMUL;
13614 Cond = X86::COND_O;
13616 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13617 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13619 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13622 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13623 DAG.getConstant(X86::COND_O, MVT::i32),
13624 SDValue(Sum.getNode(), 2));
13626 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13630 // Also sets EFLAGS.
13631 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13632 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13635 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13636 DAG.getConstant(Cond, MVT::i32),
13637 SDValue(Sum.getNode(), 1));
13639 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13642 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13643 SelectionDAG &DAG) const {
13645 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13646 MVT VT = Op.getSimpleValueType();
13648 if (!Subtarget->hasSSE2() || !VT.isVector())
13651 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13652 ExtraVT.getScalarType().getSizeInBits();
13654 switch (VT.SimpleTy) {
13655 default: return SDValue();
13658 if (!Subtarget->hasFp256())
13660 if (!Subtarget->hasInt256()) {
13661 // needs to be split
13662 unsigned NumElems = VT.getVectorNumElements();
13664 // Extract the LHS vectors
13665 SDValue LHS = Op.getOperand(0);
13666 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13667 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13669 MVT EltVT = VT.getVectorElementType();
13670 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13672 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13673 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13674 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13676 SDValue Extra = DAG.getValueType(ExtraVT);
13678 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13679 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13681 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13686 SDValue Op0 = Op.getOperand(0);
13687 SDValue Op00 = Op0.getOperand(0);
13689 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13690 if (Op0.getOpcode() == ISD::BITCAST &&
13691 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13692 // (sext (vzext x)) -> (vsext x)
13693 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13694 if (Tmp1.getNode()) {
13695 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13696 // This folding is only valid when the in-reg type is a vector of i8,
13698 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13699 ExtraEltVT == MVT::i32) {
13700 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13701 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13702 "This optimization is invalid without a VZEXT.");
13703 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13709 // If the above didn't work, then just use Shift-Left + Shift-Right.
13710 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13712 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13718 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13719 SelectionDAG &DAG) {
13721 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13722 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13723 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13724 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13726 // The only fence that needs an instruction is a sequentially-consistent
13727 // cross-thread fence.
13728 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13729 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13730 // no-sse2). There isn't any reason to disable it if the target processor
13732 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13733 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13735 SDValue Chain = Op.getOperand(0);
13736 SDValue Zero = DAG.getConstant(0, MVT::i32);
13738 DAG.getRegister(X86::ESP, MVT::i32), // Base
13739 DAG.getTargetConstant(1, MVT::i8), // Scale
13740 DAG.getRegister(0, MVT::i32), // Index
13741 DAG.getTargetConstant(0, MVT::i32), // Disp
13742 DAG.getRegister(0, MVT::i32), // Segment.
13746 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13747 return SDValue(Res, 0);
13750 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13751 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13754 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13755 SelectionDAG &DAG) {
13756 MVT T = Op.getSimpleValueType();
13760 switch(T.SimpleTy) {
13761 default: llvm_unreachable("Invalid value type!");
13762 case MVT::i8: Reg = X86::AL; size = 1; break;
13763 case MVT::i16: Reg = X86::AX; size = 2; break;
13764 case MVT::i32: Reg = X86::EAX; size = 4; break;
13766 assert(Subtarget->is64Bit() && "Node not type legal!");
13767 Reg = X86::RAX; size = 8;
13770 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13771 Op.getOperand(2), SDValue());
13772 SDValue Ops[] = { cpIn.getValue(0),
13775 DAG.getTargetConstant(size, MVT::i8),
13776 cpIn.getValue(1) };
13777 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13778 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13779 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13780 Ops, array_lengthof(Ops), T, MMO);
13782 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13786 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13787 SelectionDAG &DAG) {
13788 assert(Subtarget->is64Bit() && "Result not type legalized?");
13789 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13790 SDValue TheChain = Op.getOperand(0);
13792 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13793 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13794 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13796 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13797 DAG.getConstant(32, MVT::i8));
13799 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13802 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13805 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13806 SelectionDAG &DAG) {
13807 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13808 MVT DstVT = Op.getSimpleValueType();
13809 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13810 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13811 assert((DstVT == MVT::i64 ||
13812 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13813 "Unexpected custom BITCAST");
13814 // i64 <=> MMX conversions are Legal.
13815 if (SrcVT==MVT::i64 && DstVT.isVector())
13817 if (DstVT==MVT::i64 && SrcVT.isVector())
13819 // MMX <=> MMX conversions are Legal.
13820 if (SrcVT.isVector() && DstVT.isVector())
13822 // All other conversions need to be expanded.
13826 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13827 SDNode *Node = Op.getNode();
13829 EVT T = Node->getValueType(0);
13830 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13831 DAG.getConstant(0, T), Node->getOperand(2));
13832 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13833 cast<AtomicSDNode>(Node)->getMemoryVT(),
13834 Node->getOperand(0),
13835 Node->getOperand(1), negOp,
13836 cast<AtomicSDNode>(Node)->getMemOperand(),
13837 cast<AtomicSDNode>(Node)->getOrdering(),
13838 cast<AtomicSDNode>(Node)->getSynchScope());
13841 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13842 SDNode *Node = Op.getNode();
13844 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13846 // Convert seq_cst store -> xchg
13847 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13848 // FIXME: On 32-bit, store -> fist or movq would be more efficient
13849 // (The only way to get a 16-byte store is cmpxchg16b)
13850 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13851 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13852 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13853 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13854 cast<AtomicSDNode>(Node)->getMemoryVT(),
13855 Node->getOperand(0),
13856 Node->getOperand(1), Node->getOperand(2),
13857 cast<AtomicSDNode>(Node)->getMemOperand(),
13858 cast<AtomicSDNode>(Node)->getOrdering(),
13859 cast<AtomicSDNode>(Node)->getSynchScope());
13860 return Swap.getValue(1);
13862 // Other atomic stores have a simple pattern.
13866 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13867 EVT VT = Op.getNode()->getSimpleValueType(0);
13869 // Let legalize expand this if it isn't a legal type yet.
13870 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13873 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13876 bool ExtraOp = false;
13877 switch (Op.getOpcode()) {
13878 default: llvm_unreachable("Invalid code");
13879 case ISD::ADDC: Opc = X86ISD::ADD; break;
13880 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13881 case ISD::SUBC: Opc = X86ISD::SUB; break;
13882 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13886 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13888 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13889 Op.getOperand(1), Op.getOperand(2));
13892 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13893 SelectionDAG &DAG) {
13894 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13896 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13897 // which returns the values as { float, float } (in XMM0) or
13898 // { double, double } (which is returned in XMM0, XMM1).
13900 SDValue Arg = Op.getOperand(0);
13901 EVT ArgVT = Arg.getValueType();
13902 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13904 TargetLowering::ArgListTy Args;
13905 TargetLowering::ArgListEntry Entry;
13909 Entry.isSExt = false;
13910 Entry.isZExt = false;
13911 Args.push_back(Entry);
13913 bool isF64 = ArgVT == MVT::f64;
13914 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13915 // the small struct {f32, f32} is returned in (eax, edx). For f64,
13916 // the results are returned via SRet in memory.
13917 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
13918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13919 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13921 Type *RetTy = isF64
13922 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13923 : (Type*)VectorType::get(ArgTy, 4);
13925 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13926 false, false, false, false, 0,
13927 CallingConv::C, /*isTaillCall=*/false,
13928 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13929 Callee, Args, DAG, dl);
13930 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13933 // Returned in xmm0 and xmm1.
13934 return CallResult.first;
13936 // Returned in bits 0:31 and 32:64 xmm0.
13937 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13938 CallResult.first, DAG.getIntPtrConstant(0));
13939 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13940 CallResult.first, DAG.getIntPtrConstant(1));
13941 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13942 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13945 /// LowerOperation - Provide custom lowering hooks for some operations.
13947 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13948 switch (Op.getOpcode()) {
13949 default: llvm_unreachable("Should not custom lower this!");
13950 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
13951 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13952 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
13953 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
13954 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
13955 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
13956 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
13957 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
13958 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13959 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
13960 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13961 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13962 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
13963 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
13964 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
13965 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
13966 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
13967 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
13968 case ISD::SHL_PARTS:
13969 case ISD::SRA_PARTS:
13970 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
13971 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
13972 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
13973 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
13974 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
13975 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13976 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
13977 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
13978 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
13979 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
13980 case ISD::FABS: return LowerFABS(Op, DAG);
13981 case ISD::FNEG: return LowerFNEG(Op, DAG);
13982 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
13983 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
13984 case ISD::SETCC: return LowerSETCC(Op, DAG);
13985 case ISD::SELECT: return LowerSELECT(Op, DAG);
13986 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
13987 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
13988 case ISD::VASTART: return LowerVASTART(Op, DAG);
13989 case ISD::VAARG: return LowerVAARG(Op, DAG);
13990 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
13991 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13992 case ISD::INTRINSIC_VOID:
13993 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13994 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
13995 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
13996 case ISD::FRAME_TO_ARGS_OFFSET:
13997 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13998 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13999 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14000 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14001 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14002 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14003 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14004 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14005 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14006 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14007 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14008 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14011 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14017 case ISD::UMULO: return LowerXALUO(Op, DAG);
14018 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14019 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14023 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14024 case ISD::ADD: return LowerADD(Op, DAG);
14025 case ISD::SUB: return LowerSUB(Op, DAG);
14026 case ISD::SDIV: return LowerSDIV(Op, DAG);
14027 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14031 static void ReplaceATOMIC_LOAD(SDNode *Node,
14032 SmallVectorImpl<SDValue> &Results,
14033 SelectionDAG &DAG) {
14035 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14037 // Convert wide load -> cmpxchg8b/cmpxchg16b
14038 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14039 // (The only way to get a 16-byte load is cmpxchg16b)
14040 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14041 SDValue Zero = DAG.getConstant(0, VT);
14042 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14043 Node->getOperand(0),
14044 Node->getOperand(1), Zero, Zero,
14045 cast<AtomicSDNode>(Node)->getMemOperand(),
14046 cast<AtomicSDNode>(Node)->getOrdering(),
14047 cast<AtomicSDNode>(Node)->getOrdering(),
14048 cast<AtomicSDNode>(Node)->getSynchScope());
14049 Results.push_back(Swap.getValue(0));
14050 Results.push_back(Swap.getValue(1));
14054 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14055 SelectionDAG &DAG, unsigned NewOp) {
14057 assert (Node->getValueType(0) == MVT::i64 &&
14058 "Only know how to expand i64 atomics");
14060 SDValue Chain = Node->getOperand(0);
14061 SDValue In1 = Node->getOperand(1);
14062 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14063 Node->getOperand(2), DAG.getIntPtrConstant(0));
14064 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14065 Node->getOperand(2), DAG.getIntPtrConstant(1));
14066 SDValue Ops[] = { Chain, In1, In2L, In2H };
14067 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14069 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14070 cast<MemSDNode>(Node)->getMemOperand());
14071 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14072 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
14073 Results.push_back(Result.getValue(2));
14076 /// ReplaceNodeResults - Replace a node with an illegal result type
14077 /// with a new node built out of custom code.
14078 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14079 SmallVectorImpl<SDValue>&Results,
14080 SelectionDAG &DAG) const {
14082 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14083 switch (N->getOpcode()) {
14085 llvm_unreachable("Do not know how to custom type legalize this operation!");
14086 case ISD::SIGN_EXTEND_INREG:
14091 // We don't want to expand or promote these.
14093 case ISD::FP_TO_SINT:
14094 case ISD::FP_TO_UINT: {
14095 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14097 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14100 std::pair<SDValue,SDValue> Vals =
14101 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14102 SDValue FIST = Vals.first, StackSlot = Vals.second;
14103 if (FIST.getNode() != 0) {
14104 EVT VT = N->getValueType(0);
14105 // Return a load from the stack slot.
14106 if (StackSlot.getNode() != 0)
14107 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14108 MachinePointerInfo(),
14109 false, false, false, 0));
14111 Results.push_back(FIST);
14115 case ISD::UINT_TO_FP: {
14116 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14117 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14118 N->getValueType(0) != MVT::v2f32)
14120 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14122 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14124 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14125 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14126 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14127 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14128 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14129 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14132 case ISD::FP_ROUND: {
14133 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14135 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14136 Results.push_back(V);
14139 case ISD::READCYCLECOUNTER: {
14140 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14141 SDValue TheChain = N->getOperand(0);
14142 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
14143 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
14145 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
14147 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14148 SDValue Ops[] = { eax, edx };
14149 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
14150 array_lengthof(Ops)));
14151 Results.push_back(edx.getValue(1));
14154 case ISD::ATOMIC_CMP_SWAP: {
14155 EVT T = N->getValueType(0);
14156 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14157 bool Regs64bit = T == MVT::i128;
14158 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14159 SDValue cpInL, cpInH;
14160 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14161 DAG.getConstant(0, HalfT));
14162 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14163 DAG.getConstant(1, HalfT));
14164 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14165 Regs64bit ? X86::RAX : X86::EAX,
14167 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14168 Regs64bit ? X86::RDX : X86::EDX,
14169 cpInH, cpInL.getValue(1));
14170 SDValue swapInL, swapInH;
14171 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14172 DAG.getConstant(0, HalfT));
14173 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14174 DAG.getConstant(1, HalfT));
14175 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14176 Regs64bit ? X86::RBX : X86::EBX,
14177 swapInL, cpInH.getValue(1));
14178 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14179 Regs64bit ? X86::RCX : X86::ECX,
14180 swapInH, swapInL.getValue(1));
14181 SDValue Ops[] = { swapInH.getValue(0),
14183 swapInH.getValue(1) };
14184 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14185 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14186 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14187 X86ISD::LCMPXCHG8_DAG;
14188 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14189 Ops, array_lengthof(Ops), T, MMO);
14190 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14191 Regs64bit ? X86::RAX : X86::EAX,
14192 HalfT, Result.getValue(1));
14193 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14194 Regs64bit ? X86::RDX : X86::EDX,
14195 HalfT, cpOutL.getValue(2));
14196 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14197 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
14198 Results.push_back(cpOutH.getValue(1));
14201 case ISD::ATOMIC_LOAD_ADD:
14202 case ISD::ATOMIC_LOAD_AND:
14203 case ISD::ATOMIC_LOAD_NAND:
14204 case ISD::ATOMIC_LOAD_OR:
14205 case ISD::ATOMIC_LOAD_SUB:
14206 case ISD::ATOMIC_LOAD_XOR:
14207 case ISD::ATOMIC_LOAD_MAX:
14208 case ISD::ATOMIC_LOAD_MIN:
14209 case ISD::ATOMIC_LOAD_UMAX:
14210 case ISD::ATOMIC_LOAD_UMIN:
14211 case ISD::ATOMIC_SWAP: {
14213 switch (N->getOpcode()) {
14214 default: llvm_unreachable("Unexpected opcode");
14215 case ISD::ATOMIC_LOAD_ADD:
14216 Opc = X86ISD::ATOMADD64_DAG;
14218 case ISD::ATOMIC_LOAD_AND:
14219 Opc = X86ISD::ATOMAND64_DAG;
14221 case ISD::ATOMIC_LOAD_NAND:
14222 Opc = X86ISD::ATOMNAND64_DAG;
14224 case ISD::ATOMIC_LOAD_OR:
14225 Opc = X86ISD::ATOMOR64_DAG;
14227 case ISD::ATOMIC_LOAD_SUB:
14228 Opc = X86ISD::ATOMSUB64_DAG;
14230 case ISD::ATOMIC_LOAD_XOR:
14231 Opc = X86ISD::ATOMXOR64_DAG;
14233 case ISD::ATOMIC_LOAD_MAX:
14234 Opc = X86ISD::ATOMMAX64_DAG;
14236 case ISD::ATOMIC_LOAD_MIN:
14237 Opc = X86ISD::ATOMMIN64_DAG;
14239 case ISD::ATOMIC_LOAD_UMAX:
14240 Opc = X86ISD::ATOMUMAX64_DAG;
14242 case ISD::ATOMIC_LOAD_UMIN:
14243 Opc = X86ISD::ATOMUMIN64_DAG;
14245 case ISD::ATOMIC_SWAP:
14246 Opc = X86ISD::ATOMSWAP64_DAG;
14249 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14252 case ISD::ATOMIC_LOAD:
14253 ReplaceATOMIC_LOAD(N, Results, DAG);
14257 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14259 default: return NULL;
14260 case X86ISD::BSF: return "X86ISD::BSF";
14261 case X86ISD::BSR: return "X86ISD::BSR";
14262 case X86ISD::SHLD: return "X86ISD::SHLD";
14263 case X86ISD::SHRD: return "X86ISD::SHRD";
14264 case X86ISD::FAND: return "X86ISD::FAND";
14265 case X86ISD::FANDN: return "X86ISD::FANDN";
14266 case X86ISD::FOR: return "X86ISD::FOR";
14267 case X86ISD::FXOR: return "X86ISD::FXOR";
14268 case X86ISD::FSRL: return "X86ISD::FSRL";
14269 case X86ISD::FILD: return "X86ISD::FILD";
14270 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14271 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14272 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14273 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14274 case X86ISD::FLD: return "X86ISD::FLD";
14275 case X86ISD::FST: return "X86ISD::FST";
14276 case X86ISD::CALL: return "X86ISD::CALL";
14277 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14278 case X86ISD::BT: return "X86ISD::BT";
14279 case X86ISD::CMP: return "X86ISD::CMP";
14280 case X86ISD::COMI: return "X86ISD::COMI";
14281 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14282 case X86ISD::CMPM: return "X86ISD::CMPM";
14283 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14284 case X86ISD::SETCC: return "X86ISD::SETCC";
14285 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14286 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14287 case X86ISD::CMOV: return "X86ISD::CMOV";
14288 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14289 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14290 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14291 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14292 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14293 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14294 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14295 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14296 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14297 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14298 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14299 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14300 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14301 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14302 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14303 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14304 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14305 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14306 case X86ISD::HADD: return "X86ISD::HADD";
14307 case X86ISD::HSUB: return "X86ISD::HSUB";
14308 case X86ISD::FHADD: return "X86ISD::FHADD";
14309 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14310 case X86ISD::UMAX: return "X86ISD::UMAX";
14311 case X86ISD::UMIN: return "X86ISD::UMIN";
14312 case X86ISD::SMAX: return "X86ISD::SMAX";
14313 case X86ISD::SMIN: return "X86ISD::SMIN";
14314 case X86ISD::FMAX: return "X86ISD::FMAX";
14315 case X86ISD::FMIN: return "X86ISD::FMIN";
14316 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14317 case X86ISD::FMINC: return "X86ISD::FMINC";
14318 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14319 case X86ISD::FRCP: return "X86ISD::FRCP";
14320 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14321 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14322 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14323 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14324 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14325 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14326 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14327 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14328 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14329 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14330 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14331 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14332 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14333 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14334 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14335 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14336 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14337 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14338 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14339 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14340 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14341 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14342 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14343 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14344 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14345 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14346 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14347 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14348 case X86ISD::VSHL: return "X86ISD::VSHL";
14349 case X86ISD::VSRL: return "X86ISD::VSRL";
14350 case X86ISD::VSRA: return "X86ISD::VSRA";
14351 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14352 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14353 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14354 case X86ISD::CMPP: return "X86ISD::CMPP";
14355 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14356 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14357 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14358 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14359 case X86ISD::ADD: return "X86ISD::ADD";
14360 case X86ISD::SUB: return "X86ISD::SUB";
14361 case X86ISD::ADC: return "X86ISD::ADC";
14362 case X86ISD::SBB: return "X86ISD::SBB";
14363 case X86ISD::SMUL: return "X86ISD::SMUL";
14364 case X86ISD::UMUL: return "X86ISD::UMUL";
14365 case X86ISD::INC: return "X86ISD::INC";
14366 case X86ISD::DEC: return "X86ISD::DEC";
14367 case X86ISD::OR: return "X86ISD::OR";
14368 case X86ISD::XOR: return "X86ISD::XOR";
14369 case X86ISD::AND: return "X86ISD::AND";
14370 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14371 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14372 case X86ISD::PTEST: return "X86ISD::PTEST";
14373 case X86ISD::TESTP: return "X86ISD::TESTP";
14374 case X86ISD::TESTM: return "X86ISD::TESTM";
14375 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14376 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14377 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14378 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14379 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14380 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14381 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14382 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14383 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14384 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14385 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14386 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14387 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14388 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14389 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14390 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14391 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14392 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14393 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14394 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14395 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14396 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14397 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14398 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14399 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14400 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14401 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14402 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14403 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14404 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14405 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14406 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14407 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14408 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14409 case X86ISD::SAHF: return "X86ISD::SAHF";
14410 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14411 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14412 case X86ISD::FMADD: return "X86ISD::FMADD";
14413 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14414 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14415 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14416 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14417 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14418 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14419 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14420 case X86ISD::XTEST: return "X86ISD::XTEST";
14424 // isLegalAddressingMode - Return true if the addressing mode represented
14425 // by AM is legal for this target, for a load/store of the specified type.
14426 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14428 // X86 supports extremely general addressing modes.
14429 CodeModel::Model M = getTargetMachine().getCodeModel();
14430 Reloc::Model R = getTargetMachine().getRelocationModel();
14432 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14433 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14438 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14440 // If a reference to this global requires an extra load, we can't fold it.
14441 if (isGlobalStubReference(GVFlags))
14444 // If BaseGV requires a register for the PIC base, we cannot also have a
14445 // BaseReg specified.
14446 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14449 // If lower 4G is not available, then we must use rip-relative addressing.
14450 if ((M != CodeModel::Small || R != Reloc::Static) &&
14451 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14455 switch (AM.Scale) {
14461 // These scales always work.
14466 // These scales are formed with basereg+scalereg. Only accept if there is
14471 default: // Other stuff never works.
14478 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14479 unsigned Bits = Ty->getScalarSizeInBits();
14481 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14482 // particularly cheaper than those without.
14486 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14487 // variable shifts just as cheap as scalar ones.
14488 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14491 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14492 // fully general vector.
14496 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14497 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14499 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14500 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14501 return NumBits1 > NumBits2;
14504 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14505 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14508 if (!isTypeLegal(EVT::getEVT(Ty1)))
14511 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14513 // Assuming the caller doesn't have a zeroext or signext return parameter,
14514 // truncation all the way down to i1 is valid.
14518 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14519 return isInt<32>(Imm);
14522 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14523 // Can also use sub to handle negated immediates.
14524 return isInt<32>(Imm);
14527 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14528 if (!VT1.isInteger() || !VT2.isInteger())
14530 unsigned NumBits1 = VT1.getSizeInBits();
14531 unsigned NumBits2 = VT2.getSizeInBits();
14532 return NumBits1 > NumBits2;
14535 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14536 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14537 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14540 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14541 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14542 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14545 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14546 EVT VT1 = Val.getValueType();
14547 if (isZExtFree(VT1, VT2))
14550 if (Val.getOpcode() != ISD::LOAD)
14553 if (!VT1.isSimple() || !VT1.isInteger() ||
14554 !VT2.isSimple() || !VT2.isInteger())
14557 switch (VT1.getSimpleVT().SimpleTy) {
14562 // X86 has 8, 16, and 32-bit zero-extending loads.
14570 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14571 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14574 VT = VT.getScalarType();
14576 if (!VT.isSimple())
14579 switch (VT.getSimpleVT().SimpleTy) {
14590 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14591 // i16 instructions are longer (0x66 prefix) and potentially slower.
14592 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14595 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14596 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14597 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14598 /// are assumed to be legal.
14600 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14602 if (!VT.isSimple())
14605 MVT SVT = VT.getSimpleVT();
14607 // Very little shuffling can be done for 64-bit vectors right now.
14608 if (VT.getSizeInBits() == 64)
14611 // FIXME: pshufb, blends, shifts.
14612 return (SVT.getVectorNumElements() == 2 ||
14613 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14614 isMOVLMask(M, SVT) ||
14615 isSHUFPMask(M, SVT) ||
14616 isPSHUFDMask(M, SVT) ||
14617 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14618 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14619 isPALIGNRMask(M, SVT, Subtarget) ||
14620 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14621 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14622 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14623 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14627 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14629 if (!VT.isSimple())
14632 MVT SVT = VT.getSimpleVT();
14633 unsigned NumElts = SVT.getVectorNumElements();
14634 // FIXME: This collection of masks seems suspect.
14637 if (NumElts == 4 && SVT.is128BitVector()) {
14638 return (isMOVLMask(Mask, SVT) ||
14639 isCommutedMOVLMask(Mask, SVT, true) ||
14640 isSHUFPMask(Mask, SVT) ||
14641 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14646 //===----------------------------------------------------------------------===//
14647 // X86 Scheduler Hooks
14648 //===----------------------------------------------------------------------===//
14650 /// Utility function to emit xbegin specifying the start of an RTM region.
14651 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14652 const TargetInstrInfo *TII) {
14653 DebugLoc DL = MI->getDebugLoc();
14655 const BasicBlock *BB = MBB->getBasicBlock();
14656 MachineFunction::iterator I = MBB;
14659 // For the v = xbegin(), we generate
14670 MachineBasicBlock *thisMBB = MBB;
14671 MachineFunction *MF = MBB->getParent();
14672 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14673 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14674 MF->insert(I, mainMBB);
14675 MF->insert(I, sinkMBB);
14677 // Transfer the remainder of BB and its successor edges to sinkMBB.
14678 sinkMBB->splice(sinkMBB->begin(), MBB,
14679 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14680 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14684 // # fallthrough to mainMBB
14685 // # abortion to sinkMBB
14686 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14687 thisMBB->addSuccessor(mainMBB);
14688 thisMBB->addSuccessor(sinkMBB);
14692 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14693 mainMBB->addSuccessor(sinkMBB);
14696 // EAX is live into the sinkMBB
14697 sinkMBB->addLiveIn(X86::EAX);
14698 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14699 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14702 MI->eraseFromParent();
14706 // Get CMPXCHG opcode for the specified data type.
14707 static unsigned getCmpXChgOpcode(EVT VT) {
14708 switch (VT.getSimpleVT().SimpleTy) {
14709 case MVT::i8: return X86::LCMPXCHG8;
14710 case MVT::i16: return X86::LCMPXCHG16;
14711 case MVT::i32: return X86::LCMPXCHG32;
14712 case MVT::i64: return X86::LCMPXCHG64;
14716 llvm_unreachable("Invalid operand size!");
14719 // Get LOAD opcode for the specified data type.
14720 static unsigned getLoadOpcode(EVT VT) {
14721 switch (VT.getSimpleVT().SimpleTy) {
14722 case MVT::i8: return X86::MOV8rm;
14723 case MVT::i16: return X86::MOV16rm;
14724 case MVT::i32: return X86::MOV32rm;
14725 case MVT::i64: return X86::MOV64rm;
14729 llvm_unreachable("Invalid operand size!");
14732 // Get opcode of the non-atomic one from the specified atomic instruction.
14733 static unsigned getNonAtomicOpcode(unsigned Opc) {
14735 case X86::ATOMAND8: return X86::AND8rr;
14736 case X86::ATOMAND16: return X86::AND16rr;
14737 case X86::ATOMAND32: return X86::AND32rr;
14738 case X86::ATOMAND64: return X86::AND64rr;
14739 case X86::ATOMOR8: return X86::OR8rr;
14740 case X86::ATOMOR16: return X86::OR16rr;
14741 case X86::ATOMOR32: return X86::OR32rr;
14742 case X86::ATOMOR64: return X86::OR64rr;
14743 case X86::ATOMXOR8: return X86::XOR8rr;
14744 case X86::ATOMXOR16: return X86::XOR16rr;
14745 case X86::ATOMXOR32: return X86::XOR32rr;
14746 case X86::ATOMXOR64: return X86::XOR64rr;
14748 llvm_unreachable("Unhandled atomic-load-op opcode!");
14751 // Get opcode of the non-atomic one from the specified atomic instruction with
14753 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14754 unsigned &ExtraOpc) {
14756 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14757 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14758 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14759 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14760 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14761 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14762 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14763 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14764 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14765 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14766 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14767 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14768 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14769 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14770 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14771 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14772 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14773 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14774 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14775 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14777 llvm_unreachable("Unhandled atomic-load-op opcode!");
14780 // Get opcode of the non-atomic one from the specified atomic instruction for
14781 // 64-bit data type on 32-bit target.
14782 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14784 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14785 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14786 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14787 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14788 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14789 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14790 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14791 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14792 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14793 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14795 llvm_unreachable("Unhandled atomic-load-op opcode!");
14798 // Get opcode of the non-atomic one from the specified atomic instruction for
14799 // 64-bit data type on 32-bit target with extra opcode.
14800 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14802 unsigned &ExtraOpc) {
14804 case X86::ATOMNAND6432:
14805 ExtraOpc = X86::NOT32r;
14806 HiOpc = X86::AND32rr;
14807 return X86::AND32rr;
14809 llvm_unreachable("Unhandled atomic-load-op opcode!");
14812 // Get pseudo CMOV opcode from the specified data type.
14813 static unsigned getPseudoCMOVOpc(EVT VT) {
14814 switch (VT.getSimpleVT().SimpleTy) {
14815 case MVT::i8: return X86::CMOV_GR8;
14816 case MVT::i16: return X86::CMOV_GR16;
14817 case MVT::i32: return X86::CMOV_GR32;
14821 llvm_unreachable("Unknown CMOV opcode!");
14824 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14825 // They will be translated into a spin-loop or compare-exchange loop from
14828 // dst = atomic-fetch-op MI.addr, MI.val
14834 // t1 = LOAD MI.addr
14836 // t4 = phi(t1, t3 / loop)
14837 // t2 = OP MI.val, t4
14839 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14845 MachineBasicBlock *
14846 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14847 MachineBasicBlock *MBB) const {
14848 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14849 DebugLoc DL = MI->getDebugLoc();
14851 MachineFunction *MF = MBB->getParent();
14852 MachineRegisterInfo &MRI = MF->getRegInfo();
14854 const BasicBlock *BB = MBB->getBasicBlock();
14855 MachineFunction::iterator I = MBB;
14858 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14859 "Unexpected number of operands");
14861 assert(MI->hasOneMemOperand() &&
14862 "Expected atomic-load-op to have one memoperand");
14864 // Memory Reference
14865 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14866 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14868 unsigned DstReg, SrcReg;
14869 unsigned MemOpndSlot;
14871 unsigned CurOp = 0;
14873 DstReg = MI->getOperand(CurOp++).getReg();
14874 MemOpndSlot = CurOp;
14875 CurOp += X86::AddrNumOperands;
14876 SrcReg = MI->getOperand(CurOp++).getReg();
14878 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14879 MVT::SimpleValueType VT = *RC->vt_begin();
14880 unsigned t1 = MRI.createVirtualRegister(RC);
14881 unsigned t2 = MRI.createVirtualRegister(RC);
14882 unsigned t3 = MRI.createVirtualRegister(RC);
14883 unsigned t4 = MRI.createVirtualRegister(RC);
14884 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14886 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14887 unsigned LOADOpc = getLoadOpcode(VT);
14889 // For the atomic load-arith operator, we generate
14892 // t1 = LOAD [MI.addr]
14894 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
14895 // t1 = OP MI.val, EAX
14897 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14903 MachineBasicBlock *thisMBB = MBB;
14904 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14905 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14906 MF->insert(I, mainMBB);
14907 MF->insert(I, sinkMBB);
14909 MachineInstrBuilder MIB;
14911 // Transfer the remainder of BB and its successor edges to sinkMBB.
14912 sinkMBB->splice(sinkMBB->begin(), MBB,
14913 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14914 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14917 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14918 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14919 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14921 NewMO.setIsKill(false);
14922 MIB.addOperand(NewMO);
14924 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14925 unsigned flags = (*MMOI)->getFlags();
14926 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14927 MachineMemOperand *MMO =
14928 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14929 (*MMOI)->getSize(),
14930 (*MMOI)->getBaseAlignment(),
14931 (*MMOI)->getTBAAInfo(),
14932 (*MMOI)->getRanges());
14933 MIB.addMemOperand(MMO);
14936 thisMBB->addSuccessor(mainMBB);
14939 MachineBasicBlock *origMainMBB = mainMBB;
14942 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14943 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14945 unsigned Opc = MI->getOpcode();
14948 llvm_unreachable("Unhandled atomic-load-op opcode!");
14949 case X86::ATOMAND8:
14950 case X86::ATOMAND16:
14951 case X86::ATOMAND32:
14952 case X86::ATOMAND64:
14954 case X86::ATOMOR16:
14955 case X86::ATOMOR32:
14956 case X86::ATOMOR64:
14957 case X86::ATOMXOR8:
14958 case X86::ATOMXOR16:
14959 case X86::ATOMXOR32:
14960 case X86::ATOMXOR64: {
14961 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14962 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14966 case X86::ATOMNAND8:
14967 case X86::ATOMNAND16:
14968 case X86::ATOMNAND32:
14969 case X86::ATOMNAND64: {
14970 unsigned Tmp = MRI.createVirtualRegister(RC);
14972 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14973 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14975 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14978 case X86::ATOMMAX8:
14979 case X86::ATOMMAX16:
14980 case X86::ATOMMAX32:
14981 case X86::ATOMMAX64:
14982 case X86::ATOMMIN8:
14983 case X86::ATOMMIN16:
14984 case X86::ATOMMIN32:
14985 case X86::ATOMMIN64:
14986 case X86::ATOMUMAX8:
14987 case X86::ATOMUMAX16:
14988 case X86::ATOMUMAX32:
14989 case X86::ATOMUMAX64:
14990 case X86::ATOMUMIN8:
14991 case X86::ATOMUMIN16:
14992 case X86::ATOMUMIN32:
14993 case X86::ATOMUMIN64: {
14995 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14997 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15001 if (Subtarget->hasCMov()) {
15002 if (VT != MVT::i8) {
15004 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15008 // Promote i8 to i32 to use CMOV32
15009 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15010 const TargetRegisterClass *RC32 =
15011 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15012 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15013 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15014 unsigned Tmp = MRI.createVirtualRegister(RC32);
15016 unsigned Undef = MRI.createVirtualRegister(RC32);
15017 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15019 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15022 .addImm(X86::sub_8bit);
15023 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15026 .addImm(X86::sub_8bit);
15028 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15032 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15033 .addReg(Tmp, 0, X86::sub_8bit);
15036 // Use pseudo select and lower them.
15037 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15038 "Invalid atomic-load-op transformation!");
15039 unsigned SelOpc = getPseudoCMOVOpc(VT);
15040 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15041 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15042 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15043 .addReg(SrcReg).addReg(t4)
15045 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15046 // Replace the original PHI node as mainMBB is changed after CMOV
15048 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15049 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15050 Phi->eraseFromParent();
15056 // Copy PhyReg back from virtual register.
15057 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15060 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15061 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15062 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15064 NewMO.setIsKill(false);
15065 MIB.addOperand(NewMO);
15068 MIB.setMemRefs(MMOBegin, MMOEnd);
15070 // Copy PhyReg back to virtual register.
15071 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15074 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15076 mainMBB->addSuccessor(origMainMBB);
15077 mainMBB->addSuccessor(sinkMBB);
15080 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15081 TII->get(TargetOpcode::COPY), DstReg)
15084 MI->eraseFromParent();
15088 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15089 // instructions. They will be translated into a spin-loop or compare-exchange
15093 // dst = atomic-fetch-op MI.addr, MI.val
15099 // t1L = LOAD [MI.addr + 0]
15100 // t1H = LOAD [MI.addr + 4]
15102 // t4L = phi(t1L, t3L / loop)
15103 // t4H = phi(t1H, t3H / loop)
15104 // t2L = OP MI.val.lo, t4L
15105 // t2H = OP MI.val.hi, t4H
15110 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15118 MachineBasicBlock *
15119 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15120 MachineBasicBlock *MBB) const {
15121 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15122 DebugLoc DL = MI->getDebugLoc();
15124 MachineFunction *MF = MBB->getParent();
15125 MachineRegisterInfo &MRI = MF->getRegInfo();
15127 const BasicBlock *BB = MBB->getBasicBlock();
15128 MachineFunction::iterator I = MBB;
15131 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15132 "Unexpected number of operands");
15134 assert(MI->hasOneMemOperand() &&
15135 "Expected atomic-load-op32 to have one memoperand");
15137 // Memory Reference
15138 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15139 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15141 unsigned DstLoReg, DstHiReg;
15142 unsigned SrcLoReg, SrcHiReg;
15143 unsigned MemOpndSlot;
15145 unsigned CurOp = 0;
15147 DstLoReg = MI->getOperand(CurOp++).getReg();
15148 DstHiReg = MI->getOperand(CurOp++).getReg();
15149 MemOpndSlot = CurOp;
15150 CurOp += X86::AddrNumOperands;
15151 SrcLoReg = MI->getOperand(CurOp++).getReg();
15152 SrcHiReg = MI->getOperand(CurOp++).getReg();
15154 const TargetRegisterClass *RC = &X86::GR32RegClass;
15155 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15157 unsigned t1L = MRI.createVirtualRegister(RC);
15158 unsigned t1H = MRI.createVirtualRegister(RC);
15159 unsigned t2L = MRI.createVirtualRegister(RC);
15160 unsigned t2H = MRI.createVirtualRegister(RC);
15161 unsigned t3L = MRI.createVirtualRegister(RC);
15162 unsigned t3H = MRI.createVirtualRegister(RC);
15163 unsigned t4L = MRI.createVirtualRegister(RC);
15164 unsigned t4H = MRI.createVirtualRegister(RC);
15166 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15167 unsigned LOADOpc = X86::MOV32rm;
15169 // For the atomic load-arith operator, we generate
15172 // t1L = LOAD [MI.addr + 0]
15173 // t1H = LOAD [MI.addr + 4]
15175 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15176 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15177 // t2L = OP MI.val.lo, t4L
15178 // t2H = OP MI.val.hi, t4H
15181 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15189 MachineBasicBlock *thisMBB = MBB;
15190 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15191 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15192 MF->insert(I, mainMBB);
15193 MF->insert(I, sinkMBB);
15195 MachineInstrBuilder MIB;
15197 // Transfer the remainder of BB and its successor edges to sinkMBB.
15198 sinkMBB->splice(sinkMBB->begin(), MBB,
15199 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15200 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15204 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15205 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15206 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15208 NewMO.setIsKill(false);
15209 MIB.addOperand(NewMO);
15211 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15212 unsigned flags = (*MMOI)->getFlags();
15213 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15214 MachineMemOperand *MMO =
15215 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15216 (*MMOI)->getSize(),
15217 (*MMOI)->getBaseAlignment(),
15218 (*MMOI)->getTBAAInfo(),
15219 (*MMOI)->getRanges());
15220 MIB.addMemOperand(MMO);
15222 MachineInstr *LowMI = MIB;
15225 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15226 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15227 if (i == X86::AddrDisp) {
15228 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15230 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15232 NewMO.setIsKill(false);
15233 MIB.addOperand(NewMO);
15236 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15238 thisMBB->addSuccessor(mainMBB);
15241 MachineBasicBlock *origMainMBB = mainMBB;
15244 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15245 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15246 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15247 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15249 unsigned Opc = MI->getOpcode();
15252 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15253 case X86::ATOMAND6432:
15254 case X86::ATOMOR6432:
15255 case X86::ATOMXOR6432:
15256 case X86::ATOMADD6432:
15257 case X86::ATOMSUB6432: {
15259 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15260 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15262 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15266 case X86::ATOMNAND6432: {
15267 unsigned HiOpc, NOTOpc;
15268 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15269 unsigned TmpL = MRI.createVirtualRegister(RC);
15270 unsigned TmpH = MRI.createVirtualRegister(RC);
15271 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15273 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15275 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15276 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15279 case X86::ATOMMAX6432:
15280 case X86::ATOMMIN6432:
15281 case X86::ATOMUMAX6432:
15282 case X86::ATOMUMIN6432: {
15284 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15285 unsigned cL = MRI.createVirtualRegister(RC8);
15286 unsigned cH = MRI.createVirtualRegister(RC8);
15287 unsigned cL32 = MRI.createVirtualRegister(RC);
15288 unsigned cH32 = MRI.createVirtualRegister(RC);
15289 unsigned cc = MRI.createVirtualRegister(RC);
15290 // cl := cmp src_lo, lo
15291 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15292 .addReg(SrcLoReg).addReg(t4L);
15293 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15294 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15295 // ch := cmp src_hi, hi
15296 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15297 .addReg(SrcHiReg).addReg(t4H);
15298 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15299 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15300 // cc := if (src_hi == hi) ? cl : ch;
15301 if (Subtarget->hasCMov()) {
15302 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15303 .addReg(cH32).addReg(cL32);
15305 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15306 .addReg(cH32).addReg(cL32)
15307 .addImm(X86::COND_E);
15308 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15310 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15311 if (Subtarget->hasCMov()) {
15312 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15313 .addReg(SrcLoReg).addReg(t4L);
15314 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15315 .addReg(SrcHiReg).addReg(t4H);
15317 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15318 .addReg(SrcLoReg).addReg(t4L)
15319 .addImm(X86::COND_NE);
15320 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15321 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15322 // 2nd CMOV lowering.
15323 mainMBB->addLiveIn(X86::EFLAGS);
15324 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15325 .addReg(SrcHiReg).addReg(t4H)
15326 .addImm(X86::COND_NE);
15327 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15328 // Replace the original PHI node as mainMBB is changed after CMOV
15330 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15331 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15332 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15333 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15334 PhiL->eraseFromParent();
15335 PhiH->eraseFromParent();
15339 case X86::ATOMSWAP6432: {
15341 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15342 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15343 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15348 // Copy EDX:EAX back from HiReg:LoReg
15349 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15350 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15351 // Copy ECX:EBX from t1H:t1L
15352 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15353 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15355 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15356 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15357 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15359 NewMO.setIsKill(false);
15360 MIB.addOperand(NewMO);
15362 MIB.setMemRefs(MMOBegin, MMOEnd);
15364 // Copy EDX:EAX back to t3H:t3L
15365 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15366 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15368 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15370 mainMBB->addSuccessor(origMainMBB);
15371 mainMBB->addSuccessor(sinkMBB);
15374 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15375 TII->get(TargetOpcode::COPY), DstLoReg)
15377 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15378 TII->get(TargetOpcode::COPY), DstHiReg)
15381 MI->eraseFromParent();
15385 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15386 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15387 // in the .td file.
15388 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15389 const TargetInstrInfo *TII) {
15391 switch (MI->getOpcode()) {
15392 default: llvm_unreachable("illegal opcode!");
15393 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15394 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15395 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15396 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15397 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15398 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15399 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15400 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15403 DebugLoc dl = MI->getDebugLoc();
15404 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15406 unsigned NumArgs = MI->getNumOperands();
15407 for (unsigned i = 1; i < NumArgs; ++i) {
15408 MachineOperand &Op = MI->getOperand(i);
15409 if (!(Op.isReg() && Op.isImplicit()))
15410 MIB.addOperand(Op);
15412 if (MI->hasOneMemOperand())
15413 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15415 BuildMI(*BB, MI, dl,
15416 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15417 .addReg(X86::XMM0);
15419 MI->eraseFromParent();
15423 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15424 // defs in an instruction pattern
15425 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15426 const TargetInstrInfo *TII) {
15428 switch (MI->getOpcode()) {
15429 default: llvm_unreachable("illegal opcode!");
15430 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15431 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15432 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15433 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15434 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15435 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15436 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15437 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15440 DebugLoc dl = MI->getDebugLoc();
15441 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15443 unsigned NumArgs = MI->getNumOperands(); // remove the results
15444 for (unsigned i = 1; i < NumArgs; ++i) {
15445 MachineOperand &Op = MI->getOperand(i);
15446 if (!(Op.isReg() && Op.isImplicit()))
15447 MIB.addOperand(Op);
15449 if (MI->hasOneMemOperand())
15450 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15452 BuildMI(*BB, MI, dl,
15453 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15456 MI->eraseFromParent();
15460 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15461 const TargetInstrInfo *TII,
15462 const X86Subtarget* Subtarget) {
15463 DebugLoc dl = MI->getDebugLoc();
15465 // Address into RAX/EAX, other two args into ECX, EDX.
15466 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15467 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15468 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15469 for (int i = 0; i < X86::AddrNumOperands; ++i)
15470 MIB.addOperand(MI->getOperand(i));
15472 unsigned ValOps = X86::AddrNumOperands;
15473 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15474 .addReg(MI->getOperand(ValOps).getReg());
15475 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15476 .addReg(MI->getOperand(ValOps+1).getReg());
15478 // The instruction doesn't actually take any operands though.
15479 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15481 MI->eraseFromParent(); // The pseudo is gone now.
15485 MachineBasicBlock *
15486 X86TargetLowering::EmitVAARG64WithCustomInserter(
15488 MachineBasicBlock *MBB) const {
15489 // Emit va_arg instruction on X86-64.
15491 // Operands to this pseudo-instruction:
15492 // 0 ) Output : destination address (reg)
15493 // 1-5) Input : va_list address (addr, i64mem)
15494 // 6 ) ArgSize : Size (in bytes) of vararg type
15495 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15496 // 8 ) Align : Alignment of type
15497 // 9 ) EFLAGS (implicit-def)
15499 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15500 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15502 unsigned DestReg = MI->getOperand(0).getReg();
15503 MachineOperand &Base = MI->getOperand(1);
15504 MachineOperand &Scale = MI->getOperand(2);
15505 MachineOperand &Index = MI->getOperand(3);
15506 MachineOperand &Disp = MI->getOperand(4);
15507 MachineOperand &Segment = MI->getOperand(5);
15508 unsigned ArgSize = MI->getOperand(6).getImm();
15509 unsigned ArgMode = MI->getOperand(7).getImm();
15510 unsigned Align = MI->getOperand(8).getImm();
15512 // Memory Reference
15513 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15514 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15515 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15517 // Machine Information
15518 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15519 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15520 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15521 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15522 DebugLoc DL = MI->getDebugLoc();
15524 // struct va_list {
15527 // i64 overflow_area (address)
15528 // i64 reg_save_area (address)
15530 // sizeof(va_list) = 24
15531 // alignment(va_list) = 8
15533 unsigned TotalNumIntRegs = 6;
15534 unsigned TotalNumXMMRegs = 8;
15535 bool UseGPOffset = (ArgMode == 1);
15536 bool UseFPOffset = (ArgMode == 2);
15537 unsigned MaxOffset = TotalNumIntRegs * 8 +
15538 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15540 /* Align ArgSize to a multiple of 8 */
15541 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15542 bool NeedsAlign = (Align > 8);
15544 MachineBasicBlock *thisMBB = MBB;
15545 MachineBasicBlock *overflowMBB;
15546 MachineBasicBlock *offsetMBB;
15547 MachineBasicBlock *endMBB;
15549 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15550 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15551 unsigned OffsetReg = 0;
15553 if (!UseGPOffset && !UseFPOffset) {
15554 // If we only pull from the overflow region, we don't create a branch.
15555 // We don't need to alter control flow.
15556 OffsetDestReg = 0; // unused
15557 OverflowDestReg = DestReg;
15560 overflowMBB = thisMBB;
15563 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15564 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15565 // If not, pull from overflow_area. (branch to overflowMBB)
15570 // offsetMBB overflowMBB
15575 // Registers for the PHI in endMBB
15576 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15577 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15579 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15580 MachineFunction *MF = MBB->getParent();
15581 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15582 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15583 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15585 MachineFunction::iterator MBBIter = MBB;
15588 // Insert the new basic blocks
15589 MF->insert(MBBIter, offsetMBB);
15590 MF->insert(MBBIter, overflowMBB);
15591 MF->insert(MBBIter, endMBB);
15593 // Transfer the remainder of MBB and its successor edges to endMBB.
15594 endMBB->splice(endMBB->begin(), thisMBB,
15595 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15596 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15598 // Make offsetMBB and overflowMBB successors of thisMBB
15599 thisMBB->addSuccessor(offsetMBB);
15600 thisMBB->addSuccessor(overflowMBB);
15602 // endMBB is a successor of both offsetMBB and overflowMBB
15603 offsetMBB->addSuccessor(endMBB);
15604 overflowMBB->addSuccessor(endMBB);
15606 // Load the offset value into a register
15607 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15608 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15612 .addDisp(Disp, UseFPOffset ? 4 : 0)
15613 .addOperand(Segment)
15614 .setMemRefs(MMOBegin, MMOEnd);
15616 // Check if there is enough room left to pull this argument.
15617 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15619 .addImm(MaxOffset + 8 - ArgSizeA8);
15621 // Branch to "overflowMBB" if offset >= max
15622 // Fall through to "offsetMBB" otherwise
15623 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15624 .addMBB(overflowMBB);
15627 // In offsetMBB, emit code to use the reg_save_area.
15629 assert(OffsetReg != 0);
15631 // Read the reg_save_area address.
15632 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15633 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15638 .addOperand(Segment)
15639 .setMemRefs(MMOBegin, MMOEnd);
15641 // Zero-extend the offset
15642 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15643 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15646 .addImm(X86::sub_32bit);
15648 // Add the offset to the reg_save_area to get the final address.
15649 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15650 .addReg(OffsetReg64)
15651 .addReg(RegSaveReg);
15653 // Compute the offset for the next argument
15654 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15655 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15657 .addImm(UseFPOffset ? 16 : 8);
15659 // Store it back into the va_list.
15660 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15664 .addDisp(Disp, UseFPOffset ? 4 : 0)
15665 .addOperand(Segment)
15666 .addReg(NextOffsetReg)
15667 .setMemRefs(MMOBegin, MMOEnd);
15670 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15675 // Emit code to use overflow area
15678 // Load the overflow_area address into a register.
15679 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15680 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15685 .addOperand(Segment)
15686 .setMemRefs(MMOBegin, MMOEnd);
15688 // If we need to align it, do so. Otherwise, just copy the address
15689 // to OverflowDestReg.
15691 // Align the overflow address
15692 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15693 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15695 // aligned_addr = (addr + (align-1)) & ~(align-1)
15696 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15697 .addReg(OverflowAddrReg)
15700 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15702 .addImm(~(uint64_t)(Align-1));
15704 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15705 .addReg(OverflowAddrReg);
15708 // Compute the next overflow address after this argument.
15709 // (the overflow address should be kept 8-byte aligned)
15710 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15711 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15712 .addReg(OverflowDestReg)
15713 .addImm(ArgSizeA8);
15715 // Store the new overflow address.
15716 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15721 .addOperand(Segment)
15722 .addReg(NextAddrReg)
15723 .setMemRefs(MMOBegin, MMOEnd);
15725 // If we branched, emit the PHI to the front of endMBB.
15727 BuildMI(*endMBB, endMBB->begin(), DL,
15728 TII->get(X86::PHI), DestReg)
15729 .addReg(OffsetDestReg).addMBB(offsetMBB)
15730 .addReg(OverflowDestReg).addMBB(overflowMBB);
15733 // Erase the pseudo instruction
15734 MI->eraseFromParent();
15739 MachineBasicBlock *
15740 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15742 MachineBasicBlock *MBB) const {
15743 // Emit code to save XMM registers to the stack. The ABI says that the
15744 // number of registers to save is given in %al, so it's theoretically
15745 // possible to do an indirect jump trick to avoid saving all of them,
15746 // however this code takes a simpler approach and just executes all
15747 // of the stores if %al is non-zero. It's less code, and it's probably
15748 // easier on the hardware branch predictor, and stores aren't all that
15749 // expensive anyway.
15751 // Create the new basic blocks. One block contains all the XMM stores,
15752 // and one block is the final destination regardless of whether any
15753 // stores were performed.
15754 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15755 MachineFunction *F = MBB->getParent();
15756 MachineFunction::iterator MBBIter = MBB;
15758 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15759 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15760 F->insert(MBBIter, XMMSaveMBB);
15761 F->insert(MBBIter, EndMBB);
15763 // Transfer the remainder of MBB and its successor edges to EndMBB.
15764 EndMBB->splice(EndMBB->begin(), MBB,
15765 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15766 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15768 // The original block will now fall through to the XMM save block.
15769 MBB->addSuccessor(XMMSaveMBB);
15770 // The XMMSaveMBB will fall through to the end block.
15771 XMMSaveMBB->addSuccessor(EndMBB);
15773 // Now add the instructions.
15774 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15775 DebugLoc DL = MI->getDebugLoc();
15777 unsigned CountReg = MI->getOperand(0).getReg();
15778 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15779 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15781 if (!Subtarget->isTargetWin64()) {
15782 // If %al is 0, branch around the XMM save block.
15783 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15784 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15785 MBB->addSuccessor(EndMBB);
15788 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15789 // that was just emitted, but clearly shouldn't be "saved".
15790 assert((MI->getNumOperands() <= 3 ||
15791 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15792 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15793 && "Expected last argument to be EFLAGS");
15794 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15795 // In the XMM save block, save all the XMM argument registers.
15796 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15797 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15798 MachineMemOperand *MMO =
15799 F->getMachineMemOperand(
15800 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15801 MachineMemOperand::MOStore,
15802 /*Size=*/16, /*Align=*/16);
15803 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15804 .addFrameIndex(RegSaveFrameIndex)
15805 .addImm(/*Scale=*/1)
15806 .addReg(/*IndexReg=*/0)
15807 .addImm(/*Disp=*/Offset)
15808 .addReg(/*Segment=*/0)
15809 .addReg(MI->getOperand(i).getReg())
15810 .addMemOperand(MMO);
15813 MI->eraseFromParent(); // The pseudo instruction is gone now.
15818 // The EFLAGS operand of SelectItr might be missing a kill marker
15819 // because there were multiple uses of EFLAGS, and ISel didn't know
15820 // which to mark. Figure out whether SelectItr should have had a
15821 // kill marker, and set it if it should. Returns the correct kill
15823 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15824 MachineBasicBlock* BB,
15825 const TargetRegisterInfo* TRI) {
15826 // Scan forward through BB for a use/def of EFLAGS.
15827 MachineBasicBlock::iterator miI(std::next(SelectItr));
15828 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15829 const MachineInstr& mi = *miI;
15830 if (mi.readsRegister(X86::EFLAGS))
15832 if (mi.definesRegister(X86::EFLAGS))
15833 break; // Should have kill-flag - update below.
15836 // If we hit the end of the block, check whether EFLAGS is live into a
15838 if (miI == BB->end()) {
15839 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15840 sEnd = BB->succ_end();
15841 sItr != sEnd; ++sItr) {
15842 MachineBasicBlock* succ = *sItr;
15843 if (succ->isLiveIn(X86::EFLAGS))
15848 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15849 // out. SelectMI should have a kill flag on EFLAGS.
15850 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15854 MachineBasicBlock *
15855 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15856 MachineBasicBlock *BB) const {
15857 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15858 DebugLoc DL = MI->getDebugLoc();
15860 // To "insert" a SELECT_CC instruction, we actually have to insert the
15861 // diamond control-flow pattern. The incoming instruction knows the
15862 // destination vreg to set, the condition code register to branch on, the
15863 // true/false values to select between, and a branch opcode to use.
15864 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15865 MachineFunction::iterator It = BB;
15871 // cmpTY ccX, r1, r2
15873 // fallthrough --> copy0MBB
15874 MachineBasicBlock *thisMBB = BB;
15875 MachineFunction *F = BB->getParent();
15876 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15877 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15878 F->insert(It, copy0MBB);
15879 F->insert(It, sinkMBB);
15881 // If the EFLAGS register isn't dead in the terminator, then claim that it's
15882 // live into the sink and copy blocks.
15883 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15884 if (!MI->killsRegister(X86::EFLAGS) &&
15885 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15886 copy0MBB->addLiveIn(X86::EFLAGS);
15887 sinkMBB->addLiveIn(X86::EFLAGS);
15890 // Transfer the remainder of BB and its successor edges to sinkMBB.
15891 sinkMBB->splice(sinkMBB->begin(), BB,
15892 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15893 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15895 // Add the true and fallthrough blocks as its successors.
15896 BB->addSuccessor(copy0MBB);
15897 BB->addSuccessor(sinkMBB);
15899 // Create the conditional branch instruction.
15901 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15902 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15905 // %FalseValue = ...
15906 // # fallthrough to sinkMBB
15907 copy0MBB->addSuccessor(sinkMBB);
15910 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15912 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15913 TII->get(X86::PHI), MI->getOperand(0).getReg())
15914 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15915 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15917 MI->eraseFromParent(); // The pseudo instruction is gone now.
15921 MachineBasicBlock *
15922 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15923 bool Is64Bit) const {
15924 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15925 DebugLoc DL = MI->getDebugLoc();
15926 MachineFunction *MF = BB->getParent();
15927 const BasicBlock *LLVM_BB = BB->getBasicBlock();
15929 assert(MF->shouldSplitStack());
15931 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15932 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15935 // ... [Till the alloca]
15936 // If stacklet is not large enough, jump to mallocMBB
15939 // Allocate by subtracting from RSP
15940 // Jump to continueMBB
15943 // Allocate by call to runtime
15947 // [rest of original BB]
15950 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15951 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15952 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15954 MachineRegisterInfo &MRI = MF->getRegInfo();
15955 const TargetRegisterClass *AddrRegClass =
15956 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15958 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15959 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15960 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15961 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15962 sizeVReg = MI->getOperand(1).getReg(),
15963 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15965 MachineFunction::iterator MBBIter = BB;
15968 MF->insert(MBBIter, bumpMBB);
15969 MF->insert(MBBIter, mallocMBB);
15970 MF->insert(MBBIter, continueMBB);
15972 continueMBB->splice(continueMBB->begin(), BB,
15973 std::next(MachineBasicBlock::iterator(MI)), BB->end());
15974 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15976 // Add code to the main basic block to check if the stack limit has been hit,
15977 // and if so, jump to mallocMBB otherwise to bumpMBB.
15978 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15979 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15980 .addReg(tmpSPVReg).addReg(sizeVReg);
15981 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15982 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15983 .addReg(SPLimitVReg);
15984 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15986 // bumpMBB simply decreases the stack pointer, since we know the current
15987 // stacklet has enough space.
15988 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15989 .addReg(SPLimitVReg);
15990 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15991 .addReg(SPLimitVReg);
15992 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15994 // Calls into a routine in libgcc to allocate more space from the heap.
15995 const uint32_t *RegMask =
15996 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15998 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16000 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16001 .addExternalSymbol("__morestack_allocate_stack_space")
16002 .addRegMask(RegMask)
16003 .addReg(X86::RDI, RegState::Implicit)
16004 .addReg(X86::RAX, RegState::ImplicitDefine);
16006 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16008 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16009 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16010 .addExternalSymbol("__morestack_allocate_stack_space")
16011 .addRegMask(RegMask)
16012 .addReg(X86::EAX, RegState::ImplicitDefine);
16016 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16019 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16020 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16021 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16023 // Set up the CFG correctly.
16024 BB->addSuccessor(bumpMBB);
16025 BB->addSuccessor(mallocMBB);
16026 mallocMBB->addSuccessor(continueMBB);
16027 bumpMBB->addSuccessor(continueMBB);
16029 // Take care of the PHI nodes.
16030 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16031 MI->getOperand(0).getReg())
16032 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16033 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16035 // Delete the original pseudo instruction.
16036 MI->eraseFromParent();
16039 return continueMBB;
16042 MachineBasicBlock *
16043 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16044 MachineBasicBlock *BB) const {
16045 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16046 DebugLoc DL = MI->getDebugLoc();
16048 assert(!Subtarget->isTargetMacho());
16050 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16051 // non-trivial part is impdef of ESP.
16053 if (Subtarget->isTargetWin64()) {
16054 if (Subtarget->isTargetCygMing()) {
16055 // ___chkstk(Mingw64):
16056 // Clobbers R10, R11, RAX and EFLAGS.
16058 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16059 .addExternalSymbol("___chkstk")
16060 .addReg(X86::RAX, RegState::Implicit)
16061 .addReg(X86::RSP, RegState::Implicit)
16062 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16063 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16064 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16066 // __chkstk(MSVCRT): does not update stack pointer.
16067 // Clobbers R10, R11 and EFLAGS.
16068 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16069 .addExternalSymbol("__chkstk")
16070 .addReg(X86::RAX, RegState::Implicit)
16071 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16072 // RAX has the offset to be subtracted from RSP.
16073 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16078 const char *StackProbeSymbol =
16079 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16081 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16082 .addExternalSymbol(StackProbeSymbol)
16083 .addReg(X86::EAX, RegState::Implicit)
16084 .addReg(X86::ESP, RegState::Implicit)
16085 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16086 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16087 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16090 MI->eraseFromParent(); // The pseudo instruction is gone now.
16094 MachineBasicBlock *
16095 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16096 MachineBasicBlock *BB) const {
16097 // This is pretty easy. We're taking the value that we received from
16098 // our load from the relocation, sticking it in either RDI (x86-64)
16099 // or EAX and doing an indirect call. The return value will then
16100 // be in the normal return register.
16101 const X86InstrInfo *TII
16102 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16103 DebugLoc DL = MI->getDebugLoc();
16104 MachineFunction *F = BB->getParent();
16106 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16107 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16109 // Get a register mask for the lowered call.
16110 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16111 // proper register mask.
16112 const uint32_t *RegMask =
16113 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16114 if (Subtarget->is64Bit()) {
16115 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16116 TII->get(X86::MOV64rm), X86::RDI)
16118 .addImm(0).addReg(0)
16119 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16120 MI->getOperand(3).getTargetFlags())
16122 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16123 addDirectMem(MIB, X86::RDI);
16124 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16125 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16126 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16127 TII->get(X86::MOV32rm), X86::EAX)
16129 .addImm(0).addReg(0)
16130 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16131 MI->getOperand(3).getTargetFlags())
16133 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16134 addDirectMem(MIB, X86::EAX);
16135 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16137 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16138 TII->get(X86::MOV32rm), X86::EAX)
16139 .addReg(TII->getGlobalBaseReg(F))
16140 .addImm(0).addReg(0)
16141 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16142 MI->getOperand(3).getTargetFlags())
16144 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16145 addDirectMem(MIB, X86::EAX);
16146 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16149 MI->eraseFromParent(); // The pseudo instruction is gone now.
16153 MachineBasicBlock *
16154 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16155 MachineBasicBlock *MBB) const {
16156 DebugLoc DL = MI->getDebugLoc();
16157 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16159 MachineFunction *MF = MBB->getParent();
16160 MachineRegisterInfo &MRI = MF->getRegInfo();
16162 const BasicBlock *BB = MBB->getBasicBlock();
16163 MachineFunction::iterator I = MBB;
16166 // Memory Reference
16167 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16168 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16171 unsigned MemOpndSlot = 0;
16173 unsigned CurOp = 0;
16175 DstReg = MI->getOperand(CurOp++).getReg();
16176 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16177 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16178 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16179 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16181 MemOpndSlot = CurOp;
16183 MVT PVT = getPointerTy();
16184 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16185 "Invalid Pointer Size!");
16187 // For v = setjmp(buf), we generate
16190 // buf[LabelOffset] = restoreMBB
16191 // SjLjSetup restoreMBB
16197 // v = phi(main, restore)
16202 MachineBasicBlock *thisMBB = MBB;
16203 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16204 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16205 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16206 MF->insert(I, mainMBB);
16207 MF->insert(I, sinkMBB);
16208 MF->push_back(restoreMBB);
16210 MachineInstrBuilder MIB;
16212 // Transfer the remainder of BB and its successor edges to sinkMBB.
16213 sinkMBB->splice(sinkMBB->begin(), MBB,
16214 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16215 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16218 unsigned PtrStoreOpc = 0;
16219 unsigned LabelReg = 0;
16220 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16221 Reloc::Model RM = getTargetMachine().getRelocationModel();
16222 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16223 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16225 // Prepare IP either in reg or imm.
16226 if (!UseImmLabel) {
16227 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16228 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16229 LabelReg = MRI.createVirtualRegister(PtrRC);
16230 if (Subtarget->is64Bit()) {
16231 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16235 .addMBB(restoreMBB)
16238 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16239 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16240 .addReg(XII->getGlobalBaseReg(MF))
16243 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16247 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16249 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16250 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16251 if (i == X86::AddrDisp)
16252 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16254 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16257 MIB.addReg(LabelReg);
16259 MIB.addMBB(restoreMBB);
16260 MIB.setMemRefs(MMOBegin, MMOEnd);
16262 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16263 .addMBB(restoreMBB);
16265 const X86RegisterInfo *RegInfo =
16266 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16267 MIB.addRegMask(RegInfo->getNoPreservedMask());
16268 thisMBB->addSuccessor(mainMBB);
16269 thisMBB->addSuccessor(restoreMBB);
16273 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16274 mainMBB->addSuccessor(sinkMBB);
16277 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16278 TII->get(X86::PHI), DstReg)
16279 .addReg(mainDstReg).addMBB(mainMBB)
16280 .addReg(restoreDstReg).addMBB(restoreMBB);
16283 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16284 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16285 restoreMBB->addSuccessor(sinkMBB);
16287 MI->eraseFromParent();
16291 MachineBasicBlock *
16292 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16293 MachineBasicBlock *MBB) const {
16294 DebugLoc DL = MI->getDebugLoc();
16295 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16297 MachineFunction *MF = MBB->getParent();
16298 MachineRegisterInfo &MRI = MF->getRegInfo();
16300 // Memory Reference
16301 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16302 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16304 MVT PVT = getPointerTy();
16305 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16306 "Invalid Pointer Size!");
16308 const TargetRegisterClass *RC =
16309 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16310 unsigned Tmp = MRI.createVirtualRegister(RC);
16311 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16312 const X86RegisterInfo *RegInfo =
16313 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16314 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16315 unsigned SP = RegInfo->getStackRegister();
16317 MachineInstrBuilder MIB;
16319 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16320 const int64_t SPOffset = 2 * PVT.getStoreSize();
16322 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16323 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16326 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16327 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16328 MIB.addOperand(MI->getOperand(i));
16329 MIB.setMemRefs(MMOBegin, MMOEnd);
16331 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16332 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16333 if (i == X86::AddrDisp)
16334 MIB.addDisp(MI->getOperand(i), LabelOffset);
16336 MIB.addOperand(MI->getOperand(i));
16338 MIB.setMemRefs(MMOBegin, MMOEnd);
16340 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16341 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16342 if (i == X86::AddrDisp)
16343 MIB.addDisp(MI->getOperand(i), SPOffset);
16345 MIB.addOperand(MI->getOperand(i));
16347 MIB.setMemRefs(MMOBegin, MMOEnd);
16349 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16351 MI->eraseFromParent();
16355 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16356 // accumulator loops. Writing back to the accumulator allows the coalescer
16357 // to remove extra copies in the loop.
16358 MachineBasicBlock *
16359 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16360 MachineBasicBlock *MBB) const {
16361 MachineOperand &AddendOp = MI->getOperand(3);
16363 // Bail out early if the addend isn't a register - we can't switch these.
16364 if (!AddendOp.isReg())
16367 MachineFunction &MF = *MBB->getParent();
16368 MachineRegisterInfo &MRI = MF.getRegInfo();
16370 // Check whether the addend is defined by a PHI:
16371 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16372 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16373 if (!AddendDef.isPHI())
16376 // Look for the following pattern:
16378 // %addend = phi [%entry, 0], [%loop, %result]
16380 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16384 // %addend = phi [%entry, 0], [%loop, %result]
16386 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16388 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16389 assert(AddendDef.getOperand(i).isReg());
16390 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16391 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16392 if (&PHISrcInst == MI) {
16393 // Found a matching instruction.
16394 unsigned NewFMAOpc = 0;
16395 switch (MI->getOpcode()) {
16396 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16397 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16398 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16399 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16400 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16401 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16402 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16403 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16404 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16405 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16406 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16407 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16408 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16409 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16410 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16411 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16412 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16413 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16414 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16415 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16416 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16417 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16418 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16419 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16420 default: llvm_unreachable("Unrecognized FMA variant.");
16423 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16424 MachineInstrBuilder MIB =
16425 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16426 .addOperand(MI->getOperand(0))
16427 .addOperand(MI->getOperand(3))
16428 .addOperand(MI->getOperand(2))
16429 .addOperand(MI->getOperand(1));
16430 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16431 MI->eraseFromParent();
16438 MachineBasicBlock *
16439 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16440 MachineBasicBlock *BB) const {
16441 switch (MI->getOpcode()) {
16442 default: llvm_unreachable("Unexpected instr type to insert");
16443 case X86::TAILJMPd64:
16444 case X86::TAILJMPr64:
16445 case X86::TAILJMPm64:
16446 llvm_unreachable("TAILJMP64 would not be touched here.");
16447 case X86::TCRETURNdi64:
16448 case X86::TCRETURNri64:
16449 case X86::TCRETURNmi64:
16451 case X86::WIN_ALLOCA:
16452 return EmitLoweredWinAlloca(MI, BB);
16453 case X86::SEG_ALLOCA_32:
16454 return EmitLoweredSegAlloca(MI, BB, false);
16455 case X86::SEG_ALLOCA_64:
16456 return EmitLoweredSegAlloca(MI, BB, true);
16457 case X86::TLSCall_32:
16458 case X86::TLSCall_64:
16459 return EmitLoweredTLSCall(MI, BB);
16460 case X86::CMOV_GR8:
16461 case X86::CMOV_FR32:
16462 case X86::CMOV_FR64:
16463 case X86::CMOV_V4F32:
16464 case X86::CMOV_V2F64:
16465 case X86::CMOV_V2I64:
16466 case X86::CMOV_V8F32:
16467 case X86::CMOV_V4F64:
16468 case X86::CMOV_V4I64:
16469 case X86::CMOV_V16F32:
16470 case X86::CMOV_V8F64:
16471 case X86::CMOV_V8I64:
16472 case X86::CMOV_GR16:
16473 case X86::CMOV_GR32:
16474 case X86::CMOV_RFP32:
16475 case X86::CMOV_RFP64:
16476 case X86::CMOV_RFP80:
16477 return EmitLoweredSelect(MI, BB);
16479 case X86::FP32_TO_INT16_IN_MEM:
16480 case X86::FP32_TO_INT32_IN_MEM:
16481 case X86::FP32_TO_INT64_IN_MEM:
16482 case X86::FP64_TO_INT16_IN_MEM:
16483 case X86::FP64_TO_INT32_IN_MEM:
16484 case X86::FP64_TO_INT64_IN_MEM:
16485 case X86::FP80_TO_INT16_IN_MEM:
16486 case X86::FP80_TO_INT32_IN_MEM:
16487 case X86::FP80_TO_INT64_IN_MEM: {
16488 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16489 DebugLoc DL = MI->getDebugLoc();
16491 // Change the floating point control register to use "round towards zero"
16492 // mode when truncating to an integer value.
16493 MachineFunction *F = BB->getParent();
16494 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16495 addFrameReference(BuildMI(*BB, MI, DL,
16496 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16498 // Load the old value of the high byte of the control word...
16500 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16501 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16504 // Set the high part to be round to zero...
16505 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16508 // Reload the modified control word now...
16509 addFrameReference(BuildMI(*BB, MI, DL,
16510 TII->get(X86::FLDCW16m)), CWFrameIdx);
16512 // Restore the memory image of control word to original value
16513 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16516 // Get the X86 opcode to use.
16518 switch (MI->getOpcode()) {
16519 default: llvm_unreachable("illegal opcode!");
16520 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16521 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16522 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16523 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16524 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16525 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16526 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16527 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16528 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16532 MachineOperand &Op = MI->getOperand(0);
16534 AM.BaseType = X86AddressMode::RegBase;
16535 AM.Base.Reg = Op.getReg();
16537 AM.BaseType = X86AddressMode::FrameIndexBase;
16538 AM.Base.FrameIndex = Op.getIndex();
16540 Op = MI->getOperand(1);
16542 AM.Scale = Op.getImm();
16543 Op = MI->getOperand(2);
16545 AM.IndexReg = Op.getImm();
16546 Op = MI->getOperand(3);
16547 if (Op.isGlobal()) {
16548 AM.GV = Op.getGlobal();
16550 AM.Disp = Op.getImm();
16552 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16553 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16555 // Reload the original control word now.
16556 addFrameReference(BuildMI(*BB, MI, DL,
16557 TII->get(X86::FLDCW16m)), CWFrameIdx);
16559 MI->eraseFromParent(); // The pseudo instruction is gone now.
16562 // String/text processing lowering.
16563 case X86::PCMPISTRM128REG:
16564 case X86::VPCMPISTRM128REG:
16565 case X86::PCMPISTRM128MEM:
16566 case X86::VPCMPISTRM128MEM:
16567 case X86::PCMPESTRM128REG:
16568 case X86::VPCMPESTRM128REG:
16569 case X86::PCMPESTRM128MEM:
16570 case X86::VPCMPESTRM128MEM:
16571 assert(Subtarget->hasSSE42() &&
16572 "Target must have SSE4.2 or AVX features enabled");
16573 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16575 // String/text processing lowering.
16576 case X86::PCMPISTRIREG:
16577 case X86::VPCMPISTRIREG:
16578 case X86::PCMPISTRIMEM:
16579 case X86::VPCMPISTRIMEM:
16580 case X86::PCMPESTRIREG:
16581 case X86::VPCMPESTRIREG:
16582 case X86::PCMPESTRIMEM:
16583 case X86::VPCMPESTRIMEM:
16584 assert(Subtarget->hasSSE42() &&
16585 "Target must have SSE4.2 or AVX features enabled");
16586 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16588 // Thread synchronization.
16590 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16594 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16596 // Atomic Lowering.
16597 case X86::ATOMAND8:
16598 case X86::ATOMAND16:
16599 case X86::ATOMAND32:
16600 case X86::ATOMAND64:
16603 case X86::ATOMOR16:
16604 case X86::ATOMOR32:
16605 case X86::ATOMOR64:
16607 case X86::ATOMXOR16:
16608 case X86::ATOMXOR8:
16609 case X86::ATOMXOR32:
16610 case X86::ATOMXOR64:
16612 case X86::ATOMNAND8:
16613 case X86::ATOMNAND16:
16614 case X86::ATOMNAND32:
16615 case X86::ATOMNAND64:
16617 case X86::ATOMMAX8:
16618 case X86::ATOMMAX16:
16619 case X86::ATOMMAX32:
16620 case X86::ATOMMAX64:
16622 case X86::ATOMMIN8:
16623 case X86::ATOMMIN16:
16624 case X86::ATOMMIN32:
16625 case X86::ATOMMIN64:
16627 case X86::ATOMUMAX8:
16628 case X86::ATOMUMAX16:
16629 case X86::ATOMUMAX32:
16630 case X86::ATOMUMAX64:
16632 case X86::ATOMUMIN8:
16633 case X86::ATOMUMIN16:
16634 case X86::ATOMUMIN32:
16635 case X86::ATOMUMIN64:
16636 return EmitAtomicLoadArith(MI, BB);
16638 // This group does 64-bit operations on a 32-bit host.
16639 case X86::ATOMAND6432:
16640 case X86::ATOMOR6432:
16641 case X86::ATOMXOR6432:
16642 case X86::ATOMNAND6432:
16643 case X86::ATOMADD6432:
16644 case X86::ATOMSUB6432:
16645 case X86::ATOMMAX6432:
16646 case X86::ATOMMIN6432:
16647 case X86::ATOMUMAX6432:
16648 case X86::ATOMUMIN6432:
16649 case X86::ATOMSWAP6432:
16650 return EmitAtomicLoadArith6432(MI, BB);
16652 case X86::VASTART_SAVE_XMM_REGS:
16653 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16655 case X86::VAARG_64:
16656 return EmitVAARG64WithCustomInserter(MI, BB);
16658 case X86::EH_SjLj_SetJmp32:
16659 case X86::EH_SjLj_SetJmp64:
16660 return emitEHSjLjSetJmp(MI, BB);
16662 case X86::EH_SjLj_LongJmp32:
16663 case X86::EH_SjLj_LongJmp64:
16664 return emitEHSjLjLongJmp(MI, BB);
16666 case TargetOpcode::STACKMAP:
16667 case TargetOpcode::PATCHPOINT:
16668 return emitPatchPoint(MI, BB);
16670 case X86::VFMADDPDr213r:
16671 case X86::VFMADDPSr213r:
16672 case X86::VFMADDSDr213r:
16673 case X86::VFMADDSSr213r:
16674 case X86::VFMSUBPDr213r:
16675 case X86::VFMSUBPSr213r:
16676 case X86::VFMSUBSDr213r:
16677 case X86::VFMSUBSSr213r:
16678 case X86::VFNMADDPDr213r:
16679 case X86::VFNMADDPSr213r:
16680 case X86::VFNMADDSDr213r:
16681 case X86::VFNMADDSSr213r:
16682 case X86::VFNMSUBPDr213r:
16683 case X86::VFNMSUBPSr213r:
16684 case X86::VFNMSUBSDr213r:
16685 case X86::VFNMSUBSSr213r:
16686 case X86::VFMADDPDr213rY:
16687 case X86::VFMADDPSr213rY:
16688 case X86::VFMSUBPDr213rY:
16689 case X86::VFMSUBPSr213rY:
16690 case X86::VFNMADDPDr213rY:
16691 case X86::VFNMADDPSr213rY:
16692 case X86::VFNMSUBPDr213rY:
16693 case X86::VFNMSUBPSr213rY:
16694 return emitFMA3Instr(MI, BB);
16698 //===----------------------------------------------------------------------===//
16699 // X86 Optimization Hooks
16700 //===----------------------------------------------------------------------===//
16702 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16705 const SelectionDAG &DAG,
16706 unsigned Depth) const {
16707 unsigned BitWidth = KnownZero.getBitWidth();
16708 unsigned Opc = Op.getOpcode();
16709 assert((Opc >= ISD::BUILTIN_OP_END ||
16710 Opc == ISD::INTRINSIC_WO_CHAIN ||
16711 Opc == ISD::INTRINSIC_W_CHAIN ||
16712 Opc == ISD::INTRINSIC_VOID) &&
16713 "Should use MaskedValueIsZero if you don't know whether Op"
16714 " is a target node!");
16716 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16730 // These nodes' second result is a boolean.
16731 if (Op.getResNo() == 0)
16734 case X86ISD::SETCC:
16735 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16737 case ISD::INTRINSIC_WO_CHAIN: {
16738 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16739 unsigned NumLoBits = 0;
16742 case Intrinsic::x86_sse_movmsk_ps:
16743 case Intrinsic::x86_avx_movmsk_ps_256:
16744 case Intrinsic::x86_sse2_movmsk_pd:
16745 case Intrinsic::x86_avx_movmsk_pd_256:
16746 case Intrinsic::x86_mmx_pmovmskb:
16747 case Intrinsic::x86_sse2_pmovmskb_128:
16748 case Intrinsic::x86_avx2_pmovmskb: {
16749 // High bits of movmskp{s|d}, pmovmskb are known zero.
16751 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16752 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16753 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16754 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16755 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16756 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16757 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16758 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16760 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16769 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16771 const SelectionDAG &,
16772 unsigned Depth) const {
16773 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16774 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16775 return Op.getValueType().getScalarType().getSizeInBits();
16781 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16782 /// node is a GlobalAddress + offset.
16783 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16784 const GlobalValue* &GA,
16785 int64_t &Offset) const {
16786 if (N->getOpcode() == X86ISD::Wrapper) {
16787 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16788 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16789 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16793 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16796 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16797 /// same as extracting the high 128-bit part of 256-bit vector and then
16798 /// inserting the result into the low part of a new 256-bit vector
16799 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16800 EVT VT = SVOp->getValueType(0);
16801 unsigned NumElems = VT.getVectorNumElements();
16803 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16804 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16805 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16806 SVOp->getMaskElt(j) >= 0)
16812 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16813 /// same as extracting the low 128-bit part of 256-bit vector and then
16814 /// inserting the result into the high part of a new 256-bit vector
16815 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16816 EVT VT = SVOp->getValueType(0);
16817 unsigned NumElems = VT.getVectorNumElements();
16819 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16820 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16821 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16822 SVOp->getMaskElt(j) >= 0)
16828 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16829 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16830 TargetLowering::DAGCombinerInfo &DCI,
16831 const X86Subtarget* Subtarget) {
16833 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16834 SDValue V1 = SVOp->getOperand(0);
16835 SDValue V2 = SVOp->getOperand(1);
16836 EVT VT = SVOp->getValueType(0);
16837 unsigned NumElems = VT.getVectorNumElements();
16839 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16840 V2.getOpcode() == ISD::CONCAT_VECTORS) {
16844 // V UNDEF BUILD_VECTOR UNDEF
16846 // CONCAT_VECTOR CONCAT_VECTOR
16849 // RESULT: V + zero extended
16851 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16852 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16853 V1.getOperand(1).getOpcode() != ISD::UNDEF)
16856 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16859 // To match the shuffle mask, the first half of the mask should
16860 // be exactly the first vector, and all the rest a splat with the
16861 // first element of the second one.
16862 for (unsigned i = 0; i != NumElems/2; ++i)
16863 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16864 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16867 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16868 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16869 if (Ld->hasNUsesOfValue(1, 0)) {
16870 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16871 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16873 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16874 array_lengthof(Ops),
16876 Ld->getPointerInfo(),
16877 Ld->getAlignment(),
16878 false/*isVolatile*/, true/*ReadMem*/,
16879 false/*WriteMem*/);
16881 // Make sure the newly-created LOAD is in the same position as Ld in
16882 // terms of dependency. We create a TokenFactor for Ld and ResNode,
16883 // and update uses of Ld's output chain to use the TokenFactor.
16884 if (Ld->hasAnyUseOfValue(1)) {
16885 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16886 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16887 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16888 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16889 SDValue(ResNode.getNode(), 1));
16892 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16896 // Emit a zeroed vector and insert the desired subvector on its
16898 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16899 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16900 return DCI.CombineTo(N, InsV);
16903 //===--------------------------------------------------------------------===//
16904 // Combine some shuffles into subvector extracts and inserts:
16907 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16908 if (isShuffleHigh128VectorInsertLow(SVOp)) {
16909 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16910 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16911 return DCI.CombineTo(N, InsV);
16914 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16915 if (isShuffleLow128VectorInsertHigh(SVOp)) {
16916 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16917 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16918 return DCI.CombineTo(N, InsV);
16924 /// PerformShuffleCombine - Performs several different shuffle combines.
16925 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16926 TargetLowering::DAGCombinerInfo &DCI,
16927 const X86Subtarget *Subtarget) {
16929 EVT VT = N->getValueType(0);
16931 // Don't create instructions with illegal types after legalize types has run.
16932 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16933 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16936 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16937 if (Subtarget->hasFp256() && VT.is256BitVector() &&
16938 N->getOpcode() == ISD::VECTOR_SHUFFLE)
16939 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16941 // Only handle 128 wide vector from here on.
16942 if (!VT.is128BitVector())
16945 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16946 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16947 // consecutive, non-overlapping, and in the right order.
16948 SmallVector<SDValue, 16> Elts;
16949 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16950 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16952 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16955 /// PerformTruncateCombine - Converts truncate operation to
16956 /// a sequence of vector shuffle operations.
16957 /// It is possible when we truncate 256-bit vector to 128-bit vector
16958 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16959 TargetLowering::DAGCombinerInfo &DCI,
16960 const X86Subtarget *Subtarget) {
16964 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16965 /// specific shuffle of a load can be folded into a single element load.
16966 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16967 /// shuffles have been customed lowered so we need to handle those here.
16968 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16969 TargetLowering::DAGCombinerInfo &DCI) {
16970 if (DCI.isBeforeLegalizeOps())
16973 SDValue InVec = N->getOperand(0);
16974 SDValue EltNo = N->getOperand(1);
16976 if (!isa<ConstantSDNode>(EltNo))
16979 EVT VT = InVec.getValueType();
16981 bool HasShuffleIntoBitcast = false;
16982 if (InVec.getOpcode() == ISD::BITCAST) {
16983 // Don't duplicate a load with other uses.
16984 if (!InVec.hasOneUse())
16986 EVT BCVT = InVec.getOperand(0).getValueType();
16987 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16989 InVec = InVec.getOperand(0);
16990 HasShuffleIntoBitcast = true;
16993 if (!isTargetShuffle(InVec.getOpcode()))
16996 // Don't duplicate a load with other uses.
16997 if (!InVec.hasOneUse())
17000 SmallVector<int, 16> ShuffleMask;
17002 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17006 // Select the input vector, guarding against out of range extract vector.
17007 unsigned NumElems = VT.getVectorNumElements();
17008 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17009 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17010 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17011 : InVec.getOperand(1);
17013 // If inputs to shuffle are the same for both ops, then allow 2 uses
17014 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17016 if (LdNode.getOpcode() == ISD::BITCAST) {
17017 // Don't duplicate a load with other uses.
17018 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17021 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17022 LdNode = LdNode.getOperand(0);
17025 if (!ISD::isNormalLoad(LdNode.getNode()))
17028 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17030 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17033 if (HasShuffleIntoBitcast) {
17034 // If there's a bitcast before the shuffle, check if the load type and
17035 // alignment is valid.
17036 unsigned Align = LN0->getAlignment();
17037 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17038 unsigned NewAlign = TLI.getDataLayout()->
17039 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17041 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17045 // All checks match so transform back to vector_shuffle so that DAG combiner
17046 // can finish the job
17049 // Create shuffle node taking into account the case that its a unary shuffle
17050 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17051 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17052 InVec.getOperand(0), Shuffle,
17054 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17055 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17059 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17060 /// generation and convert it from being a bunch of shuffles and extracts
17061 /// to a simple store and scalar loads to extract the elements.
17062 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17063 TargetLowering::DAGCombinerInfo &DCI) {
17064 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17065 if (NewOp.getNode())
17068 SDValue InputVector = N->getOperand(0);
17070 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17071 // from mmx to v2i32 has a single usage.
17072 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17073 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17074 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17075 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17076 N->getValueType(0),
17077 InputVector.getNode()->getOperand(0));
17079 // Only operate on vectors of 4 elements, where the alternative shuffling
17080 // gets to be more expensive.
17081 if (InputVector.getValueType() != MVT::v4i32)
17084 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17085 // single use which is a sign-extend or zero-extend, and all elements are
17087 SmallVector<SDNode *, 4> Uses;
17088 unsigned ExtractedElements = 0;
17089 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17090 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17091 if (UI.getUse().getResNo() != InputVector.getResNo())
17094 SDNode *Extract = *UI;
17095 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17098 if (Extract->getValueType(0) != MVT::i32)
17100 if (!Extract->hasOneUse())
17102 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17103 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17105 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17108 // Record which element was extracted.
17109 ExtractedElements |=
17110 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17112 Uses.push_back(Extract);
17115 // If not all the elements were used, this may not be worthwhile.
17116 if (ExtractedElements != 15)
17119 // Ok, we've now decided to do the transformation.
17120 SDLoc dl(InputVector);
17122 // Store the value to a temporary stack slot.
17123 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17124 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17125 MachinePointerInfo(), false, false, 0);
17127 // Replace each use (extract) with a load of the appropriate element.
17128 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17129 UE = Uses.end(); UI != UE; ++UI) {
17130 SDNode *Extract = *UI;
17132 // cOMpute the element's address.
17133 SDValue Idx = Extract->getOperand(1);
17135 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17136 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17138 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17140 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17141 StackPtr, OffsetVal);
17143 // Load the scalar.
17144 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17145 ScalarAddr, MachinePointerInfo(),
17146 false, false, false, 0);
17148 // Replace the exact with the load.
17149 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17152 // The replacement was made in place; don't return anything.
17156 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17157 static std::pair<unsigned, bool>
17158 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17159 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17160 if (!VT.isVector())
17161 return std::make_pair(0, false);
17163 bool NeedSplit = false;
17164 switch (VT.getSimpleVT().SimpleTy) {
17165 default: return std::make_pair(0, false);
17169 if (!Subtarget->hasAVX2())
17171 if (!Subtarget->hasAVX())
17172 return std::make_pair(0, false);
17177 if (!Subtarget->hasSSE2())
17178 return std::make_pair(0, false);
17181 // SSE2 has only a small subset of the operations.
17182 bool hasUnsigned = Subtarget->hasSSE41() ||
17183 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17184 bool hasSigned = Subtarget->hasSSE41() ||
17185 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17187 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17190 // Check for x CC y ? x : y.
17191 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17192 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17197 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17200 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17203 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17206 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17208 // Check for x CC y ? y : x -- a min/max with reversed arms.
17209 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17210 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17215 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17218 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17221 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17224 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17228 return std::make_pair(Opc, NeedSplit);
17231 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17233 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17234 TargetLowering::DAGCombinerInfo &DCI,
17235 const X86Subtarget *Subtarget) {
17237 SDValue Cond = N->getOperand(0);
17238 // Get the LHS/RHS of the select.
17239 SDValue LHS = N->getOperand(1);
17240 SDValue RHS = N->getOperand(2);
17241 EVT VT = LHS.getValueType();
17242 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17244 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17245 // instructions match the semantics of the common C idiom x<y?x:y but not
17246 // x<=y?x:y, because of how they handle negative zero (which can be
17247 // ignored in unsafe-math mode).
17248 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17249 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17250 (Subtarget->hasSSE2() ||
17251 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17252 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17254 unsigned Opcode = 0;
17255 // Check for x CC y ? x : y.
17256 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17257 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17261 // Converting this to a min would handle NaNs incorrectly, and swapping
17262 // the operands would cause it to handle comparisons between positive
17263 // and negative zero incorrectly.
17264 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17265 if (!DAG.getTarget().Options.UnsafeFPMath &&
17266 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17268 std::swap(LHS, RHS);
17270 Opcode = X86ISD::FMIN;
17273 // Converting this to a min would handle comparisons between positive
17274 // and negative zero incorrectly.
17275 if (!DAG.getTarget().Options.UnsafeFPMath &&
17276 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17278 Opcode = X86ISD::FMIN;
17281 // Converting this to a min would handle both negative zeros and NaNs
17282 // incorrectly, but we can swap the operands to fix both.
17283 std::swap(LHS, RHS);
17287 Opcode = X86ISD::FMIN;
17291 // Converting this to a max would handle comparisons between positive
17292 // and negative zero incorrectly.
17293 if (!DAG.getTarget().Options.UnsafeFPMath &&
17294 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17296 Opcode = X86ISD::FMAX;
17299 // Converting this to a max would handle NaNs incorrectly, and swapping
17300 // the operands would cause it to handle comparisons between positive
17301 // and negative zero incorrectly.
17302 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17303 if (!DAG.getTarget().Options.UnsafeFPMath &&
17304 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17306 std::swap(LHS, RHS);
17308 Opcode = X86ISD::FMAX;
17311 // Converting this to a max would handle both negative zeros and NaNs
17312 // incorrectly, but we can swap the operands to fix both.
17313 std::swap(LHS, RHS);
17317 Opcode = X86ISD::FMAX;
17320 // Check for x CC y ? y : x -- a min/max with reversed arms.
17321 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17322 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17326 // Converting this to a min would handle comparisons between positive
17327 // and negative zero incorrectly, and swapping the operands would
17328 // cause it to handle NaNs incorrectly.
17329 if (!DAG.getTarget().Options.UnsafeFPMath &&
17330 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17331 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17333 std::swap(LHS, RHS);
17335 Opcode = X86ISD::FMIN;
17338 // Converting this to a min would handle NaNs incorrectly.
17339 if (!DAG.getTarget().Options.UnsafeFPMath &&
17340 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17342 Opcode = X86ISD::FMIN;
17345 // Converting this to a min would handle both negative zeros and NaNs
17346 // incorrectly, but we can swap the operands to fix both.
17347 std::swap(LHS, RHS);
17351 Opcode = X86ISD::FMIN;
17355 // Converting this to a max would handle NaNs incorrectly.
17356 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17358 Opcode = X86ISD::FMAX;
17361 // Converting this to a max would handle comparisons between positive
17362 // and negative zero incorrectly, and swapping the operands would
17363 // cause it to handle NaNs incorrectly.
17364 if (!DAG.getTarget().Options.UnsafeFPMath &&
17365 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17366 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17368 std::swap(LHS, RHS);
17370 Opcode = X86ISD::FMAX;
17373 // Converting this to a max would handle both negative zeros and NaNs
17374 // incorrectly, but we can swap the operands to fix both.
17375 std::swap(LHS, RHS);
17379 Opcode = X86ISD::FMAX;
17385 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17388 EVT CondVT = Cond.getValueType();
17389 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17390 CondVT.getVectorElementType() == MVT::i1) {
17391 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17392 // lowering on AVX-512. In this case we convert it to
17393 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17394 // The same situation for all 128 and 256-bit vectors of i8 and i16
17395 EVT OpVT = LHS.getValueType();
17396 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17397 (OpVT.getVectorElementType() == MVT::i8 ||
17398 OpVT.getVectorElementType() == MVT::i16)) {
17399 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17400 DCI.AddToWorklist(Cond.getNode());
17401 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17404 // If this is a select between two integer constants, try to do some
17406 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17407 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17408 // Don't do this for crazy integer types.
17409 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17410 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17411 // so that TrueC (the true value) is larger than FalseC.
17412 bool NeedsCondInvert = false;
17414 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17415 // Efficiently invertible.
17416 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17417 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17418 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17419 NeedsCondInvert = true;
17420 std::swap(TrueC, FalseC);
17423 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17424 if (FalseC->getAPIntValue() == 0 &&
17425 TrueC->getAPIntValue().isPowerOf2()) {
17426 if (NeedsCondInvert) // Invert the condition if needed.
17427 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17428 DAG.getConstant(1, Cond.getValueType()));
17430 // Zero extend the condition if needed.
17431 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17433 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17434 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17435 DAG.getConstant(ShAmt, MVT::i8));
17438 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17439 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17440 if (NeedsCondInvert) // Invert the condition if needed.
17441 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17442 DAG.getConstant(1, Cond.getValueType()));
17444 // Zero extend the condition if needed.
17445 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17446 FalseC->getValueType(0), Cond);
17447 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17448 SDValue(FalseC, 0));
17451 // Optimize cases that will turn into an LEA instruction. This requires
17452 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17453 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17454 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17455 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17457 bool isFastMultiplier = false;
17459 switch ((unsigned char)Diff) {
17461 case 1: // result = add base, cond
17462 case 2: // result = lea base( , cond*2)
17463 case 3: // result = lea base(cond, cond*2)
17464 case 4: // result = lea base( , cond*4)
17465 case 5: // result = lea base(cond, cond*4)
17466 case 8: // result = lea base( , cond*8)
17467 case 9: // result = lea base(cond, cond*8)
17468 isFastMultiplier = true;
17473 if (isFastMultiplier) {
17474 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17475 if (NeedsCondInvert) // Invert the condition if needed.
17476 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17477 DAG.getConstant(1, Cond.getValueType()));
17479 // Zero extend the condition if needed.
17480 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17482 // Scale the condition by the difference.
17484 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17485 DAG.getConstant(Diff, Cond.getValueType()));
17487 // Add the base if non-zero.
17488 if (FalseC->getAPIntValue() != 0)
17489 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17490 SDValue(FalseC, 0));
17497 // Canonicalize max and min:
17498 // (x > y) ? x : y -> (x >= y) ? x : y
17499 // (x < y) ? x : y -> (x <= y) ? x : y
17500 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17501 // the need for an extra compare
17502 // against zero. e.g.
17503 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17505 // testl %edi, %edi
17507 // cmovgl %edi, %eax
17511 // cmovsl %eax, %edi
17512 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17513 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17514 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17515 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17520 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17521 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17522 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17523 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17528 // Early exit check
17529 if (!TLI.isTypeLegal(VT))
17532 // Match VSELECTs into subs with unsigned saturation.
17533 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17534 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17535 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17536 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17537 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17539 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17540 // left side invert the predicate to simplify logic below.
17542 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17544 CC = ISD::getSetCCInverse(CC, true);
17545 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17549 if (Other.getNode() && Other->getNumOperands() == 2 &&
17550 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17551 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17552 SDValue CondRHS = Cond->getOperand(1);
17554 // Look for a general sub with unsigned saturation first.
17555 // x >= y ? x-y : 0 --> subus x, y
17556 // x > y ? x-y : 0 --> subus x, y
17557 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17558 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17559 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17561 // If the RHS is a constant we have to reverse the const canonicalization.
17562 // x > C-1 ? x+-C : 0 --> subus x, C
17563 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17564 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17565 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17566 if (CondRHS.getConstantOperandVal(0) == -A-1)
17567 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17568 DAG.getConstant(-A, VT));
17571 // Another special case: If C was a sign bit, the sub has been
17572 // canonicalized into a xor.
17573 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17574 // it's safe to decanonicalize the xor?
17575 // x s< 0 ? x^C : 0 --> subus x, C
17576 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17577 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17578 isSplatVector(OpRHS.getNode())) {
17579 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17581 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17586 // Try to match a min/max vector operation.
17587 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17588 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17589 unsigned Opc = ret.first;
17590 bool NeedSplit = ret.second;
17592 if (Opc && NeedSplit) {
17593 unsigned NumElems = VT.getVectorNumElements();
17594 // Extract the LHS vectors
17595 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17596 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17598 // Extract the RHS vectors
17599 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17600 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17602 // Create min/max for each subvector
17603 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17604 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17606 // Merge the result
17607 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17609 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17612 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17613 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17614 // Check if SETCC has already been promoted
17615 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17616 // Check that condition value type matches vselect operand type
17619 assert(Cond.getValueType().isVector() &&
17620 "vector select expects a vector selector!");
17622 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17623 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17625 if (!TValIsAllOnes && !FValIsAllZeros) {
17626 // Try invert the condition if true value is not all 1s and false value
17628 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17629 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17631 if (TValIsAllZeros || FValIsAllOnes) {
17632 SDValue CC = Cond.getOperand(2);
17633 ISD::CondCode NewCC =
17634 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17635 Cond.getOperand(0).getValueType().isInteger());
17636 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17637 std::swap(LHS, RHS);
17638 TValIsAllOnes = FValIsAllOnes;
17639 FValIsAllZeros = TValIsAllZeros;
17643 if (TValIsAllOnes || FValIsAllZeros) {
17646 if (TValIsAllOnes && FValIsAllZeros)
17648 else if (TValIsAllOnes)
17649 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17650 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17651 else if (FValIsAllZeros)
17652 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17653 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17655 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17659 // Try to fold this VSELECT into a MOVSS/MOVSD
17660 if (N->getOpcode() == ISD::VSELECT &&
17661 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17662 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17663 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17664 bool CanFold = false;
17665 unsigned NumElems = Cond.getNumOperands();
17669 if (isZero(Cond.getOperand(0))) {
17672 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17673 // fold (vselect <0,-1> -> (movsd A, B)
17674 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17675 CanFold = isAllOnes(Cond.getOperand(i));
17676 } else if (isAllOnes(Cond.getOperand(0))) {
17680 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17681 // fold (vselect <-1,0> -> (movsd B, A)
17682 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17683 CanFold = isZero(Cond.getOperand(i));
17687 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17688 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17689 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17692 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17693 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17694 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17695 // (v2i64 (bitcast B)))))
17697 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17698 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17699 // (v2f64 (bitcast B)))))
17701 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17702 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17703 // (v2i64 (bitcast A)))))
17705 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17706 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17707 // (v2f64 (bitcast A)))))
17709 CanFold = (isZero(Cond.getOperand(0)) &&
17710 isZero(Cond.getOperand(1)) &&
17711 isAllOnes(Cond.getOperand(2)) &&
17712 isAllOnes(Cond.getOperand(3)));
17714 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17715 isAllOnes(Cond.getOperand(1)) &&
17716 isZero(Cond.getOperand(2)) &&
17717 isZero(Cond.getOperand(3))) {
17719 std::swap(LHS, RHS);
17723 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17724 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17725 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17726 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17728 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17734 // If we know that this node is legal then we know that it is going to be
17735 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17736 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17737 // to simplify previous instructions.
17738 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17739 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17740 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17742 // Don't optimize vector selects that map to mask-registers.
17746 // Check all uses of that condition operand to check whether it will be
17747 // consumed by non-BLEND instructions, which may depend on all bits are set
17749 for (SDNode::use_iterator I = Cond->use_begin(),
17750 E = Cond->use_end(); I != E; ++I)
17751 if (I->getOpcode() != ISD::VSELECT)
17752 // TODO: Add other opcodes eventually lowered into BLEND.
17755 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17756 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17758 APInt KnownZero, KnownOne;
17759 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17760 DCI.isBeforeLegalizeOps());
17761 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17762 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17763 DCI.CommitTargetLoweringOpt(TLO);
17769 // Check whether a boolean test is testing a boolean value generated by
17770 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17773 // Simplify the following patterns:
17774 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17775 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17776 // to (Op EFLAGS Cond)
17778 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17779 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17780 // to (Op EFLAGS !Cond)
17782 // where Op could be BRCOND or CMOV.
17784 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17785 // Quit if not CMP and SUB with its value result used.
17786 if (Cmp.getOpcode() != X86ISD::CMP &&
17787 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17790 // Quit if not used as a boolean value.
17791 if (CC != X86::COND_E && CC != X86::COND_NE)
17794 // Check CMP operands. One of them should be 0 or 1 and the other should be
17795 // an SetCC or extended from it.
17796 SDValue Op1 = Cmp.getOperand(0);
17797 SDValue Op2 = Cmp.getOperand(1);
17800 const ConstantSDNode* C = 0;
17801 bool needOppositeCond = (CC == X86::COND_E);
17802 bool checkAgainstTrue = false; // Is it a comparison against 1?
17804 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17806 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17808 else // Quit if all operands are not constants.
17811 if (C->getZExtValue() == 1) {
17812 needOppositeCond = !needOppositeCond;
17813 checkAgainstTrue = true;
17814 } else if (C->getZExtValue() != 0)
17815 // Quit if the constant is neither 0 or 1.
17818 bool truncatedToBoolWithAnd = false;
17819 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17820 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17821 SetCC.getOpcode() == ISD::TRUNCATE ||
17822 SetCC.getOpcode() == ISD::AND) {
17823 if (SetCC.getOpcode() == ISD::AND) {
17825 ConstantSDNode *CS;
17826 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17827 CS->getZExtValue() == 1)
17829 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17830 CS->getZExtValue() == 1)
17834 SetCC = SetCC.getOperand(OpIdx);
17835 truncatedToBoolWithAnd = true;
17837 SetCC = SetCC.getOperand(0);
17840 switch (SetCC.getOpcode()) {
17841 case X86ISD::SETCC_CARRY:
17842 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17843 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17844 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17845 // truncated to i1 using 'and'.
17846 if (checkAgainstTrue && !truncatedToBoolWithAnd)
17848 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17849 "Invalid use of SETCC_CARRY!");
17851 case X86ISD::SETCC:
17852 // Set the condition code or opposite one if necessary.
17853 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17854 if (needOppositeCond)
17855 CC = X86::GetOppositeBranchCondition(CC);
17856 return SetCC.getOperand(1);
17857 case X86ISD::CMOV: {
17858 // Check whether false/true value has canonical one, i.e. 0 or 1.
17859 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17860 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17861 // Quit if true value is not a constant.
17864 // Quit if false value is not a constant.
17866 SDValue Op = SetCC.getOperand(0);
17867 // Skip 'zext' or 'trunc' node.
17868 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17869 Op.getOpcode() == ISD::TRUNCATE)
17870 Op = Op.getOperand(0);
17871 // A special case for rdrand/rdseed, where 0 is set if false cond is
17873 if ((Op.getOpcode() != X86ISD::RDRAND &&
17874 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17877 // Quit if false value is not the constant 0 or 1.
17878 bool FValIsFalse = true;
17879 if (FVal && FVal->getZExtValue() != 0) {
17880 if (FVal->getZExtValue() != 1)
17882 // If FVal is 1, opposite cond is needed.
17883 needOppositeCond = !needOppositeCond;
17884 FValIsFalse = false;
17886 // Quit if TVal is not the constant opposite of FVal.
17887 if (FValIsFalse && TVal->getZExtValue() != 1)
17889 if (!FValIsFalse && TVal->getZExtValue() != 0)
17891 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17892 if (needOppositeCond)
17893 CC = X86::GetOppositeBranchCondition(CC);
17894 return SetCC.getOperand(3);
17901 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17902 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17903 TargetLowering::DAGCombinerInfo &DCI,
17904 const X86Subtarget *Subtarget) {
17907 // If the flag operand isn't dead, don't touch this CMOV.
17908 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17911 SDValue FalseOp = N->getOperand(0);
17912 SDValue TrueOp = N->getOperand(1);
17913 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17914 SDValue Cond = N->getOperand(3);
17916 if (CC == X86::COND_E || CC == X86::COND_NE) {
17917 switch (Cond.getOpcode()) {
17921 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17922 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17923 return (CC == X86::COND_E) ? FalseOp : TrueOp;
17929 Flags = checkBoolTestSetCCCombine(Cond, CC);
17930 if (Flags.getNode() &&
17931 // Extra check as FCMOV only supports a subset of X86 cond.
17932 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17933 SDValue Ops[] = { FalseOp, TrueOp,
17934 DAG.getConstant(CC, MVT::i8), Flags };
17935 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17936 Ops, array_lengthof(Ops));
17939 // If this is a select between two integer constants, try to do some
17940 // optimizations. Note that the operands are ordered the opposite of SELECT
17942 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17943 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17944 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17945 // larger than FalseC (the false value).
17946 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17947 CC = X86::GetOppositeBranchCondition(CC);
17948 std::swap(TrueC, FalseC);
17949 std::swap(TrueOp, FalseOp);
17952 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
17953 // This is efficient for any integer data type (including i8/i16) and
17955 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17956 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17957 DAG.getConstant(CC, MVT::i8), Cond);
17959 // Zero extend the condition if needed.
17960 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17962 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17963 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17964 DAG.getConstant(ShAmt, MVT::i8));
17965 if (N->getNumValues() == 2) // Dead flag value?
17966 return DCI.CombineTo(N, Cond, SDValue());
17970 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
17971 // for any integer data type, including i8/i16.
17972 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17973 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17974 DAG.getConstant(CC, MVT::i8), Cond);
17976 // Zero extend the condition if needed.
17977 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17978 FalseC->getValueType(0), Cond);
17979 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17980 SDValue(FalseC, 0));
17982 if (N->getNumValues() == 2) // Dead flag value?
17983 return DCI.CombineTo(N, Cond, SDValue());
17987 // Optimize cases that will turn into an LEA instruction. This requires
17988 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17989 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17990 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17991 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17993 bool isFastMultiplier = false;
17995 switch ((unsigned char)Diff) {
17997 case 1: // result = add base, cond
17998 case 2: // result = lea base( , cond*2)
17999 case 3: // result = lea base(cond, cond*2)
18000 case 4: // result = lea base( , cond*4)
18001 case 5: // result = lea base(cond, cond*4)
18002 case 8: // result = lea base( , cond*8)
18003 case 9: // result = lea base(cond, cond*8)
18004 isFastMultiplier = true;
18009 if (isFastMultiplier) {
18010 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18011 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18012 DAG.getConstant(CC, MVT::i8), Cond);
18013 // Zero extend the condition if needed.
18014 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18016 // Scale the condition by the difference.
18018 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18019 DAG.getConstant(Diff, Cond.getValueType()));
18021 // Add the base if non-zero.
18022 if (FalseC->getAPIntValue() != 0)
18023 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18024 SDValue(FalseC, 0));
18025 if (N->getNumValues() == 2) // Dead flag value?
18026 return DCI.CombineTo(N, Cond, SDValue());
18033 // Handle these cases:
18034 // (select (x != c), e, c) -> select (x != c), e, x),
18035 // (select (x == c), c, e) -> select (x == c), x, e)
18036 // where the c is an integer constant, and the "select" is the combination
18037 // of CMOV and CMP.
18039 // The rationale for this change is that the conditional-move from a constant
18040 // needs two instructions, however, conditional-move from a register needs
18041 // only one instruction.
18043 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18044 // some instruction-combining opportunities. This opt needs to be
18045 // postponed as late as possible.
18047 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18048 // the DCI.xxxx conditions are provided to postpone the optimization as
18049 // late as possible.
18051 ConstantSDNode *CmpAgainst = 0;
18052 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18053 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18054 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18056 if (CC == X86::COND_NE &&
18057 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18058 CC = X86::GetOppositeBranchCondition(CC);
18059 std::swap(TrueOp, FalseOp);
18062 if (CC == X86::COND_E &&
18063 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18064 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18065 DAG.getConstant(CC, MVT::i8), Cond };
18066 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
18067 array_lengthof(Ops));
18075 /// PerformMulCombine - Optimize a single multiply with constant into two
18076 /// in order to implement it with two cheaper instructions, e.g.
18077 /// LEA + SHL, LEA + LEA.
18078 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18079 TargetLowering::DAGCombinerInfo &DCI) {
18080 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18083 EVT VT = N->getValueType(0);
18084 if (VT != MVT::i64)
18087 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18090 uint64_t MulAmt = C->getZExtValue();
18091 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18094 uint64_t MulAmt1 = 0;
18095 uint64_t MulAmt2 = 0;
18096 if ((MulAmt % 9) == 0) {
18098 MulAmt2 = MulAmt / 9;
18099 } else if ((MulAmt % 5) == 0) {
18101 MulAmt2 = MulAmt / 5;
18102 } else if ((MulAmt % 3) == 0) {
18104 MulAmt2 = MulAmt / 3;
18107 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18110 if (isPowerOf2_64(MulAmt2) &&
18111 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18112 // If second multiplifer is pow2, issue it first. We want the multiply by
18113 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18115 std::swap(MulAmt1, MulAmt2);
18118 if (isPowerOf2_64(MulAmt1))
18119 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18120 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18122 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18123 DAG.getConstant(MulAmt1, VT));
18125 if (isPowerOf2_64(MulAmt2))
18126 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18127 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18129 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18130 DAG.getConstant(MulAmt2, VT));
18132 // Do not add new nodes to DAG combiner worklist.
18133 DCI.CombineTo(N, NewMul, false);
18138 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18139 SDValue N0 = N->getOperand(0);
18140 SDValue N1 = N->getOperand(1);
18141 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18142 EVT VT = N0.getValueType();
18144 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18145 // since the result of setcc_c is all zero's or all ones.
18146 if (VT.isInteger() && !VT.isVector() &&
18147 N1C && N0.getOpcode() == ISD::AND &&
18148 N0.getOperand(1).getOpcode() == ISD::Constant) {
18149 SDValue N00 = N0.getOperand(0);
18150 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18151 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18152 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18153 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18154 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18155 APInt ShAmt = N1C->getAPIntValue();
18156 Mask = Mask.shl(ShAmt);
18158 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18159 N00, DAG.getConstant(Mask, VT));
18163 // Hardware support for vector shifts is sparse which makes us scalarize the
18164 // vector operations in many cases. Also, on sandybridge ADD is faster than
18166 // (shl V, 1) -> add V,V
18167 if (isSplatVector(N1.getNode())) {
18168 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18170 // We shift all of the values by one. In many cases we do not have
18171 // hardware support for this operation. This is better expressed as an ADD
18173 if (N1C && (1 == N1C->getZExtValue())) {
18174 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18181 /// \brief Returns a vector of 0s if the node in input is a vector logical
18182 /// shift by a constant amount which is known to be bigger than or equal
18183 /// to the vector element size in bits.
18184 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18185 const X86Subtarget *Subtarget) {
18186 EVT VT = N->getValueType(0);
18188 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18189 (!Subtarget->hasInt256() ||
18190 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18193 SDValue Amt = N->getOperand(1);
18195 if (isSplatVector(Amt.getNode())) {
18196 SDValue SclrAmt = Amt->getOperand(0);
18197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18198 APInt ShiftAmt = C->getAPIntValue();
18199 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18201 // SSE2/AVX2 logical shifts always return a vector of 0s
18202 // if the shift amount is bigger than or equal to
18203 // the element size. The constant shift amount will be
18204 // encoded as a 8-bit immediate.
18205 if (ShiftAmt.trunc(8).uge(MaxAmount))
18206 return getZeroVector(VT, Subtarget, DAG, DL);
18213 /// PerformShiftCombine - Combine shifts.
18214 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18215 TargetLowering::DAGCombinerInfo &DCI,
18216 const X86Subtarget *Subtarget) {
18217 if (N->getOpcode() == ISD::SHL) {
18218 SDValue V = PerformSHLCombine(N, DAG);
18219 if (V.getNode()) return V;
18222 if (N->getOpcode() != ISD::SRA) {
18223 // Try to fold this logical shift into a zero vector.
18224 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18225 if (V.getNode()) return V;
18231 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18232 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18233 // and friends. Likewise for OR -> CMPNEQSS.
18234 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18235 TargetLowering::DAGCombinerInfo &DCI,
18236 const X86Subtarget *Subtarget) {
18239 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18240 // we're requiring SSE2 for both.
18241 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18242 SDValue N0 = N->getOperand(0);
18243 SDValue N1 = N->getOperand(1);
18244 SDValue CMP0 = N0->getOperand(1);
18245 SDValue CMP1 = N1->getOperand(1);
18248 // The SETCCs should both refer to the same CMP.
18249 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18252 SDValue CMP00 = CMP0->getOperand(0);
18253 SDValue CMP01 = CMP0->getOperand(1);
18254 EVT VT = CMP00.getValueType();
18256 if (VT == MVT::f32 || VT == MVT::f64) {
18257 bool ExpectingFlags = false;
18258 // Check for any users that want flags:
18259 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18260 !ExpectingFlags && UI != UE; ++UI)
18261 switch (UI->getOpcode()) {
18266 ExpectingFlags = true;
18268 case ISD::CopyToReg:
18269 case ISD::SIGN_EXTEND:
18270 case ISD::ZERO_EXTEND:
18271 case ISD::ANY_EXTEND:
18275 if (!ExpectingFlags) {
18276 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18277 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18279 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18280 X86::CondCode tmp = cc0;
18285 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18286 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18287 // FIXME: need symbolic constants for these magic numbers.
18288 // See X86ATTInstPrinter.cpp:printSSECC().
18289 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18290 if (Subtarget->hasAVX512()) {
18291 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18292 CMP01, DAG.getConstant(x86cc, MVT::i8));
18293 if (N->getValueType(0) != MVT::i1)
18294 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18298 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18299 CMP00.getValueType(), CMP00, CMP01,
18300 DAG.getConstant(x86cc, MVT::i8));
18302 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18303 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18305 if (is64BitFP && !Subtarget->is64Bit()) {
18306 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18307 // 64-bit integer, since that's not a legal type. Since
18308 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18309 // bits, but can do this little dance to extract the lowest 32 bits
18310 // and work with those going forward.
18311 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18313 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18315 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18316 Vector32, DAG.getIntPtrConstant(0));
18320 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18321 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18322 DAG.getConstant(1, IntVT));
18323 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18324 return OneBitOfTruth;
18332 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18333 /// so it can be folded inside ANDNP.
18334 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18335 EVT VT = N->getValueType(0);
18337 // Match direct AllOnes for 128 and 256-bit vectors
18338 if (ISD::isBuildVectorAllOnes(N))
18341 // Look through a bit convert.
18342 if (N->getOpcode() == ISD::BITCAST)
18343 N = N->getOperand(0).getNode();
18345 // Sometimes the operand may come from a insert_subvector building a 256-bit
18347 if (VT.is256BitVector() &&
18348 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18349 SDValue V1 = N->getOperand(0);
18350 SDValue V2 = N->getOperand(1);
18352 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18353 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18354 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18355 ISD::isBuildVectorAllOnes(V2.getNode()))
18362 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18363 // register. In most cases we actually compare or select YMM-sized registers
18364 // and mixing the two types creates horrible code. This method optimizes
18365 // some of the transition sequences.
18366 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18367 TargetLowering::DAGCombinerInfo &DCI,
18368 const X86Subtarget *Subtarget) {
18369 EVT VT = N->getValueType(0);
18370 if (!VT.is256BitVector())
18373 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18374 N->getOpcode() == ISD::ZERO_EXTEND ||
18375 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18377 SDValue Narrow = N->getOperand(0);
18378 EVT NarrowVT = Narrow->getValueType(0);
18379 if (!NarrowVT.is128BitVector())
18382 if (Narrow->getOpcode() != ISD::XOR &&
18383 Narrow->getOpcode() != ISD::AND &&
18384 Narrow->getOpcode() != ISD::OR)
18387 SDValue N0 = Narrow->getOperand(0);
18388 SDValue N1 = Narrow->getOperand(1);
18391 // The Left side has to be a trunc.
18392 if (N0.getOpcode() != ISD::TRUNCATE)
18395 // The type of the truncated inputs.
18396 EVT WideVT = N0->getOperand(0)->getValueType(0);
18400 // The right side has to be a 'trunc' or a constant vector.
18401 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18402 bool RHSConst = (isSplatVector(N1.getNode()) &&
18403 isa<ConstantSDNode>(N1->getOperand(0)));
18404 if (!RHSTrunc && !RHSConst)
18407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18409 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18412 // Set N0 and N1 to hold the inputs to the new wide operation.
18413 N0 = N0->getOperand(0);
18415 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18416 N1->getOperand(0));
18417 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18418 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
18419 } else if (RHSTrunc) {
18420 N1 = N1->getOperand(0);
18423 // Generate the wide operation.
18424 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18425 unsigned Opcode = N->getOpcode();
18427 case ISD::ANY_EXTEND:
18429 case ISD::ZERO_EXTEND: {
18430 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18431 APInt Mask = APInt::getAllOnesValue(InBits);
18432 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18433 return DAG.getNode(ISD::AND, DL, VT,
18434 Op, DAG.getConstant(Mask, VT));
18436 case ISD::SIGN_EXTEND:
18437 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18438 Op, DAG.getValueType(NarrowVT));
18440 llvm_unreachable("Unexpected opcode");
18444 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18445 TargetLowering::DAGCombinerInfo &DCI,
18446 const X86Subtarget *Subtarget) {
18447 EVT VT = N->getValueType(0);
18448 if (DCI.isBeforeLegalizeOps())
18451 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18455 // Create BEXTR instructions
18456 // BEXTR is ((X >> imm) & (2**size-1))
18457 if (VT == MVT::i32 || VT == MVT::i64) {
18458 SDValue N0 = N->getOperand(0);
18459 SDValue N1 = N->getOperand(1);
18462 // Check for BEXTR.
18463 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18464 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18465 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18466 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18467 if (MaskNode && ShiftNode) {
18468 uint64_t Mask = MaskNode->getZExtValue();
18469 uint64_t Shift = ShiftNode->getZExtValue();
18470 if (isMask_64(Mask)) {
18471 uint64_t MaskSize = CountPopulation_64(Mask);
18472 if (Shift + MaskSize <= VT.getSizeInBits())
18473 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18474 DAG.getConstant(Shift | (MaskSize << 8), VT));
18482 // Want to form ANDNP nodes:
18483 // 1) In the hopes of then easily combining them with OR and AND nodes
18484 // to form PBLEND/PSIGN.
18485 // 2) To match ANDN packed intrinsics
18486 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18489 SDValue N0 = N->getOperand(0);
18490 SDValue N1 = N->getOperand(1);
18493 // Check LHS for vnot
18494 if (N0.getOpcode() == ISD::XOR &&
18495 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18496 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18497 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18499 // Check RHS for vnot
18500 if (N1.getOpcode() == ISD::XOR &&
18501 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18502 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18503 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18508 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18509 TargetLowering::DAGCombinerInfo &DCI,
18510 const X86Subtarget *Subtarget) {
18511 if (DCI.isBeforeLegalizeOps())
18514 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18518 SDValue N0 = N->getOperand(0);
18519 SDValue N1 = N->getOperand(1);
18520 EVT VT = N->getValueType(0);
18522 // look for psign/blend
18523 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18524 if (!Subtarget->hasSSSE3() ||
18525 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18528 // Canonicalize pandn to RHS
18529 if (N0.getOpcode() == X86ISD::ANDNP)
18531 // or (and (m, y), (pandn m, x))
18532 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18533 SDValue Mask = N1.getOperand(0);
18534 SDValue X = N1.getOperand(1);
18536 if (N0.getOperand(0) == Mask)
18537 Y = N0.getOperand(1);
18538 if (N0.getOperand(1) == Mask)
18539 Y = N0.getOperand(0);
18541 // Check to see if the mask appeared in both the AND and ANDNP and
18545 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18546 // Look through mask bitcast.
18547 if (Mask.getOpcode() == ISD::BITCAST)
18548 Mask = Mask.getOperand(0);
18549 if (X.getOpcode() == ISD::BITCAST)
18550 X = X.getOperand(0);
18551 if (Y.getOpcode() == ISD::BITCAST)
18552 Y = Y.getOperand(0);
18554 EVT MaskVT = Mask.getValueType();
18556 // Validate that the Mask operand is a vector sra node.
18557 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18558 // there is no psrai.b
18559 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18560 unsigned SraAmt = ~0;
18561 if (Mask.getOpcode() == ISD::SRA) {
18562 SDValue Amt = Mask.getOperand(1);
18563 if (isSplatVector(Amt.getNode())) {
18564 SDValue SclrAmt = Amt->getOperand(0);
18565 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18566 SraAmt = C->getZExtValue();
18568 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18569 SDValue SraC = Mask.getOperand(1);
18570 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18572 if ((SraAmt + 1) != EltBits)
18577 // Now we know we at least have a plendvb with the mask val. See if
18578 // we can form a psignb/w/d.
18579 // psign = x.type == y.type == mask.type && y = sub(0, x);
18580 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18581 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18582 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18583 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18584 "Unsupported VT for PSIGN");
18585 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18586 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18588 // PBLENDVB only available on SSE 4.1
18589 if (!Subtarget->hasSSE41())
18592 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18594 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18595 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18596 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18597 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18598 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18602 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18605 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18606 MachineFunction &MF = DAG.getMachineFunction();
18607 bool OptForSize = MF.getFunction()->getAttributes().
18608 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18610 // SHLD/SHRD instructions have lower register pressure, but on some
18611 // platforms they have higher latency than the equivalent
18612 // series of shifts/or that would otherwise be generated.
18613 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18614 // have higher latencies and we are not optimizing for size.
18615 if (!OptForSize && Subtarget->isSHLDSlow())
18618 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18620 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18622 if (!N0.hasOneUse() || !N1.hasOneUse())
18625 SDValue ShAmt0 = N0.getOperand(1);
18626 if (ShAmt0.getValueType() != MVT::i8)
18628 SDValue ShAmt1 = N1.getOperand(1);
18629 if (ShAmt1.getValueType() != MVT::i8)
18631 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18632 ShAmt0 = ShAmt0.getOperand(0);
18633 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18634 ShAmt1 = ShAmt1.getOperand(0);
18637 unsigned Opc = X86ISD::SHLD;
18638 SDValue Op0 = N0.getOperand(0);
18639 SDValue Op1 = N1.getOperand(0);
18640 if (ShAmt0.getOpcode() == ISD::SUB) {
18641 Opc = X86ISD::SHRD;
18642 std::swap(Op0, Op1);
18643 std::swap(ShAmt0, ShAmt1);
18646 unsigned Bits = VT.getSizeInBits();
18647 if (ShAmt1.getOpcode() == ISD::SUB) {
18648 SDValue Sum = ShAmt1.getOperand(0);
18649 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18650 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18651 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18652 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18653 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18654 return DAG.getNode(Opc, DL, VT,
18656 DAG.getNode(ISD::TRUNCATE, DL,
18659 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18660 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18662 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18663 return DAG.getNode(Opc, DL, VT,
18664 N0.getOperand(0), N1.getOperand(0),
18665 DAG.getNode(ISD::TRUNCATE, DL,
18672 // Generate NEG and CMOV for integer abs.
18673 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18674 EVT VT = N->getValueType(0);
18676 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18677 // 8-bit integer abs to NEG and CMOV.
18678 if (VT.isInteger() && VT.getSizeInBits() == 8)
18681 SDValue N0 = N->getOperand(0);
18682 SDValue N1 = N->getOperand(1);
18685 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18686 // and change it to SUB and CMOV.
18687 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18688 N0.getOpcode() == ISD::ADD &&
18689 N0.getOperand(1) == N1 &&
18690 N1.getOpcode() == ISD::SRA &&
18691 N1.getOperand(0) == N0.getOperand(0))
18692 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18693 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18694 // Generate SUB & CMOV.
18695 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18696 DAG.getConstant(0, VT), N0.getOperand(0));
18698 SDValue Ops[] = { N0.getOperand(0), Neg,
18699 DAG.getConstant(X86::COND_GE, MVT::i8),
18700 SDValue(Neg.getNode(), 1) };
18701 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18702 Ops, array_lengthof(Ops));
18707 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18708 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18709 TargetLowering::DAGCombinerInfo &DCI,
18710 const X86Subtarget *Subtarget) {
18711 if (DCI.isBeforeLegalizeOps())
18714 if (Subtarget->hasCMov()) {
18715 SDValue RV = performIntegerAbsCombine(N, DAG);
18723 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18724 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18725 TargetLowering::DAGCombinerInfo &DCI,
18726 const X86Subtarget *Subtarget) {
18727 LoadSDNode *Ld = cast<LoadSDNode>(N);
18728 EVT RegVT = Ld->getValueType(0);
18729 EVT MemVT = Ld->getMemoryVT();
18731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18732 unsigned RegSz = RegVT.getSizeInBits();
18734 // On Sandybridge unaligned 256bit loads are inefficient.
18735 ISD::LoadExtType Ext = Ld->getExtensionType();
18736 unsigned Alignment = Ld->getAlignment();
18737 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18738 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18739 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18740 unsigned NumElems = RegVT.getVectorNumElements();
18744 SDValue Ptr = Ld->getBasePtr();
18745 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18747 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18749 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18750 Ld->getPointerInfo(), Ld->isVolatile(),
18751 Ld->isNonTemporal(), Ld->isInvariant(),
18753 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18754 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18755 Ld->getPointerInfo(), Ld->isVolatile(),
18756 Ld->isNonTemporal(), Ld->isInvariant(),
18757 std::min(16U, Alignment));
18758 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18760 Load2.getValue(1));
18762 SDValue NewVec = DAG.getUNDEF(RegVT);
18763 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18764 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18765 return DCI.CombineTo(N, NewVec, TF, true);
18768 // If this is a vector EXT Load then attempt to optimize it using a
18769 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18770 // expansion is still better than scalar code.
18771 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18772 // emit a shuffle and a arithmetic shift.
18773 // TODO: It is possible to support ZExt by zeroing the undef values
18774 // during the shuffle phase or after the shuffle.
18775 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18776 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18777 assert(MemVT != RegVT && "Cannot extend to the same type");
18778 assert(MemVT.isVector() && "Must load a vector from memory");
18780 unsigned NumElems = RegVT.getVectorNumElements();
18781 unsigned MemSz = MemVT.getSizeInBits();
18782 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18784 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18787 // All sizes must be a power of two.
18788 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18791 // Attempt to load the original value using scalar loads.
18792 // Find the largest scalar type that divides the total loaded size.
18793 MVT SclrLoadTy = MVT::i8;
18794 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18795 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18796 MVT Tp = (MVT::SimpleValueType)tp;
18797 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18802 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18803 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18805 SclrLoadTy = MVT::f64;
18807 // Calculate the number of scalar loads that we need to perform
18808 // in order to load our vector from memory.
18809 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18810 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18813 unsigned loadRegZize = RegSz;
18814 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18817 // Represent our vector as a sequence of elements which are the
18818 // largest scalar that we can load.
18819 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18820 loadRegZize/SclrLoadTy.getSizeInBits());
18822 // Represent the data using the same element type that is stored in
18823 // memory. In practice, we ''widen'' MemVT.
18825 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18826 loadRegZize/MemVT.getScalarType().getSizeInBits());
18828 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18829 "Invalid vector type");
18831 // We can't shuffle using an illegal type.
18832 if (!TLI.isTypeLegal(WideVecVT))
18835 SmallVector<SDValue, 8> Chains;
18836 SDValue Ptr = Ld->getBasePtr();
18837 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18838 TLI.getPointerTy());
18839 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18841 for (unsigned i = 0; i < NumLoads; ++i) {
18842 // Perform a single load.
18843 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18844 Ptr, Ld->getPointerInfo(),
18845 Ld->isVolatile(), Ld->isNonTemporal(),
18846 Ld->isInvariant(), Ld->getAlignment());
18847 Chains.push_back(ScalarLoad.getValue(1));
18848 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18849 // another round of DAGCombining.
18851 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18853 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18854 ScalarLoad, DAG.getIntPtrConstant(i));
18856 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18859 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18862 // Bitcast the loaded value to a vector of the original element type, in
18863 // the size of the target vector type.
18864 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18865 unsigned SizeRatio = RegSz/MemSz;
18867 if (Ext == ISD::SEXTLOAD) {
18868 // If we have SSE4.1 we can directly emit a VSEXT node.
18869 if (Subtarget->hasSSE41()) {
18870 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18871 return DCI.CombineTo(N, Sext, TF, true);
18874 // Otherwise we'll shuffle the small elements in the high bits of the
18875 // larger type and perform an arithmetic shift. If the shift is not legal
18876 // it's better to scalarize.
18877 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18880 // Redistribute the loaded elements into the different locations.
18881 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18882 for (unsigned i = 0; i != NumElems; ++i)
18883 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18885 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18886 DAG.getUNDEF(WideVecVT),
18889 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18891 // Build the arithmetic shift.
18892 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18893 MemVT.getVectorElementType().getSizeInBits();
18894 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18895 DAG.getConstant(Amt, RegVT));
18897 return DCI.CombineTo(N, Shuff, TF, true);
18900 // Redistribute the loaded elements into the different locations.
18901 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18902 for (unsigned i = 0; i != NumElems; ++i)
18903 ShuffleVec[i*SizeRatio] = i;
18905 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18906 DAG.getUNDEF(WideVecVT),
18909 // Bitcast to the requested type.
18910 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18911 // Replace the original load with the new sequence
18912 // and return the new chain.
18913 return DCI.CombineTo(N, Shuff, TF, true);
18919 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18920 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18921 const X86Subtarget *Subtarget) {
18922 StoreSDNode *St = cast<StoreSDNode>(N);
18923 EVT VT = St->getValue().getValueType();
18924 EVT StVT = St->getMemoryVT();
18926 SDValue StoredVal = St->getOperand(1);
18927 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18929 // If we are saving a concatenation of two XMM registers, perform two stores.
18930 // On Sandy Bridge, 256-bit memory operations are executed by two
18931 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18932 // memory operation.
18933 unsigned Alignment = St->getAlignment();
18934 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18935 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18936 StVT == VT && !IsAligned) {
18937 unsigned NumElems = VT.getVectorNumElements();
18941 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18942 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18944 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18945 SDValue Ptr0 = St->getBasePtr();
18946 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18948 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18949 St->getPointerInfo(), St->isVolatile(),
18950 St->isNonTemporal(), Alignment);
18951 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18952 St->getPointerInfo(), St->isVolatile(),
18953 St->isNonTemporal(),
18954 std::min(16U, Alignment));
18955 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18958 // Optimize trunc store (of multiple scalars) to shuffle and store.
18959 // First, pack all of the elements in one place. Next, store to memory
18960 // in fewer chunks.
18961 if (St->isTruncatingStore() && VT.isVector()) {
18962 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18963 unsigned NumElems = VT.getVectorNumElements();
18964 assert(StVT != VT && "Cannot truncate to the same type");
18965 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18966 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18968 // From, To sizes and ElemCount must be pow of two
18969 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18970 // We are going to use the original vector elt for storing.
18971 // Accumulated smaller vector elements must be a multiple of the store size.
18972 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18974 unsigned SizeRatio = FromSz / ToSz;
18976 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18978 // Create a type on which we perform the shuffle
18979 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18980 StVT.getScalarType(), NumElems*SizeRatio);
18982 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18984 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18985 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18986 for (unsigned i = 0; i != NumElems; ++i)
18987 ShuffleVec[i] = i * SizeRatio;
18989 // Can't shuffle using an illegal type.
18990 if (!TLI.isTypeLegal(WideVecVT))
18993 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18994 DAG.getUNDEF(WideVecVT),
18996 // At this point all of the data is stored at the bottom of the
18997 // register. We now need to save it to mem.
18999 // Find the largest store unit
19000 MVT StoreType = MVT::i8;
19001 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19002 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19003 MVT Tp = (MVT::SimpleValueType)tp;
19004 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19008 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19009 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19010 (64 <= NumElems * ToSz))
19011 StoreType = MVT::f64;
19013 // Bitcast the original vector into a vector of store-size units
19014 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19015 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19016 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19017 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19018 SmallVector<SDValue, 8> Chains;
19019 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19020 TLI.getPointerTy());
19021 SDValue Ptr = St->getBasePtr();
19023 // Perform one or more big stores into memory.
19024 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19025 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19026 StoreType, ShuffWide,
19027 DAG.getIntPtrConstant(i));
19028 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19029 St->getPointerInfo(), St->isVolatile(),
19030 St->isNonTemporal(), St->getAlignment());
19031 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19032 Chains.push_back(Ch);
19035 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
19039 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19040 // the FP state in cases where an emms may be missing.
19041 // A preferable solution to the general problem is to figure out the right
19042 // places to insert EMMS. This qualifies as a quick hack.
19044 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19045 if (VT.getSizeInBits() != 64)
19048 const Function *F = DAG.getMachineFunction().getFunction();
19049 bool NoImplicitFloatOps = F->getAttributes().
19050 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19051 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19052 && Subtarget->hasSSE2();
19053 if ((VT.isVector() ||
19054 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19055 isa<LoadSDNode>(St->getValue()) &&
19056 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19057 St->getChain().hasOneUse() && !St->isVolatile()) {
19058 SDNode* LdVal = St->getValue().getNode();
19059 LoadSDNode *Ld = 0;
19060 int TokenFactorIndex = -1;
19061 SmallVector<SDValue, 8> Ops;
19062 SDNode* ChainVal = St->getChain().getNode();
19063 // Must be a store of a load. We currently handle two cases: the load
19064 // is a direct child, and it's under an intervening TokenFactor. It is
19065 // possible to dig deeper under nested TokenFactors.
19066 if (ChainVal == LdVal)
19067 Ld = cast<LoadSDNode>(St->getChain());
19068 else if (St->getValue().hasOneUse() &&
19069 ChainVal->getOpcode() == ISD::TokenFactor) {
19070 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19071 if (ChainVal->getOperand(i).getNode() == LdVal) {
19072 TokenFactorIndex = i;
19073 Ld = cast<LoadSDNode>(St->getValue());
19075 Ops.push_back(ChainVal->getOperand(i));
19079 if (!Ld || !ISD::isNormalLoad(Ld))
19082 // If this is not the MMX case, i.e. we are just turning i64 load/store
19083 // into f64 load/store, avoid the transformation if there are multiple
19084 // uses of the loaded value.
19085 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19090 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19091 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19093 if (Subtarget->is64Bit() || F64IsLegal) {
19094 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19095 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19096 Ld->getPointerInfo(), Ld->isVolatile(),
19097 Ld->isNonTemporal(), Ld->isInvariant(),
19098 Ld->getAlignment());
19099 SDValue NewChain = NewLd.getValue(1);
19100 if (TokenFactorIndex != -1) {
19101 Ops.push_back(NewChain);
19102 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19105 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19106 St->getPointerInfo(),
19107 St->isVolatile(), St->isNonTemporal(),
19108 St->getAlignment());
19111 // Otherwise, lower to two pairs of 32-bit loads / stores.
19112 SDValue LoAddr = Ld->getBasePtr();
19113 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19114 DAG.getConstant(4, MVT::i32));
19116 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19117 Ld->getPointerInfo(),
19118 Ld->isVolatile(), Ld->isNonTemporal(),
19119 Ld->isInvariant(), Ld->getAlignment());
19120 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19121 Ld->getPointerInfo().getWithOffset(4),
19122 Ld->isVolatile(), Ld->isNonTemporal(),
19124 MinAlign(Ld->getAlignment(), 4));
19126 SDValue NewChain = LoLd.getValue(1);
19127 if (TokenFactorIndex != -1) {
19128 Ops.push_back(LoLd);
19129 Ops.push_back(HiLd);
19130 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
19134 LoAddr = St->getBasePtr();
19135 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19136 DAG.getConstant(4, MVT::i32));
19138 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19139 St->getPointerInfo(),
19140 St->isVolatile(), St->isNonTemporal(),
19141 St->getAlignment());
19142 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19143 St->getPointerInfo().getWithOffset(4),
19145 St->isNonTemporal(),
19146 MinAlign(St->getAlignment(), 4));
19147 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19152 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19153 /// and return the operands for the horizontal operation in LHS and RHS. A
19154 /// horizontal operation performs the binary operation on successive elements
19155 /// of its first operand, then on successive elements of its second operand,
19156 /// returning the resulting values in a vector. For example, if
19157 /// A = < float a0, float a1, float a2, float a3 >
19159 /// B = < float b0, float b1, float b2, float b3 >
19160 /// then the result of doing a horizontal operation on A and B is
19161 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19162 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19163 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19164 /// set to A, RHS to B, and the routine returns 'true'.
19165 /// Note that the binary operation should have the property that if one of the
19166 /// operands is UNDEF then the result is UNDEF.
19167 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19168 // Look for the following pattern: if
19169 // A = < float a0, float a1, float a2, float a3 >
19170 // B = < float b0, float b1, float b2, float b3 >
19172 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19173 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19174 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19175 // which is A horizontal-op B.
19177 // At least one of the operands should be a vector shuffle.
19178 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19179 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19182 MVT VT = LHS.getSimpleValueType();
19184 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19185 "Unsupported vector type for horizontal add/sub");
19187 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19188 // operate independently on 128-bit lanes.
19189 unsigned NumElts = VT.getVectorNumElements();
19190 unsigned NumLanes = VT.getSizeInBits()/128;
19191 unsigned NumLaneElts = NumElts / NumLanes;
19192 assert((NumLaneElts % 2 == 0) &&
19193 "Vector type should have an even number of elements in each lane");
19194 unsigned HalfLaneElts = NumLaneElts/2;
19196 // View LHS in the form
19197 // LHS = VECTOR_SHUFFLE A, B, LMask
19198 // If LHS is not a shuffle then pretend it is the shuffle
19199 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19200 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19203 SmallVector<int, 16> LMask(NumElts);
19204 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19205 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19206 A = LHS.getOperand(0);
19207 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19208 B = LHS.getOperand(1);
19209 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19210 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19212 if (LHS.getOpcode() != ISD::UNDEF)
19214 for (unsigned i = 0; i != NumElts; ++i)
19218 // Likewise, view RHS in the form
19219 // RHS = VECTOR_SHUFFLE C, D, RMask
19221 SmallVector<int, 16> RMask(NumElts);
19222 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19223 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19224 C = RHS.getOperand(0);
19225 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19226 D = RHS.getOperand(1);
19227 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19228 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19230 if (RHS.getOpcode() != ISD::UNDEF)
19232 for (unsigned i = 0; i != NumElts; ++i)
19236 // Check that the shuffles are both shuffling the same vectors.
19237 if (!(A == C && B == D) && !(A == D && B == C))
19240 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19241 if (!A.getNode() && !B.getNode())
19244 // If A and B occur in reverse order in RHS, then "swap" them (which means
19245 // rewriting the mask).
19247 CommuteVectorShuffleMask(RMask, NumElts);
19249 // At this point LHS and RHS are equivalent to
19250 // LHS = VECTOR_SHUFFLE A, B, LMask
19251 // RHS = VECTOR_SHUFFLE A, B, RMask
19252 // Check that the masks correspond to performing a horizontal operation.
19253 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19254 for (unsigned i = 0; i != NumLaneElts; ++i) {
19255 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19257 // Ignore any UNDEF components.
19258 if (LIdx < 0 || RIdx < 0 ||
19259 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19260 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19263 // Check that successive elements are being operated on. If not, this is
19264 // not a horizontal operation.
19265 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19266 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19267 if (!(LIdx == Index && RIdx == Index + 1) &&
19268 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19273 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19274 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19278 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19279 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19280 const X86Subtarget *Subtarget) {
19281 EVT VT = N->getValueType(0);
19282 SDValue LHS = N->getOperand(0);
19283 SDValue RHS = N->getOperand(1);
19285 // Try to synthesize horizontal adds from adds of shuffles.
19286 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19287 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19288 isHorizontalBinOp(LHS, RHS, true))
19289 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19293 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19294 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19295 const X86Subtarget *Subtarget) {
19296 EVT VT = N->getValueType(0);
19297 SDValue LHS = N->getOperand(0);
19298 SDValue RHS = N->getOperand(1);
19300 // Try to synthesize horizontal subs from subs of shuffles.
19301 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19302 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19303 isHorizontalBinOp(LHS, RHS, false))
19304 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19308 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19309 /// X86ISD::FXOR nodes.
19310 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19311 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19312 // F[X]OR(0.0, x) -> x
19313 // F[X]OR(x, 0.0) -> x
19314 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19315 if (C->getValueAPF().isPosZero())
19316 return N->getOperand(1);
19317 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19318 if (C->getValueAPF().isPosZero())
19319 return N->getOperand(0);
19323 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19324 /// X86ISD::FMAX nodes.
19325 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19326 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19328 // Only perform optimizations if UnsafeMath is used.
19329 if (!DAG.getTarget().Options.UnsafeFPMath)
19332 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19333 // into FMINC and FMAXC, which are Commutative operations.
19334 unsigned NewOp = 0;
19335 switch (N->getOpcode()) {
19336 default: llvm_unreachable("unknown opcode");
19337 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19338 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19341 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19342 N->getOperand(0), N->getOperand(1));
19345 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19346 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19347 // FAND(0.0, x) -> 0.0
19348 // FAND(x, 0.0) -> 0.0
19349 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19350 if (C->getValueAPF().isPosZero())
19351 return N->getOperand(0);
19352 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19353 if (C->getValueAPF().isPosZero())
19354 return N->getOperand(1);
19358 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19359 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19360 // FANDN(x, 0.0) -> 0.0
19361 // FANDN(0.0, x) -> x
19362 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19363 if (C->getValueAPF().isPosZero())
19364 return N->getOperand(1);
19365 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19366 if (C->getValueAPF().isPosZero())
19367 return N->getOperand(1);
19371 static SDValue PerformBTCombine(SDNode *N,
19373 TargetLowering::DAGCombinerInfo &DCI) {
19374 // BT ignores high bits in the bit index operand.
19375 SDValue Op1 = N->getOperand(1);
19376 if (Op1.hasOneUse()) {
19377 unsigned BitWidth = Op1.getValueSizeInBits();
19378 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19379 APInt KnownZero, KnownOne;
19380 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19381 !DCI.isBeforeLegalizeOps());
19382 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19383 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19384 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19385 DCI.CommitTargetLoweringOpt(TLO);
19390 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19391 SDValue Op = N->getOperand(0);
19392 if (Op.getOpcode() == ISD::BITCAST)
19393 Op = Op.getOperand(0);
19394 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19395 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19396 VT.getVectorElementType().getSizeInBits() ==
19397 OpVT.getVectorElementType().getSizeInBits()) {
19398 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19403 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19404 const X86Subtarget *Subtarget) {
19405 EVT VT = N->getValueType(0);
19406 if (!VT.isVector())
19409 SDValue N0 = N->getOperand(0);
19410 SDValue N1 = N->getOperand(1);
19411 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19414 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19415 // both SSE and AVX2 since there is no sign-extended shift right
19416 // operation on a vector with 64-bit elements.
19417 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19418 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19419 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19420 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19421 SDValue N00 = N0.getOperand(0);
19423 // EXTLOAD has a better solution on AVX2,
19424 // it may be replaced with X86ISD::VSEXT node.
19425 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19426 if (!ISD::isNormalLoad(N00.getNode()))
19429 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19430 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19432 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19438 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19439 TargetLowering::DAGCombinerInfo &DCI,
19440 const X86Subtarget *Subtarget) {
19441 if (!DCI.isBeforeLegalizeOps())
19444 if (!Subtarget->hasFp256())
19447 EVT VT = N->getValueType(0);
19448 if (VT.isVector() && VT.getSizeInBits() == 256) {
19449 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19457 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19458 const X86Subtarget* Subtarget) {
19460 EVT VT = N->getValueType(0);
19462 // Let legalize expand this if it isn't a legal type yet.
19463 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19466 EVT ScalarVT = VT.getScalarType();
19467 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19468 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19471 SDValue A = N->getOperand(0);
19472 SDValue B = N->getOperand(1);
19473 SDValue C = N->getOperand(2);
19475 bool NegA = (A.getOpcode() == ISD::FNEG);
19476 bool NegB = (B.getOpcode() == ISD::FNEG);
19477 bool NegC = (C.getOpcode() == ISD::FNEG);
19479 // Negative multiplication when NegA xor NegB
19480 bool NegMul = (NegA != NegB);
19482 A = A.getOperand(0);
19484 B = B.getOperand(0);
19486 C = C.getOperand(0);
19490 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19492 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19494 return DAG.getNode(Opcode, dl, VT, A, B, C);
19497 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19498 TargetLowering::DAGCombinerInfo &DCI,
19499 const X86Subtarget *Subtarget) {
19500 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19501 // (and (i32 x86isd::setcc_carry), 1)
19502 // This eliminates the zext. This transformation is necessary because
19503 // ISD::SETCC is always legalized to i8.
19505 SDValue N0 = N->getOperand(0);
19506 EVT VT = N->getValueType(0);
19508 if (N0.getOpcode() == ISD::AND &&
19510 N0.getOperand(0).hasOneUse()) {
19511 SDValue N00 = N0.getOperand(0);
19512 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19513 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19514 if (!C || C->getZExtValue() != 1)
19516 return DAG.getNode(ISD::AND, dl, VT,
19517 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19518 N00.getOperand(0), N00.getOperand(1)),
19519 DAG.getConstant(1, VT));
19523 if (N0.getOpcode() == ISD::TRUNCATE &&
19525 N0.getOperand(0).hasOneUse()) {
19526 SDValue N00 = N0.getOperand(0);
19527 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19528 return DAG.getNode(ISD::AND, dl, VT,
19529 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19530 N00.getOperand(0), N00.getOperand(1)),
19531 DAG.getConstant(1, VT));
19534 if (VT.is256BitVector()) {
19535 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19543 // Optimize x == -y --> x+y == 0
19544 // x != -y --> x+y != 0
19545 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19546 const X86Subtarget* Subtarget) {
19547 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19548 SDValue LHS = N->getOperand(0);
19549 SDValue RHS = N->getOperand(1);
19550 EVT VT = N->getValueType(0);
19553 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19554 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19555 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19556 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19557 LHS.getValueType(), RHS, LHS.getOperand(1));
19558 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19559 addV, DAG.getConstant(0, addV.getValueType()), CC);
19561 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19562 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19563 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19564 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19565 RHS.getValueType(), LHS, RHS.getOperand(1));
19566 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19567 addV, DAG.getConstant(0, addV.getValueType()), CC);
19570 if (VT.getScalarType() == MVT::i1) {
19571 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19572 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19573 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19574 if (!IsSEXT0 && !IsVZero0)
19576 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19577 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19578 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19580 if (!IsSEXT1 && !IsVZero1)
19583 if (IsSEXT0 && IsVZero1) {
19584 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19585 if (CC == ISD::SETEQ)
19586 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19587 return LHS.getOperand(0);
19589 if (IsSEXT1 && IsVZero0) {
19590 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19591 if (CC == ISD::SETEQ)
19592 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19593 return RHS.getOperand(0);
19600 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19601 // as "sbb reg,reg", since it can be extended without zext and produces
19602 // an all-ones bit which is more useful than 0/1 in some cases.
19603 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19606 return DAG.getNode(ISD::AND, DL, VT,
19607 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19608 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19609 DAG.getConstant(1, VT));
19610 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19611 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19612 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19613 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19616 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19617 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19618 TargetLowering::DAGCombinerInfo &DCI,
19619 const X86Subtarget *Subtarget) {
19621 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19622 SDValue EFLAGS = N->getOperand(1);
19624 if (CC == X86::COND_A) {
19625 // Try to convert COND_A into COND_B in an attempt to facilitate
19626 // materializing "setb reg".
19628 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19629 // cannot take an immediate as its first operand.
19631 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19632 EFLAGS.getValueType().isInteger() &&
19633 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19634 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19635 EFLAGS.getNode()->getVTList(),
19636 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19637 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19638 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19642 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19643 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19645 if (CC == X86::COND_B)
19646 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19650 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19651 if (Flags.getNode()) {
19652 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19653 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19659 // Optimize branch condition evaluation.
19661 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19662 TargetLowering::DAGCombinerInfo &DCI,
19663 const X86Subtarget *Subtarget) {
19665 SDValue Chain = N->getOperand(0);
19666 SDValue Dest = N->getOperand(1);
19667 SDValue EFLAGS = N->getOperand(3);
19668 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19672 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19673 if (Flags.getNode()) {
19674 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19675 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19682 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19683 const X86TargetLowering *XTLI) {
19684 SDValue Op0 = N->getOperand(0);
19685 EVT InVT = Op0->getValueType(0);
19687 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19688 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19690 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19691 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19692 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19695 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19696 // a 32-bit target where SSE doesn't support i64->FP operations.
19697 if (Op0.getOpcode() == ISD::LOAD) {
19698 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19699 EVT VT = Ld->getValueType(0);
19700 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19701 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19702 !XTLI->getSubtarget()->is64Bit() &&
19704 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19705 Ld->getChain(), Op0, DAG);
19706 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19713 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19714 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19715 X86TargetLowering::DAGCombinerInfo &DCI) {
19716 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19717 // the result is either zero or one (depending on the input carry bit).
19718 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19719 if (X86::isZeroNode(N->getOperand(0)) &&
19720 X86::isZeroNode(N->getOperand(1)) &&
19721 // We don't have a good way to replace an EFLAGS use, so only do this when
19723 SDValue(N, 1).use_empty()) {
19725 EVT VT = N->getValueType(0);
19726 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19727 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19728 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19729 DAG.getConstant(X86::COND_B,MVT::i8),
19731 DAG.getConstant(1, VT));
19732 return DCI.CombineTo(N, Res1, CarryOut);
19738 // fold (add Y, (sete X, 0)) -> adc 0, Y
19739 // (add Y, (setne X, 0)) -> sbb -1, Y
19740 // (sub (sete X, 0), Y) -> sbb 0, Y
19741 // (sub (setne X, 0), Y) -> adc -1, Y
19742 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19745 // Look through ZExts.
19746 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19747 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19750 SDValue SetCC = Ext.getOperand(0);
19751 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19754 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19755 if (CC != X86::COND_E && CC != X86::COND_NE)
19758 SDValue Cmp = SetCC.getOperand(1);
19759 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19760 !X86::isZeroNode(Cmp.getOperand(1)) ||
19761 !Cmp.getOperand(0).getValueType().isInteger())
19764 SDValue CmpOp0 = Cmp.getOperand(0);
19765 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19766 DAG.getConstant(1, CmpOp0.getValueType()));
19768 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19769 if (CC == X86::COND_NE)
19770 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19771 DL, OtherVal.getValueType(), OtherVal,
19772 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19773 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19774 DL, OtherVal.getValueType(), OtherVal,
19775 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19778 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19779 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19780 const X86Subtarget *Subtarget) {
19781 EVT VT = N->getValueType(0);
19782 SDValue Op0 = N->getOperand(0);
19783 SDValue Op1 = N->getOperand(1);
19785 // Try to synthesize horizontal adds from adds of shuffles.
19786 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19787 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19788 isHorizontalBinOp(Op0, Op1, true))
19789 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19791 return OptimizeConditionalInDecrement(N, DAG);
19794 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19795 const X86Subtarget *Subtarget) {
19796 SDValue Op0 = N->getOperand(0);
19797 SDValue Op1 = N->getOperand(1);
19799 // X86 can't encode an immediate LHS of a sub. See if we can push the
19800 // negation into a preceding instruction.
19801 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19802 // If the RHS of the sub is a XOR with one use and a constant, invert the
19803 // immediate. Then add one to the LHS of the sub so we can turn
19804 // X-Y -> X+~Y+1, saving one register.
19805 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19806 isa<ConstantSDNode>(Op1.getOperand(1))) {
19807 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19808 EVT VT = Op0.getValueType();
19809 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19811 DAG.getConstant(~XorC, VT));
19812 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19813 DAG.getConstant(C->getAPIntValue()+1, VT));
19817 // Try to synthesize horizontal adds from adds of shuffles.
19818 EVT VT = N->getValueType(0);
19819 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19820 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19821 isHorizontalBinOp(Op0, Op1, true))
19822 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19824 return OptimizeConditionalInDecrement(N, DAG);
19827 /// performVZEXTCombine - Performs build vector combines
19828 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19829 TargetLowering::DAGCombinerInfo &DCI,
19830 const X86Subtarget *Subtarget) {
19831 // (vzext (bitcast (vzext (x)) -> (vzext x)
19832 SDValue In = N->getOperand(0);
19833 while (In.getOpcode() == ISD::BITCAST)
19834 In = In.getOperand(0);
19836 if (In.getOpcode() != X86ISD::VZEXT)
19839 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19843 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19844 DAGCombinerInfo &DCI) const {
19845 SelectionDAG &DAG = DCI.DAG;
19846 switch (N->getOpcode()) {
19848 case ISD::EXTRACT_VECTOR_ELT:
19849 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19851 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19852 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19853 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
19854 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
19855 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
19856 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
19859 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
19860 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
19861 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
19862 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
19863 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
19864 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
19865 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
19866 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
19867 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
19869 case X86ISD::FOR: return PerformFORCombine(N, DAG);
19871 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
19872 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
19873 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
19874 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
19875 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
19876 case ISD::ANY_EXTEND:
19877 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
19878 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
19879 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19880 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19881 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
19882 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19883 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19884 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
19885 case X86ISD::SHUFP: // Handle all target specific shuffles
19886 case X86ISD::PALIGNR:
19887 case X86ISD::UNPCKH:
19888 case X86ISD::UNPCKL:
19889 case X86ISD::MOVHLPS:
19890 case X86ISD::MOVLHPS:
19891 case X86ISD::PSHUFD:
19892 case X86ISD::PSHUFHW:
19893 case X86ISD::PSHUFLW:
19894 case X86ISD::MOVSS:
19895 case X86ISD::MOVSD:
19896 case X86ISD::VPERMILP:
19897 case X86ISD::VPERM2X128:
19898 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19899 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
19905 /// isTypeDesirableForOp - Return true if the target has native support for
19906 /// the specified value type and it is 'desirable' to use the type for the
19907 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19908 /// instruction encodings are longer and some i16 instructions are slow.
19909 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19910 if (!isTypeLegal(VT))
19912 if (VT != MVT::i16)
19919 case ISD::SIGN_EXTEND:
19920 case ISD::ZERO_EXTEND:
19921 case ISD::ANY_EXTEND:
19934 /// IsDesirableToPromoteOp - This method query the target whether it is
19935 /// beneficial for dag combiner to promote the specified node. If true, it
19936 /// should return the desired promotion type by reference.
19937 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19938 EVT VT = Op.getValueType();
19939 if (VT != MVT::i16)
19942 bool Promote = false;
19943 bool Commute = false;
19944 switch (Op.getOpcode()) {
19947 LoadSDNode *LD = cast<LoadSDNode>(Op);
19948 // If the non-extending load has a single use and it's not live out, then it
19949 // might be folded.
19950 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19951 Op.hasOneUse()*/) {
19952 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19953 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19954 // The only case where we'd want to promote LOAD (rather then it being
19955 // promoted as an operand is when it's only use is liveout.
19956 if (UI->getOpcode() != ISD::CopyToReg)
19963 case ISD::SIGN_EXTEND:
19964 case ISD::ZERO_EXTEND:
19965 case ISD::ANY_EXTEND:
19970 SDValue N0 = Op.getOperand(0);
19971 // Look out for (store (shl (load), x)).
19972 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19985 SDValue N0 = Op.getOperand(0);
19986 SDValue N1 = Op.getOperand(1);
19987 if (!Commute && MayFoldLoad(N1))
19989 // Avoid disabling potential load folding opportunities.
19990 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19992 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20002 //===----------------------------------------------------------------------===//
20003 // X86 Inline Assembly Support
20004 //===----------------------------------------------------------------------===//
20007 // Helper to match a string separated by whitespace.
20008 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20009 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20011 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20012 StringRef piece(*args[i]);
20013 if (!s.startswith(piece)) // Check if the piece matches.
20016 s = s.substr(piece.size());
20017 StringRef::size_type pos = s.find_first_not_of(" \t");
20018 if (pos == 0) // We matched a prefix.
20026 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20029 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20031 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20032 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20033 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20034 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20036 if (AsmPieces.size() == 3)
20038 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20045 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20046 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20048 std::string AsmStr = IA->getAsmString();
20050 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20051 if (!Ty || Ty->getBitWidth() % 16 != 0)
20054 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20055 SmallVector<StringRef, 4> AsmPieces;
20056 SplitString(AsmStr, AsmPieces, ";\n");
20058 switch (AsmPieces.size()) {
20059 default: return false;
20061 // FIXME: this should verify that we are targeting a 486 or better. If not,
20062 // we will turn this bswap into something that will be lowered to logical
20063 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20064 // lower so don't worry about this.
20066 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20067 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20068 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20069 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20070 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20071 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20072 // No need to check constraints, nothing other than the equivalent of
20073 // "=r,0" would be valid here.
20074 return IntrinsicLowering::LowerToByteSwap(CI);
20077 // rorw $$8, ${0:w} --> llvm.bswap.i16
20078 if (CI->getType()->isIntegerTy(16) &&
20079 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20080 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20081 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20083 const std::string &ConstraintsStr = IA->getConstraintString();
20084 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20085 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20086 if (clobbersFlagRegisters(AsmPieces))
20087 return IntrinsicLowering::LowerToByteSwap(CI);
20091 if (CI->getType()->isIntegerTy(32) &&
20092 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20093 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20094 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20095 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20097 const std::string &ConstraintsStr = IA->getConstraintString();
20098 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20099 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20100 if (clobbersFlagRegisters(AsmPieces))
20101 return IntrinsicLowering::LowerToByteSwap(CI);
20104 if (CI->getType()->isIntegerTy(64)) {
20105 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20106 if (Constraints.size() >= 2 &&
20107 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20108 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20109 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20110 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20111 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20112 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20113 return IntrinsicLowering::LowerToByteSwap(CI);
20121 /// getConstraintType - Given a constraint letter, return the type of
20122 /// constraint it is for this target.
20123 X86TargetLowering::ConstraintType
20124 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20125 if (Constraint.size() == 1) {
20126 switch (Constraint[0]) {
20137 return C_RegisterClass;
20161 return TargetLowering::getConstraintType(Constraint);
20164 /// Examine constraint type and operand type and determine a weight value.
20165 /// This object must already have been set up with the operand type
20166 /// and the current alternative constraint selected.
20167 TargetLowering::ConstraintWeight
20168 X86TargetLowering::getSingleConstraintMatchWeight(
20169 AsmOperandInfo &info, const char *constraint) const {
20170 ConstraintWeight weight = CW_Invalid;
20171 Value *CallOperandVal = info.CallOperandVal;
20172 // If we don't have a value, we can't do a match,
20173 // but allow it at the lowest weight.
20174 if (CallOperandVal == NULL)
20176 Type *type = CallOperandVal->getType();
20177 // Look at the constraint type.
20178 switch (*constraint) {
20180 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20191 if (CallOperandVal->getType()->isIntegerTy())
20192 weight = CW_SpecificReg;
20197 if (type->isFloatingPointTy())
20198 weight = CW_SpecificReg;
20201 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20202 weight = CW_SpecificReg;
20206 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20207 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20208 weight = CW_Register;
20211 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20212 if (C->getZExtValue() <= 31)
20213 weight = CW_Constant;
20217 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20218 if (C->getZExtValue() <= 63)
20219 weight = CW_Constant;
20223 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20224 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20225 weight = CW_Constant;
20229 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20230 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20231 weight = CW_Constant;
20235 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20236 if (C->getZExtValue() <= 3)
20237 weight = CW_Constant;
20241 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20242 if (C->getZExtValue() <= 0xff)
20243 weight = CW_Constant;
20248 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20249 weight = CW_Constant;
20253 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20254 if ((C->getSExtValue() >= -0x80000000LL) &&
20255 (C->getSExtValue() <= 0x7fffffffLL))
20256 weight = CW_Constant;
20260 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20261 if (C->getZExtValue() <= 0xffffffff)
20262 weight = CW_Constant;
20269 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20270 /// with another that has more specific requirements based on the type of the
20271 /// corresponding operand.
20272 const char *X86TargetLowering::
20273 LowerXConstraint(EVT ConstraintVT) const {
20274 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20275 // 'f' like normal targets.
20276 if (ConstraintVT.isFloatingPoint()) {
20277 if (Subtarget->hasSSE2())
20279 if (Subtarget->hasSSE1())
20283 return TargetLowering::LowerXConstraint(ConstraintVT);
20286 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20287 /// vector. If it is invalid, don't add anything to Ops.
20288 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20289 std::string &Constraint,
20290 std::vector<SDValue>&Ops,
20291 SelectionDAG &DAG) const {
20292 SDValue Result(0, 0);
20294 // Only support length 1 constraints for now.
20295 if (Constraint.length() > 1) return;
20297 char ConstraintLetter = Constraint[0];
20298 switch (ConstraintLetter) {
20301 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20302 if (C->getZExtValue() <= 31) {
20303 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20310 if (C->getZExtValue() <= 63) {
20311 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20317 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20318 if (isInt<8>(C->getSExtValue())) {
20319 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20325 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20326 if (C->getZExtValue() <= 255) {
20327 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20333 // 32-bit signed value
20334 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20335 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20336 C->getSExtValue())) {
20337 // Widen to 64 bits here to get it sign extended.
20338 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20341 // FIXME gcc accepts some relocatable values here too, but only in certain
20342 // memory models; it's complicated.
20347 // 32-bit unsigned value
20348 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20349 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20350 C->getZExtValue())) {
20351 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20355 // FIXME gcc accepts some relocatable values here too, but only in certain
20356 // memory models; it's complicated.
20360 // Literal immediates are always ok.
20361 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20362 // Widen to 64 bits here to get it sign extended.
20363 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20367 // In any sort of PIC mode addresses need to be computed at runtime by
20368 // adding in a register or some sort of table lookup. These can't
20369 // be used as immediates.
20370 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20373 // If we are in non-pic codegen mode, we allow the address of a global (with
20374 // an optional displacement) to be used with 'i'.
20375 GlobalAddressSDNode *GA = 0;
20376 int64_t Offset = 0;
20378 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20380 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20381 Offset += GA->getOffset();
20383 } else if (Op.getOpcode() == ISD::ADD) {
20384 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20385 Offset += C->getZExtValue();
20386 Op = Op.getOperand(0);
20389 } else if (Op.getOpcode() == ISD::SUB) {
20390 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20391 Offset += -C->getZExtValue();
20392 Op = Op.getOperand(0);
20397 // Otherwise, this isn't something we can handle, reject it.
20401 const GlobalValue *GV = GA->getGlobal();
20402 // If we require an extra load to get this address, as in PIC mode, we
20403 // can't accept it.
20404 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20405 getTargetMachine())))
20408 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20409 GA->getValueType(0), Offset);
20414 if (Result.getNode()) {
20415 Ops.push_back(Result);
20418 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20421 std::pair<unsigned, const TargetRegisterClass*>
20422 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20424 // First, see if this is a constraint that directly corresponds to an LLVM
20426 if (Constraint.size() == 1) {
20427 // GCC Constraint Letters
20428 switch (Constraint[0]) {
20430 // TODO: Slight differences here in allocation order and leaving
20431 // RIP in the class. Do they matter any more here than they do
20432 // in the normal allocation?
20433 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20434 if (Subtarget->is64Bit()) {
20435 if (VT == MVT::i32 || VT == MVT::f32)
20436 return std::make_pair(0U, &X86::GR32RegClass);
20437 if (VT == MVT::i16)
20438 return std::make_pair(0U, &X86::GR16RegClass);
20439 if (VT == MVT::i8 || VT == MVT::i1)
20440 return std::make_pair(0U, &X86::GR8RegClass);
20441 if (VT == MVT::i64 || VT == MVT::f64)
20442 return std::make_pair(0U, &X86::GR64RegClass);
20445 // 32-bit fallthrough
20446 case 'Q': // Q_REGS
20447 if (VT == MVT::i32 || VT == MVT::f32)
20448 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20449 if (VT == MVT::i16)
20450 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20451 if (VT == MVT::i8 || VT == MVT::i1)
20452 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20453 if (VT == MVT::i64)
20454 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20456 case 'r': // GENERAL_REGS
20457 case 'l': // INDEX_REGS
20458 if (VT == MVT::i8 || VT == MVT::i1)
20459 return std::make_pair(0U, &X86::GR8RegClass);
20460 if (VT == MVT::i16)
20461 return std::make_pair(0U, &X86::GR16RegClass);
20462 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20463 return std::make_pair(0U, &X86::GR32RegClass);
20464 return std::make_pair(0U, &X86::GR64RegClass);
20465 case 'R': // LEGACY_REGS
20466 if (VT == MVT::i8 || VT == MVT::i1)
20467 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20468 if (VT == MVT::i16)
20469 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20470 if (VT == MVT::i32 || !Subtarget->is64Bit())
20471 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20472 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20473 case 'f': // FP Stack registers.
20474 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20475 // value to the correct fpstack register class.
20476 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20477 return std::make_pair(0U, &X86::RFP32RegClass);
20478 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20479 return std::make_pair(0U, &X86::RFP64RegClass);
20480 return std::make_pair(0U, &X86::RFP80RegClass);
20481 case 'y': // MMX_REGS if MMX allowed.
20482 if (!Subtarget->hasMMX()) break;
20483 return std::make_pair(0U, &X86::VR64RegClass);
20484 case 'Y': // SSE_REGS if SSE2 allowed
20485 if (!Subtarget->hasSSE2()) break;
20487 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20488 if (!Subtarget->hasSSE1()) break;
20490 switch (VT.SimpleTy) {
20492 // Scalar SSE types.
20495 return std::make_pair(0U, &X86::FR32RegClass);
20498 return std::make_pair(0U, &X86::FR64RegClass);
20506 return std::make_pair(0U, &X86::VR128RegClass);
20514 return std::make_pair(0U, &X86::VR256RegClass);
20519 return std::make_pair(0U, &X86::VR512RegClass);
20525 // Use the default implementation in TargetLowering to convert the register
20526 // constraint into a member of a register class.
20527 std::pair<unsigned, const TargetRegisterClass*> Res;
20528 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20530 // Not found as a standard register?
20531 if (Res.second == 0) {
20532 // Map st(0) -> st(7) -> ST0
20533 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20534 tolower(Constraint[1]) == 's' &&
20535 tolower(Constraint[2]) == 't' &&
20536 Constraint[3] == '(' &&
20537 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20538 Constraint[5] == ')' &&
20539 Constraint[6] == '}') {
20541 Res.first = X86::ST0+Constraint[4]-'0';
20542 Res.second = &X86::RFP80RegClass;
20546 // GCC allows "st(0)" to be called just plain "st".
20547 if (StringRef("{st}").equals_lower(Constraint)) {
20548 Res.first = X86::ST0;
20549 Res.second = &X86::RFP80RegClass;
20554 if (StringRef("{flags}").equals_lower(Constraint)) {
20555 Res.first = X86::EFLAGS;
20556 Res.second = &X86::CCRRegClass;
20560 // 'A' means EAX + EDX.
20561 if (Constraint == "A") {
20562 Res.first = X86::EAX;
20563 Res.second = &X86::GR32_ADRegClass;
20569 // Otherwise, check to see if this is a register class of the wrong value
20570 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20571 // turn into {ax},{dx}.
20572 if (Res.second->hasType(VT))
20573 return Res; // Correct type already, nothing to do.
20575 // All of the single-register GCC register classes map their values onto
20576 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20577 // really want an 8-bit or 32-bit register, map to the appropriate register
20578 // class and return the appropriate register.
20579 if (Res.second == &X86::GR16RegClass) {
20580 if (VT == MVT::i8 || VT == MVT::i1) {
20581 unsigned DestReg = 0;
20582 switch (Res.first) {
20584 case X86::AX: DestReg = X86::AL; break;
20585 case X86::DX: DestReg = X86::DL; break;
20586 case X86::CX: DestReg = X86::CL; break;
20587 case X86::BX: DestReg = X86::BL; break;
20590 Res.first = DestReg;
20591 Res.second = &X86::GR8RegClass;
20593 } else if (VT == MVT::i32 || VT == MVT::f32) {
20594 unsigned DestReg = 0;
20595 switch (Res.first) {
20597 case X86::AX: DestReg = X86::EAX; break;
20598 case X86::DX: DestReg = X86::EDX; break;
20599 case X86::CX: DestReg = X86::ECX; break;
20600 case X86::BX: DestReg = X86::EBX; break;
20601 case X86::SI: DestReg = X86::ESI; break;
20602 case X86::DI: DestReg = X86::EDI; break;
20603 case X86::BP: DestReg = X86::EBP; break;
20604 case X86::SP: DestReg = X86::ESP; break;
20607 Res.first = DestReg;
20608 Res.second = &X86::GR32RegClass;
20610 } else if (VT == MVT::i64 || VT == MVT::f64) {
20611 unsigned DestReg = 0;
20612 switch (Res.first) {
20614 case X86::AX: DestReg = X86::RAX; break;
20615 case X86::DX: DestReg = X86::RDX; break;
20616 case X86::CX: DestReg = X86::RCX; break;
20617 case X86::BX: DestReg = X86::RBX; break;
20618 case X86::SI: DestReg = X86::RSI; break;
20619 case X86::DI: DestReg = X86::RDI; break;
20620 case X86::BP: DestReg = X86::RBP; break;
20621 case X86::SP: DestReg = X86::RSP; break;
20624 Res.first = DestReg;
20625 Res.second = &X86::GR64RegClass;
20628 } else if (Res.second == &X86::FR32RegClass ||
20629 Res.second == &X86::FR64RegClass ||
20630 Res.second == &X86::VR128RegClass ||
20631 Res.second == &X86::VR256RegClass ||
20632 Res.second == &X86::FR32XRegClass ||
20633 Res.second == &X86::FR64XRegClass ||
20634 Res.second == &X86::VR128XRegClass ||
20635 Res.second == &X86::VR256XRegClass ||
20636 Res.second == &X86::VR512RegClass) {
20637 // Handle references to XMM physical registers that got mapped into the
20638 // wrong class. This can happen with constraints like {xmm0} where the
20639 // target independent register mapper will just pick the first match it can
20640 // find, ignoring the required type.
20642 if (VT == MVT::f32 || VT == MVT::i32)
20643 Res.second = &X86::FR32RegClass;
20644 else if (VT == MVT::f64 || VT == MVT::i64)
20645 Res.second = &X86::FR64RegClass;
20646 else if (X86::VR128RegClass.hasType(VT))
20647 Res.second = &X86::VR128RegClass;
20648 else if (X86::VR256RegClass.hasType(VT))
20649 Res.second = &X86::VR256RegClass;
20650 else if (X86::VR512RegClass.hasType(VT))
20651 Res.second = &X86::VR512RegClass;