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, nullptr);
270 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
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::MULHS, VT, Expand);
830 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
831 setOperationAction(ISD::MULHU, VT, Expand);
832 setOperationAction(ISD::SDIVREM, VT, Expand);
833 setOperationAction(ISD::UDIVREM, VT, Expand);
834 setOperationAction(ISD::FPOW, VT, Expand);
835 setOperationAction(ISD::CTPOP, VT, Expand);
836 setOperationAction(ISD::CTTZ, VT, Expand);
837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::CTLZ, VT, Expand);
839 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840 setOperationAction(ISD::SHL, VT, Expand);
841 setOperationAction(ISD::SRA, VT, Expand);
842 setOperationAction(ISD::SRL, VT, Expand);
843 setOperationAction(ISD::ROTL, VT, Expand);
844 setOperationAction(ISD::ROTR, VT, Expand);
845 setOperationAction(ISD::BSWAP, VT, Expand);
846 setOperationAction(ISD::SETCC, VT, Expand);
847 setOperationAction(ISD::FLOG, VT, Expand);
848 setOperationAction(ISD::FLOG2, VT, Expand);
849 setOperationAction(ISD::FLOG10, VT, Expand);
850 setOperationAction(ISD::FEXP, VT, Expand);
851 setOperationAction(ISD::FEXP2, VT, Expand);
852 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857 setOperationAction(ISD::TRUNCATE, VT, Expand);
858 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861 setOperationAction(ISD::VSELECT, VT, Expand);
862 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864 setTruncStoreAction(VT,
865 (MVT::SimpleValueType)InnerVT, Expand);
866 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872 // with -msoft-float, disable use of MMX as well.
873 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875 // No operations on x86mmx supported, everything uses intrinsics.
878 // MMX-sized vectors (other than x86mmx) are expected to be expanded
879 // into smaller operations.
880 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
881 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
882 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
883 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
884 setOperationAction(ISD::AND, MVT::v8i8, Expand);
885 setOperationAction(ISD::AND, MVT::v4i16, Expand);
886 setOperationAction(ISD::AND, MVT::v2i32, Expand);
887 setOperationAction(ISD::AND, MVT::v1i64, Expand);
888 setOperationAction(ISD::OR, MVT::v8i8, Expand);
889 setOperationAction(ISD::OR, MVT::v4i16, Expand);
890 setOperationAction(ISD::OR, MVT::v2i32, Expand);
891 setOperationAction(ISD::OR, MVT::v1i64, Expand);
892 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
893 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
894 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
895 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
901 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
902 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
903 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
904 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
908 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
910 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
914 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
915 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
916 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
917 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
918 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
919 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
920 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
921 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
922 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
927 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931 // registers cannot be used even for integer operations.
932 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
938 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
939 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
940 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
941 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
942 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
943 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
944 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
945 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
946 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
947 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
948 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
949 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
950 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
951 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
953 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
954 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
956 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
957 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
959 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
961 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
962 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
964 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
970 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972 MVT VT = (MVT::SimpleValueType)i;
973 // Do not attempt to custom lower non-power-of-2 vectors
974 if (!isPowerOf2_32(VT.getVectorNumElements()))
976 // Do not attempt to custom lower non-128-bit vectors
977 if (!VT.is128BitVector())
979 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
980 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
984 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
986 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
991 if (Subtarget->is64Bit()) {
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
996 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998 MVT VT = (MVT::SimpleValueType)i;
1000 // Do not attempt to promote non-128-bit vectors
1001 if (!VT.is128BitVector())
1004 setOperationAction(ISD::AND, VT, Promote);
1005 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1006 setOperationAction(ISD::OR, VT, Promote);
1007 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1008 setOperationAction(ISD::XOR, VT, Promote);
1009 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1010 setOperationAction(ISD::LOAD, VT, Promote);
1011 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1012 setOperationAction(ISD::SELECT, VT, Promote);
1013 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1016 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1018 // Custom lower v2i64 and v2f64 selects.
1019 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1020 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1021 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1022 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1024 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1025 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1029 // As there is no 64-bit GPR available, we need build a special custom
1030 // sequence to convert from v2i32 to v2f32.
1031 if (!Subtarget->is64Bit())
1032 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1034 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1037 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1040 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1041 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1042 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1043 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1044 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1045 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1046 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1047 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1048 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1049 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1050 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1060 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1063 // FIXME: Do we need to handle scalar-to-vector here?
1064 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1065 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
1067 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1068 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1069 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1071 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1073 // i8 and i16 vectors are custom , because the source register and source
1074 // source memory operand types are not the same width. f32 vectors are
1075 // custom since the immediate controlling the insert encodes additional
1077 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1078 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1079 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1080 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1082 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1084 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1085 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1087 // FIXME: these should be Legal but thats only for the case where
1088 // the index is constant. For now custom expand to deal with that.
1089 if (Subtarget->is64Bit()) {
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1095 if (Subtarget->hasSSE2()) {
1096 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1097 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1099 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1100 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1102 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1103 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1105 // In the customized shift lowering, the legal cases in AVX2 will be
1107 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1108 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1110 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1111 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1113 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1116 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1117 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1118 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1119 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1120 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1121 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1122 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1124 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1125 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1126 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1128 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1130 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1132 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1134 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1139 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1141 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1143 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1144 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1145 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1146 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1147 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1152 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1154 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1155 // even though v8i16 is a legal type.
1156 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1157 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1158 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1160 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1161 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1162 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1164 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1167 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1169 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1172 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1173 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1175 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1179 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1180 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1181 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1183 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1184 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1187 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1188 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1189 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1190 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1192 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1193 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1195 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1198 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1199 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1200 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1201 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1202 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1203 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1205 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1206 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1207 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1208 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1209 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1210 setOperationAction(ISD::FMA, MVT::f32, Legal);
1211 setOperationAction(ISD::FMA, MVT::f64, Legal);
1214 if (Subtarget->hasInt256()) {
1215 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1216 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1217 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1218 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1220 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1221 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1222 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1223 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1225 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1226 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1227 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1228 // Don't lower v32i8 because there is no 128-bit byte mul
1230 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1231 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1232 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1233 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1235 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1237 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1238 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1239 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1240 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1242 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1243 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1244 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1245 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1247 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1248 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1249 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1250 // Don't lower v32i8 because there is no 128-bit byte mul
1253 // In the customized shift lowering, the legal cases in AVX2 will be
1255 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1256 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1258 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1259 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1261 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1263 // Custom lower several nodes for 256-bit types.
1264 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1265 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1266 MVT VT = (MVT::SimpleValueType)i;
1268 // Extract subvector is special because the value type
1269 // (result) is 128-bit but the source is 256-bit wide.
1270 if (VT.is128BitVector())
1271 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1273 // Do not attempt to custom lower other non-256-bit vectors
1274 if (!VT.is256BitVector())
1277 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1278 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1279 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1280 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1281 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1282 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1283 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1286 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1287 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1288 MVT VT = (MVT::SimpleValueType)i;
1290 // Do not attempt to promote non-256-bit vectors
1291 if (!VT.is256BitVector())
1294 setOperationAction(ISD::AND, VT, Promote);
1295 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1296 setOperationAction(ISD::OR, VT, Promote);
1297 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1298 setOperationAction(ISD::XOR, VT, Promote);
1299 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1300 setOperationAction(ISD::LOAD, VT, Promote);
1301 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1302 setOperationAction(ISD::SELECT, VT, Promote);
1303 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1307 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1308 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1309 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1310 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1313 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1314 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1315 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1317 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1318 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1319 setOperationAction(ISD::XOR, MVT::i1, Legal);
1320 setOperationAction(ISD::OR, MVT::i1, Legal);
1321 setOperationAction(ISD::AND, MVT::i1, Legal);
1322 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1323 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1324 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1325 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1326 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1327 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1329 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1330 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1331 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1332 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1334 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1336 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1338 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1340 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1342 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1346 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1347 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1348 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1349 if (Subtarget->is64Bit()) {
1350 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1351 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1352 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1353 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1355 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1356 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1357 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1358 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1359 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1360 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1361 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1362 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1363 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1364 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1366 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1368 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1369 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1372 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1373 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1374 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1375 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1376 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1377 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1378 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1380 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1381 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1382 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1383 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1384 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1385 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1387 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1388 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1390 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1396 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1397 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1398 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1399 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1400 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1402 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1403 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1405 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1406 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1408 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1410 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1411 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1413 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1414 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1416 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1417 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1419 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1420 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1421 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1422 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1423 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1424 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1426 // Custom lower several nodes.
1427 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1428 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1429 MVT VT = (MVT::SimpleValueType)i;
1431 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1432 // Extract subvector is special because the value type
1433 // (result) is 256/128-bit but the source is 512-bit wide.
1434 if (VT.is128BitVector() || VT.is256BitVector())
1435 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1437 if (VT.getVectorElementType() == MVT::i1)
1438 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1440 // Do not attempt to custom lower other non-512-bit vectors
1441 if (!VT.is512BitVector())
1444 if ( EltSize >= 32) {
1445 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1446 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1447 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1448 setOperationAction(ISD::VSELECT, VT, Legal);
1449 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1450 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1451 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1454 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1455 MVT VT = (MVT::SimpleValueType)i;
1457 // Do not attempt to promote non-256-bit vectors
1458 if (!VT.is512BitVector())
1461 setOperationAction(ISD::SELECT, VT, Promote);
1462 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1466 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1467 // of this type with custom code.
1468 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1469 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1470 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1474 // We want to custom lower some of our intrinsics.
1475 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1476 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1477 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1478 if (!Subtarget->is64Bit())
1479 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1481 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1482 // handle type legalization for these operations here.
1484 // FIXME: We really should do custom legalization for addition and
1485 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1486 // than generic legalization for 64-bit multiplication-with-overflow, though.
1487 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1488 // Add/Sub/Mul with overflow operations are custom lowered.
1490 setOperationAction(ISD::SADDO, VT, Custom);
1491 setOperationAction(ISD::UADDO, VT, Custom);
1492 setOperationAction(ISD::SSUBO, VT, Custom);
1493 setOperationAction(ISD::USUBO, VT, Custom);
1494 setOperationAction(ISD::SMULO, VT, Custom);
1495 setOperationAction(ISD::UMULO, VT, Custom);
1498 // There are no 8-bit 3-address imul/mul instructions
1499 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1500 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1502 if (!Subtarget->is64Bit()) {
1503 // These libcalls are not available in 32-bit.
1504 setLibcallName(RTLIB::SHL_I128, nullptr);
1505 setLibcallName(RTLIB::SRL_I128, nullptr);
1506 setLibcallName(RTLIB::SRA_I128, nullptr);
1509 // Combine sin / cos into one node or libcall if possible.
1510 if (Subtarget->hasSinCos()) {
1511 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1512 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1513 if (Subtarget->isTargetDarwin()) {
1514 // For MacOSX, we don't want to the normal expansion of a libcall to
1515 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1517 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1518 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1522 // We have target-specific dag combine patterns for the following nodes:
1523 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1524 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1525 setTargetDAGCombine(ISD::VSELECT);
1526 setTargetDAGCombine(ISD::SELECT);
1527 setTargetDAGCombine(ISD::SHL);
1528 setTargetDAGCombine(ISD::SRA);
1529 setTargetDAGCombine(ISD::SRL);
1530 setTargetDAGCombine(ISD::OR);
1531 setTargetDAGCombine(ISD::AND);
1532 setTargetDAGCombine(ISD::ADD);
1533 setTargetDAGCombine(ISD::FADD);
1534 setTargetDAGCombine(ISD::FSUB);
1535 setTargetDAGCombine(ISD::FMA);
1536 setTargetDAGCombine(ISD::SUB);
1537 setTargetDAGCombine(ISD::LOAD);
1538 setTargetDAGCombine(ISD::STORE);
1539 setTargetDAGCombine(ISD::ZERO_EXTEND);
1540 setTargetDAGCombine(ISD::ANY_EXTEND);
1541 setTargetDAGCombine(ISD::SIGN_EXTEND);
1542 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1543 setTargetDAGCombine(ISD::TRUNCATE);
1544 setTargetDAGCombine(ISD::SINT_TO_FP);
1545 setTargetDAGCombine(ISD::SETCC);
1546 if (Subtarget->is64Bit())
1547 setTargetDAGCombine(ISD::MUL);
1548 setTargetDAGCombine(ISD::XOR);
1550 computeRegisterProperties();
1552 // On Darwin, -Os means optimize for size without hurting performance,
1553 // do not reduce the limit.
1554 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1555 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1556 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1557 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1558 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1559 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1560 setPrefLoopAlignment(4); // 2^4 bytes.
1562 // Predictable cmov don't hurt on atom because it's in-order.
1563 PredictableSelectIsExpensive = !Subtarget->isAtom();
1565 setPrefFunctionAlignment(4); // 2^4 bytes.
1568 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1570 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1572 if (Subtarget->hasAVX512())
1573 switch(VT.getVectorNumElements()) {
1574 case 8: return MVT::v8i1;
1575 case 16: return MVT::v16i1;
1578 return VT.changeVectorElementTypeToInteger();
1581 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1582 /// the desired ByVal argument alignment.
1583 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1586 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1587 if (VTy->getBitWidth() == 128)
1589 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1590 unsigned EltAlign = 0;
1591 getMaxByValAlign(ATy->getElementType(), EltAlign);
1592 if (EltAlign > MaxAlign)
1593 MaxAlign = EltAlign;
1594 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1595 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1596 unsigned EltAlign = 0;
1597 getMaxByValAlign(STy->getElementType(i), EltAlign);
1598 if (EltAlign > MaxAlign)
1599 MaxAlign = EltAlign;
1606 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1607 /// function arguments in the caller parameter area. For X86, aggregates
1608 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1609 /// are at 4-byte boundaries.
1610 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1611 if (Subtarget->is64Bit()) {
1612 // Max of 8 and alignment of type.
1613 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1620 if (Subtarget->hasSSE1())
1621 getMaxByValAlign(Ty, Align);
1625 /// getOptimalMemOpType - Returns the target specific optimal type for load
1626 /// and store operations as a result of memset, memcpy, and memmove
1627 /// lowering. If DstAlign is zero that means it's safe to destination
1628 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1629 /// means there isn't a need to check it against alignment requirement,
1630 /// probably because the source does not need to be loaded. If 'IsMemset' is
1631 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1632 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1633 /// source is constant so it does not need to be loaded.
1634 /// It returns EVT::Other if the type should be determined using generic
1635 /// target-independent logic.
1637 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1638 unsigned DstAlign, unsigned SrcAlign,
1639 bool IsMemset, bool ZeroMemset,
1641 MachineFunction &MF) const {
1642 const Function *F = MF.getFunction();
1643 if ((!IsMemset || ZeroMemset) &&
1644 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1645 Attribute::NoImplicitFloat)) {
1647 (Subtarget->isUnalignedMemAccessFast() ||
1648 ((DstAlign == 0 || DstAlign >= 16) &&
1649 (SrcAlign == 0 || SrcAlign >= 16)))) {
1651 if (Subtarget->hasInt256())
1653 if (Subtarget->hasFp256())
1656 if (Subtarget->hasSSE2())
1658 if (Subtarget->hasSSE1())
1660 } else if (!MemcpyStrSrc && Size >= 8 &&
1661 !Subtarget->is64Bit() &&
1662 Subtarget->hasSSE2()) {
1663 // Do not use f64 to lower memcpy if source is string constant. It's
1664 // better to use i32 to avoid the loads.
1668 if (Subtarget->is64Bit() && Size >= 8)
1673 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1675 return X86ScalarSSEf32;
1676 else if (VT == MVT::f64)
1677 return X86ScalarSSEf64;
1682 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1686 *Fast = Subtarget->isUnalignedMemAccessFast();
1690 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1691 /// current function. The returned value is a member of the
1692 /// MachineJumpTableInfo::JTEntryKind enum.
1693 unsigned X86TargetLowering::getJumpTableEncoding() const {
1694 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1696 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1697 Subtarget->isPICStyleGOT())
1698 return MachineJumpTableInfo::EK_Custom32;
1700 // Otherwise, use the normal jump table encoding heuristics.
1701 return TargetLowering::getJumpTableEncoding();
1705 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1706 const MachineBasicBlock *MBB,
1707 unsigned uid,MCContext &Ctx) const{
1708 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1709 Subtarget->isPICStyleGOT());
1710 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1712 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1713 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1716 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1718 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1719 SelectionDAG &DAG) const {
1720 if (!Subtarget->is64Bit())
1721 // This doesn't have SDLoc associated with it, but is not really the
1722 // same as a Register.
1723 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1727 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1728 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1730 const MCExpr *X86TargetLowering::
1731 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1732 MCContext &Ctx) const {
1733 // X86-64 uses RIP relative addressing based on the jump table label.
1734 if (Subtarget->isPICStyleRIPRel())
1735 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1737 // Otherwise, the reference is relative to the PIC base.
1738 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1741 // FIXME: Why this routine is here? Move to RegInfo!
1742 std::pair<const TargetRegisterClass*, uint8_t>
1743 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1744 const TargetRegisterClass *RRC = nullptr;
1746 switch (VT.SimpleTy) {
1748 return TargetLowering::findRepresentativeClass(VT);
1749 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1750 RRC = Subtarget->is64Bit() ?
1751 (const TargetRegisterClass*)&X86::GR64RegClass :
1752 (const TargetRegisterClass*)&X86::GR32RegClass;
1755 RRC = &X86::VR64RegClass;
1757 case MVT::f32: case MVT::f64:
1758 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1759 case MVT::v4f32: case MVT::v2f64:
1760 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1762 RRC = &X86::VR128RegClass;
1765 return std::make_pair(RRC, Cost);
1768 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1769 unsigned &Offset) const {
1770 if (!Subtarget->isTargetLinux())
1773 if (Subtarget->is64Bit()) {
1774 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1776 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1788 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1789 unsigned DestAS) const {
1790 assert(SrcAS != DestAS && "Expected different address spaces!");
1792 return SrcAS < 256 && DestAS < 256;
1795 //===----------------------------------------------------------------------===//
1796 // Return Value Calling Convention Implementation
1797 //===----------------------------------------------------------------------===//
1799 #include "X86GenCallingConv.inc"
1802 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1803 MachineFunction &MF, bool isVarArg,
1804 const SmallVectorImpl<ISD::OutputArg> &Outs,
1805 LLVMContext &Context) const {
1806 SmallVector<CCValAssign, 16> RVLocs;
1807 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1809 return CCInfo.CheckReturn(Outs, RetCC_X86);
1812 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1813 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1818 X86TargetLowering::LowerReturn(SDValue Chain,
1819 CallingConv::ID CallConv, bool isVarArg,
1820 const SmallVectorImpl<ISD::OutputArg> &Outs,
1821 const SmallVectorImpl<SDValue> &OutVals,
1822 SDLoc dl, SelectionDAG &DAG) const {
1823 MachineFunction &MF = DAG.getMachineFunction();
1824 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1826 SmallVector<CCValAssign, 16> RVLocs;
1827 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1828 RVLocs, *DAG.getContext());
1829 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1832 SmallVector<SDValue, 6> RetOps;
1833 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1834 // Operand #1 = Bytes To Pop
1835 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1838 // Copy the result values into the output registers.
1839 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1840 CCValAssign &VA = RVLocs[i];
1841 assert(VA.isRegLoc() && "Can only return in registers!");
1842 SDValue ValToCopy = OutVals[i];
1843 EVT ValVT = ValToCopy.getValueType();
1845 // Promote values to the appropriate types
1846 if (VA.getLocInfo() == CCValAssign::SExt)
1847 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1848 else if (VA.getLocInfo() == CCValAssign::ZExt)
1849 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1850 else if (VA.getLocInfo() == CCValAssign::AExt)
1851 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1852 else if (VA.getLocInfo() == CCValAssign::BCvt)
1853 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1855 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1856 "Unexpected FP-extend for return value.");
1858 // If this is x86-64, and we disabled SSE, we can't return FP values,
1859 // or SSE or MMX vectors.
1860 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1861 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1862 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1863 report_fatal_error("SSE register return with SSE disabled");
1865 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1866 // llvm-gcc has never done it right and no one has noticed, so this
1867 // should be OK for now.
1868 if (ValVT == MVT::f64 &&
1869 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1870 report_fatal_error("SSE2 register return with SSE2 disabled");
1872 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1873 // the RET instruction and handled by the FP Stackifier.
1874 if (VA.getLocReg() == X86::ST0 ||
1875 VA.getLocReg() == X86::ST1) {
1876 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1877 // change the value to the FP stack register class.
1878 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1879 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1880 RetOps.push_back(ValToCopy);
1881 // Don't emit a copytoreg.
1885 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1886 // which is returned in RAX / RDX.
1887 if (Subtarget->is64Bit()) {
1888 if (ValVT == MVT::x86mmx) {
1889 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1890 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1891 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1893 // If we don't have SSE2 available, convert to v4f32 so the generated
1894 // register is legal.
1895 if (!Subtarget->hasSSE2())
1896 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1901 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1902 Flag = Chain.getValue(1);
1903 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1906 // The x86-64 ABIs require that for returning structs by value we copy
1907 // the sret argument into %rax/%eax (depending on ABI) for the return.
1908 // Win32 requires us to put the sret argument to %eax as well.
1909 // We saved the argument into a virtual register in the entry block,
1910 // so now we copy the value out and into %rax/%eax.
1911 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1912 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1913 MachineFunction &MF = DAG.getMachineFunction();
1914 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1915 unsigned Reg = FuncInfo->getSRetReturnReg();
1917 "SRetReturnReg should have been set in LowerFormalArguments().");
1918 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1921 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1922 X86::RAX : X86::EAX;
1923 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1924 Flag = Chain.getValue(1);
1926 // RAX/EAX now acts like a return value.
1927 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1930 RetOps[0] = Chain; // Update chain.
1932 // Add the flag if we have it.
1934 RetOps.push_back(Flag);
1936 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1939 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1940 if (N->getNumValues() != 1)
1942 if (!N->hasNUsesOfValue(1, 0))
1945 SDValue TCChain = Chain;
1946 SDNode *Copy = *N->use_begin();
1947 if (Copy->getOpcode() == ISD::CopyToReg) {
1948 // If the copy has a glue operand, we conservatively assume it isn't safe to
1949 // perform a tail call.
1950 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1952 TCChain = Copy->getOperand(0);
1953 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1956 bool HasRet = false;
1957 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1959 if (UI->getOpcode() != X86ISD::RET_FLAG)
1972 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1973 ISD::NodeType ExtendKind) const {
1975 // TODO: Is this also valid on 32-bit?
1976 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1977 ReturnMVT = MVT::i8;
1979 ReturnMVT = MVT::i32;
1981 MVT MinVT = getRegisterType(ReturnMVT);
1982 return VT.bitsLT(MinVT) ? MinVT : VT;
1985 /// LowerCallResult - Lower the result values of a call into the
1986 /// appropriate copies out of appropriate physical registers.
1989 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1990 CallingConv::ID CallConv, bool isVarArg,
1991 const SmallVectorImpl<ISD::InputArg> &Ins,
1992 SDLoc dl, SelectionDAG &DAG,
1993 SmallVectorImpl<SDValue> &InVals) const {
1995 // Assign locations to each value returned by this call.
1996 SmallVector<CCValAssign, 16> RVLocs;
1997 bool Is64Bit = Subtarget->is64Bit();
1998 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1999 getTargetMachine(), RVLocs, *DAG.getContext());
2000 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2002 // Copy all of the result registers out of their specified physreg.
2003 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2004 CCValAssign &VA = RVLocs[i];
2005 EVT CopyVT = VA.getValVT();
2007 // If this is x86-64, and we disabled SSE, we can't return FP values
2008 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2009 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2010 report_fatal_error("SSE register return with SSE disabled");
2015 // If this is a call to a function that returns an fp value on the floating
2016 // point stack, we must guarantee the value is popped from the stack, so
2017 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2018 // if the return value is not used. We use the FpPOP_RETVAL instruction
2020 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2021 // If we prefer to use the value in xmm registers, copy it out as f80 and
2022 // use a truncate to move it from fp stack reg to xmm reg.
2023 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2024 SDValue Ops[] = { Chain, InFlag };
2025 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2026 MVT::Other, MVT::Glue, Ops), 1);
2027 Val = Chain.getValue(0);
2029 // Round the f80 to the right size, which also moves it to the appropriate
2031 if (CopyVT != VA.getValVT())
2032 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2033 // This truncation won't change the value.
2034 DAG.getIntPtrConstant(1));
2036 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2037 CopyVT, InFlag).getValue(1);
2038 Val = Chain.getValue(0);
2040 InFlag = Chain.getValue(2);
2041 InVals.push_back(Val);
2047 //===----------------------------------------------------------------------===//
2048 // C & StdCall & Fast Calling Convention implementation
2049 //===----------------------------------------------------------------------===//
2050 // StdCall calling convention seems to be standard for many Windows' API
2051 // routines and around. It differs from C calling convention just a little:
2052 // callee should clean up the stack, not caller. Symbols should be also
2053 // decorated in some fancy way :) It doesn't support any vector arguments.
2054 // For info on fast calling convention see Fast Calling Convention (tail call)
2055 // implementation LowerX86_32FastCCCallTo.
2057 /// CallIsStructReturn - Determines whether a call uses struct return
2059 enum StructReturnType {
2064 static StructReturnType
2065 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2067 return NotStructReturn;
2069 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2070 if (!Flags.isSRet())
2071 return NotStructReturn;
2072 if (Flags.isInReg())
2073 return RegStructReturn;
2074 return StackStructReturn;
2077 /// ArgsAreStructReturn - Determines whether a function uses struct
2078 /// return semantics.
2079 static StructReturnType
2080 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2082 return NotStructReturn;
2084 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2085 if (!Flags.isSRet())
2086 return NotStructReturn;
2087 if (Flags.isInReg())
2088 return RegStructReturn;
2089 return StackStructReturn;
2092 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2093 /// by "Src" to address "Dst" with size and alignment information specified by
2094 /// the specific parameter attribute. The copy will be passed as a byval
2095 /// function parameter.
2097 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2098 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2100 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2102 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2103 /*isVolatile*/false, /*AlwaysInline=*/true,
2104 MachinePointerInfo(), MachinePointerInfo());
2107 /// IsTailCallConvention - Return true if the calling convention is one that
2108 /// supports tail call optimization.
2109 static bool IsTailCallConvention(CallingConv::ID CC) {
2110 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2111 CC == CallingConv::HiPE);
2114 /// \brief Return true if the calling convention is a C calling convention.
2115 static bool IsCCallConvention(CallingConv::ID CC) {
2116 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2117 CC == CallingConv::X86_64_SysV);
2120 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2121 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2125 CallingConv::ID CalleeCC = CS.getCallingConv();
2126 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2132 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2133 /// a tailcall target by changing its ABI.
2134 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2135 bool GuaranteedTailCallOpt) {
2136 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2140 X86TargetLowering::LowerMemArgument(SDValue Chain,
2141 CallingConv::ID CallConv,
2142 const SmallVectorImpl<ISD::InputArg> &Ins,
2143 SDLoc dl, SelectionDAG &DAG,
2144 const CCValAssign &VA,
2145 MachineFrameInfo *MFI,
2147 // Create the nodes corresponding to a load from this parameter slot.
2148 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2149 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2150 getTargetMachine().Options.GuaranteedTailCallOpt);
2151 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2154 // If value is passed by pointer we have address passed instead of the value
2156 if (VA.getLocInfo() == CCValAssign::Indirect)
2157 ValVT = VA.getLocVT();
2159 ValVT = VA.getValVT();
2161 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2162 // changed with more analysis.
2163 // In case of tail call optimization mark all arguments mutable. Since they
2164 // could be overwritten by lowering of arguments in case of a tail call.
2165 if (Flags.isByVal()) {
2166 unsigned Bytes = Flags.getByValSize();
2167 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2168 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2169 return DAG.getFrameIndex(FI, getPointerTy());
2171 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2172 VA.getLocMemOffset(), isImmutable);
2173 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2174 return DAG.getLoad(ValVT, dl, Chain, FIN,
2175 MachinePointerInfo::getFixedStack(FI),
2176 false, false, false, 0);
2181 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2182 CallingConv::ID CallConv,
2184 const SmallVectorImpl<ISD::InputArg> &Ins,
2187 SmallVectorImpl<SDValue> &InVals)
2189 MachineFunction &MF = DAG.getMachineFunction();
2190 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2192 const Function* Fn = MF.getFunction();
2193 if (Fn->hasExternalLinkage() &&
2194 Subtarget->isTargetCygMing() &&
2195 Fn->getName() == "main")
2196 FuncInfo->setForceFramePointer(true);
2198 MachineFrameInfo *MFI = MF.getFrameInfo();
2199 bool Is64Bit = Subtarget->is64Bit();
2200 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2202 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2203 "Var args not supported with calling convention fastcc, ghc or hipe");
2205 // Assign locations to all of the incoming arguments.
2206 SmallVector<CCValAssign, 16> ArgLocs;
2207 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2208 ArgLocs, *DAG.getContext());
2210 // Allocate shadow area for Win64
2212 CCInfo.AllocateStack(32, 8);
2214 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2216 unsigned LastVal = ~0U;
2218 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2219 CCValAssign &VA = ArgLocs[i];
2220 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2222 assert(VA.getValNo() != LastVal &&
2223 "Don't support value assigned to multiple locs yet");
2225 LastVal = VA.getValNo();
2227 if (VA.isRegLoc()) {
2228 EVT RegVT = VA.getLocVT();
2229 const TargetRegisterClass *RC;
2230 if (RegVT == MVT::i32)
2231 RC = &X86::GR32RegClass;
2232 else if (Is64Bit && RegVT == MVT::i64)
2233 RC = &X86::GR64RegClass;
2234 else if (RegVT == MVT::f32)
2235 RC = &X86::FR32RegClass;
2236 else if (RegVT == MVT::f64)
2237 RC = &X86::FR64RegClass;
2238 else if (RegVT.is512BitVector())
2239 RC = &X86::VR512RegClass;
2240 else if (RegVT.is256BitVector())
2241 RC = &X86::VR256RegClass;
2242 else if (RegVT.is128BitVector())
2243 RC = &X86::VR128RegClass;
2244 else if (RegVT == MVT::x86mmx)
2245 RC = &X86::VR64RegClass;
2246 else if (RegVT == MVT::i1)
2247 RC = &X86::VK1RegClass;
2248 else if (RegVT == MVT::v8i1)
2249 RC = &X86::VK8RegClass;
2250 else if (RegVT == MVT::v16i1)
2251 RC = &X86::VK16RegClass;
2253 llvm_unreachable("Unknown argument type!");
2255 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2256 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2258 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2259 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2261 if (VA.getLocInfo() == CCValAssign::SExt)
2262 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2263 DAG.getValueType(VA.getValVT()));
2264 else if (VA.getLocInfo() == CCValAssign::ZExt)
2265 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2266 DAG.getValueType(VA.getValVT()));
2267 else if (VA.getLocInfo() == CCValAssign::BCvt)
2268 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2270 if (VA.isExtInLoc()) {
2271 // Handle MMX values passed in XMM regs.
2272 if (RegVT.isVector())
2273 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2275 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2278 assert(VA.isMemLoc());
2279 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2282 // If value is passed via pointer - do a load.
2283 if (VA.getLocInfo() == CCValAssign::Indirect)
2284 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2285 MachinePointerInfo(), false, false, false, 0);
2287 InVals.push_back(ArgValue);
2290 // The x86-64 ABIs require that for returning structs by value we copy
2291 // the sret argument into %rax/%eax (depending on ABI) for the return.
2292 // Win32 requires us to put the sret argument to %eax as well.
2293 // Save the argument into a virtual register so that we can access it
2294 // from the return points.
2295 if (MF.getFunction()->hasStructRetAttr() &&
2296 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2297 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2298 unsigned Reg = FuncInfo->getSRetReturnReg();
2300 MVT PtrTy = getPointerTy();
2301 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2302 FuncInfo->setSRetReturnReg(Reg);
2304 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2305 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2308 unsigned StackSize = CCInfo.getNextStackOffset();
2309 // Align stack specially for tail calls.
2310 if (FuncIsMadeTailCallSafe(CallConv,
2311 MF.getTarget().Options.GuaranteedTailCallOpt))
2312 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2314 // If the function takes variable number of arguments, make a frame index for
2315 // the start of the first vararg value... for expansion of llvm.va_start.
2317 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2318 CallConv != CallingConv::X86_ThisCall)) {
2319 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2322 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2324 // FIXME: We should really autogenerate these arrays
2325 static const MCPhysReg GPR64ArgRegsWin64[] = {
2326 X86::RCX, X86::RDX, X86::R8, X86::R9
2328 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2329 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2331 static const MCPhysReg XMMArgRegs64Bit[] = {
2332 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2333 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2335 const MCPhysReg *GPR64ArgRegs;
2336 unsigned NumXMMRegs = 0;
2339 // The XMM registers which might contain var arg parameters are shadowed
2340 // in their paired GPR. So we only need to save the GPR to their home
2342 TotalNumIntRegs = 4;
2343 GPR64ArgRegs = GPR64ArgRegsWin64;
2345 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2346 GPR64ArgRegs = GPR64ArgRegs64Bit;
2348 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2351 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2354 bool NoImplicitFloatOps = Fn->getAttributes().
2355 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2356 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2357 "SSE register cannot be used when SSE is disabled!");
2358 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2359 NoImplicitFloatOps) &&
2360 "SSE register cannot be used when SSE is disabled!");
2361 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2362 !Subtarget->hasSSE1())
2363 // Kernel mode asks for SSE to be disabled, so don't push them
2365 TotalNumXMMRegs = 0;
2368 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2369 // Get to the caller-allocated home save location. Add 8 to account
2370 // for the return address.
2371 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2372 FuncInfo->setRegSaveFrameIndex(
2373 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2374 // Fixup to set vararg frame on shadow area (4 x i64).
2376 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2378 // For X86-64, if there are vararg parameters that are passed via
2379 // registers, then we must store them to their spots on the stack so
2380 // they may be loaded by deferencing the result of va_next.
2381 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2382 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2383 FuncInfo->setRegSaveFrameIndex(
2384 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2388 // Store the integer parameter registers.
2389 SmallVector<SDValue, 8> MemOps;
2390 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2392 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2393 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2394 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2395 DAG.getIntPtrConstant(Offset));
2396 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2397 &X86::GR64RegClass);
2398 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2400 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2401 MachinePointerInfo::getFixedStack(
2402 FuncInfo->getRegSaveFrameIndex(), Offset),
2404 MemOps.push_back(Store);
2408 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2409 // Now store the XMM (fp + vector) parameter registers.
2410 SmallVector<SDValue, 11> SaveXMMOps;
2411 SaveXMMOps.push_back(Chain);
2413 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2414 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2415 SaveXMMOps.push_back(ALVal);
2417 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418 FuncInfo->getRegSaveFrameIndex()));
2419 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2420 FuncInfo->getVarArgsFPOffset()));
2422 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2423 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2424 &X86::VR128RegClass);
2425 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2426 SaveXMMOps.push_back(Val);
2428 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2429 MVT::Other, SaveXMMOps));
2432 if (!MemOps.empty())
2433 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2437 // Some CCs need callee pop.
2438 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2442 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443 // If this is an sret function, the return should pop the hidden pointer.
2444 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446 argsAreStructReturn(Ins) == StackStructReturn)
2447 FuncInfo->setBytesToPopOnReturn(4);
2451 // RegSaveFrameIndex is X86-64 only.
2452 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453 if (CallConv == CallingConv::X86_FastCall ||
2454 CallConv == CallingConv::X86_ThisCall)
2455 // fastcc functions can't have varargs.
2456 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2459 FuncInfo->setArgumentStackSize(StackSize);
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466 SDValue StackPtr, SDValue Arg,
2467 SDLoc dl, SelectionDAG &DAG,
2468 const CCValAssign &VA,
2469 ISD::ArgFlagsTy Flags) const {
2470 unsigned LocMemOffset = VA.getLocMemOffset();
2471 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473 if (Flags.isByVal())
2474 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2476 return DAG.getStore(Chain, dl, Arg, PtrOff,
2477 MachinePointerInfo::getStack(LocMemOffset),
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485 SDValue &OutRetAddr, SDValue Chain,
2486 bool IsTailCall, bool Is64Bit,
2487 int FPDiff, SDLoc dl) const {
2488 // Adjust the Return address stack slot.
2489 EVT VT = getPointerTy();
2490 OutRetAddr = getReturnAddressFrameIndex(DAG);
2492 // Load the "old" Return address.
2493 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494 false, false, false, 0);
2495 return SDValue(OutRetAddr.getNode(), 1);
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503 unsigned SlotSize, int FPDiff, SDLoc dl) {
2504 // Store the return address to the appropriate stack slot.
2505 if (!FPDiff) return Chain;
2506 // Calculate the new stack slot for the return address.
2507 int NewReturnAddrFI =
2508 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2510 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519 SmallVectorImpl<SDValue> &InVals) const {
2520 SelectionDAG &DAG = CLI.DAG;
2522 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2524 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2525 SDValue Chain = CLI.Chain;
2526 SDValue Callee = CLI.Callee;
2527 CallingConv::ID CallConv = CLI.CallConv;
2528 bool &isTailCall = CLI.IsTailCall;
2529 bool isVarArg = CLI.IsVarArg;
2531 MachineFunction &MF = DAG.getMachineFunction();
2532 bool Is64Bit = Subtarget->is64Bit();
2533 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2534 StructReturnType SR = callIsStructReturn(Outs);
2535 bool IsSibcall = false;
2537 if (MF.getTarget().Options.DisableTailCalls)
2541 // Check if it's really possible to do a tail call.
2542 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543 isVarArg, SR != NotStructReturn,
2544 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545 Outs, OutVals, Ins, DAG);
2547 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2548 report_fatal_error("failed to perform tail call elimination on a call "
2549 "site marked musttail");
2551 // Sibcalls are automatically detected tailcalls which do not require
2553 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2560 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2561 "Var args not supported with calling convention fastcc, ghc or hipe");
2563 // Analyze operands of the call, assigning locations to each operand.
2564 SmallVector<CCValAssign, 16> ArgLocs;
2565 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2566 ArgLocs, *DAG.getContext());
2568 // Allocate shadow area for Win64
2570 CCInfo.AllocateStack(32, 8);
2572 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2574 // Get a count of how many bytes are to be pushed on the stack.
2575 unsigned NumBytes = CCInfo.getNextStackOffset();
2577 // This is a sibcall. The memory operands are available in caller's
2578 // own caller's stack.
2580 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2581 IsTailCallConvention(CallConv))
2582 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2585 if (isTailCall && !IsSibcall) {
2586 // Lower arguments at fp - stackoffset + fpdiff.
2587 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2588 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2590 FPDiff = NumBytesCallerPushed - NumBytes;
2592 // Set the delta of movement of the returnaddr stackslot.
2593 // But only set if delta is greater than previous delta.
2594 if (FPDiff < X86Info->getTCReturnAddrDelta())
2595 X86Info->setTCReturnAddrDelta(FPDiff);
2598 unsigned NumBytesToPush = NumBytes;
2599 unsigned NumBytesToPop = NumBytes;
2601 // If we have an inalloca argument, all stack space has already been allocated
2602 // for us and be right at the top of the stack. We don't support multiple
2603 // arguments passed in memory when using inalloca.
2604 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2606 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2607 "an inalloca argument must be the only memory argument");
2611 Chain = DAG.getCALLSEQ_START(
2612 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2614 SDValue RetAddrFrIdx;
2615 // Load return address for tail calls.
2616 if (isTailCall && FPDiff)
2617 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2618 Is64Bit, FPDiff, dl);
2620 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2621 SmallVector<SDValue, 8> MemOpChains;
2624 // Walk the register/memloc assignments, inserting copies/loads. In the case
2625 // of tail call optimization arguments are handle later.
2626 const X86RegisterInfo *RegInfo =
2627 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2628 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629 // Skip inalloca arguments, they have already been written.
2630 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2631 if (Flags.isInAlloca())
2634 CCValAssign &VA = ArgLocs[i];
2635 EVT RegVT = VA.getLocVT();
2636 SDValue Arg = OutVals[i];
2637 bool isByVal = Flags.isByVal();
2639 // Promote the value if needed.
2640 switch (VA.getLocInfo()) {
2641 default: llvm_unreachable("Unknown loc info!");
2642 case CCValAssign::Full: break;
2643 case CCValAssign::SExt:
2644 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2646 case CCValAssign::ZExt:
2647 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2649 case CCValAssign::AExt:
2650 if (RegVT.is128BitVector()) {
2651 // Special case: passing MMX values in XMM registers.
2652 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2653 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2654 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2656 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2658 case CCValAssign::BCvt:
2659 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2661 case CCValAssign::Indirect: {
2662 // Store the argument.
2663 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2664 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2665 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2666 MachinePointerInfo::getFixedStack(FI),
2673 if (VA.isRegLoc()) {
2674 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2675 if (isVarArg && IsWin64) {
2676 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2677 // shadow reg if callee is a varargs function.
2678 unsigned ShadowReg = 0;
2679 switch (VA.getLocReg()) {
2680 case X86::XMM0: ShadowReg = X86::RCX; break;
2681 case X86::XMM1: ShadowReg = X86::RDX; break;
2682 case X86::XMM2: ShadowReg = X86::R8; break;
2683 case X86::XMM3: ShadowReg = X86::R9; break;
2686 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2688 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2689 assert(VA.isMemLoc());
2690 if (!StackPtr.getNode())
2691 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2693 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2694 dl, DAG, VA, Flags));
2698 if (!MemOpChains.empty())
2699 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2701 if (Subtarget->isPICStyleGOT()) {
2702 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2705 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2706 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2708 // If we are tail calling and generating PIC/GOT style code load the
2709 // address of the callee into ECX. The value in ecx is used as target of
2710 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2711 // for tail calls on PIC/GOT architectures. Normally we would just put the
2712 // address of GOT into ebx and then call target@PLT. But for tail calls
2713 // ebx would be restored (since ebx is callee saved) before jumping to the
2716 // Note: The actual moving to ECX is done further down.
2717 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2718 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2719 !G->getGlobal()->hasProtectedVisibility())
2720 Callee = LowerGlobalAddress(Callee, DAG);
2721 else if (isa<ExternalSymbolSDNode>(Callee))
2722 Callee = LowerExternalSymbol(Callee, DAG);
2726 if (Is64Bit && isVarArg && !IsWin64) {
2727 // From AMD64 ABI document:
2728 // For calls that may call functions that use varargs or stdargs
2729 // (prototype-less calls or calls to functions containing ellipsis (...) in
2730 // the declaration) %al is used as hidden argument to specify the number
2731 // of SSE registers used. The contents of %al do not need to match exactly
2732 // the number of registers, but must be an ubound on the number of SSE
2733 // registers used and is in the range 0 - 8 inclusive.
2735 // Count the number of XMM registers allocated.
2736 static const MCPhysReg XMMArgRegs[] = {
2737 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2738 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2740 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2741 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2742 && "SSE registers cannot be used when SSE is disabled");
2744 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2745 DAG.getConstant(NumXMMRegs, MVT::i8)));
2748 // For tail calls lower the arguments to the 'real' stack slot.
2750 // Force all the incoming stack arguments to be loaded from the stack
2751 // before any new outgoing arguments are stored to the stack, because the
2752 // outgoing stack slots may alias the incoming argument stack slots, and
2753 // the alias isn't otherwise explicit. This is slightly more conservative
2754 // than necessary, because it means that each store effectively depends
2755 // on every argument instead of just those arguments it would clobber.
2756 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2758 SmallVector<SDValue, 8> MemOpChains2;
2761 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2762 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2763 CCValAssign &VA = ArgLocs[i];
2766 assert(VA.isMemLoc());
2767 SDValue Arg = OutVals[i];
2768 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2769 // Create frame index.
2770 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2771 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2772 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2773 FIN = DAG.getFrameIndex(FI, getPointerTy());
2775 if (Flags.isByVal()) {
2776 // Copy relative to framepointer.
2777 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2778 if (!StackPtr.getNode())
2779 StackPtr = DAG.getCopyFromReg(Chain, dl,
2780 RegInfo->getStackRegister(),
2782 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2784 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2788 // Store relative to framepointer.
2789 MemOpChains2.push_back(
2790 DAG.getStore(ArgChain, dl, Arg, FIN,
2791 MachinePointerInfo::getFixedStack(FI),
2797 if (!MemOpChains2.empty())
2798 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2800 // Store the return address to the appropriate stack slot.
2801 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2802 getPointerTy(), RegInfo->getSlotSize(),
2806 // Build a sequence of copy-to-reg nodes chained together with token chain
2807 // and flag operands which copy the outgoing args into registers.
2809 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2810 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2811 RegsToPass[i].second, InFlag);
2812 InFlag = Chain.getValue(1);
2815 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2816 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2817 // In the 64-bit large code model, we have to make all calls
2818 // through a register, since the call instruction's 32-bit
2819 // pc-relative offset may not be large enough to hold the whole
2821 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2822 // If the callee is a GlobalAddress node (quite common, every direct call
2823 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2826 // We should use extra load for direct calls to dllimported functions in
2828 const GlobalValue *GV = G->getGlobal();
2829 if (!GV->hasDLLImportStorageClass()) {
2830 unsigned char OpFlags = 0;
2831 bool ExtraLoad = false;
2832 unsigned WrapperKind = ISD::DELETED_NODE;
2834 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2835 // external symbols most go through the PLT in PIC mode. If the symbol
2836 // has hidden or protected visibility, or if it is static or local, then
2837 // we don't need to use the PLT - we can directly call it.
2838 if (Subtarget->isTargetELF() &&
2839 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2840 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2841 OpFlags = X86II::MO_PLT;
2842 } else if (Subtarget->isPICStyleStubAny() &&
2843 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2844 (!Subtarget->getTargetTriple().isMacOSX() ||
2845 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2846 // PC-relative references to external symbols should go through $stub,
2847 // unless we're building with the leopard linker or later, which
2848 // automatically synthesizes these stubs.
2849 OpFlags = X86II::MO_DARWIN_STUB;
2850 } else if (Subtarget->isPICStyleRIPRel() &&
2851 isa<Function>(GV) &&
2852 cast<Function>(GV)->getAttributes().
2853 hasAttribute(AttributeSet::FunctionIndex,
2854 Attribute::NonLazyBind)) {
2855 // If the function is marked as non-lazy, generate an indirect call
2856 // which loads from the GOT directly. This avoids runtime overhead
2857 // at the cost of eager binding (and one extra byte of encoding).
2858 OpFlags = X86II::MO_GOTPCREL;
2859 WrapperKind = X86ISD::WrapperRIP;
2863 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2864 G->getOffset(), OpFlags);
2866 // Add a wrapper if needed.
2867 if (WrapperKind != ISD::DELETED_NODE)
2868 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2869 // Add extra indirection if needed.
2871 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2872 MachinePointerInfo::getGOT(),
2873 false, false, false, 0);
2875 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2876 unsigned char OpFlags = 0;
2878 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2879 // external symbols should go through the PLT.
2880 if (Subtarget->isTargetELF() &&
2881 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2882 OpFlags = X86II::MO_PLT;
2883 } else if (Subtarget->isPICStyleStubAny() &&
2884 (!Subtarget->getTargetTriple().isMacOSX() ||
2885 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2886 // PC-relative references to external symbols should go through $stub,
2887 // unless we're building with the leopard linker or later, which
2888 // automatically synthesizes these stubs.
2889 OpFlags = X86II::MO_DARWIN_STUB;
2892 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2896 // Returns a chain & a flag for retval copy to use.
2897 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2898 SmallVector<SDValue, 8> Ops;
2900 if (!IsSibcall && isTailCall) {
2901 Chain = DAG.getCALLSEQ_END(Chain,
2902 DAG.getIntPtrConstant(NumBytesToPop, true),
2903 DAG.getIntPtrConstant(0, true), InFlag, dl);
2904 InFlag = Chain.getValue(1);
2907 Ops.push_back(Chain);
2908 Ops.push_back(Callee);
2911 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2913 // Add argument registers to the end of the list so that they are known live
2915 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2916 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2917 RegsToPass[i].second.getValueType()));
2919 // Add a register mask operand representing the call-preserved registers.
2920 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2921 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2922 assert(Mask && "Missing call preserved mask for calling convention");
2923 Ops.push_back(DAG.getRegisterMask(Mask));
2925 if (InFlag.getNode())
2926 Ops.push_back(InFlag);
2930 //// If this is the first return lowered for this function, add the regs
2931 //// to the liveout set for the function.
2932 // This isn't right, although it's probably harmless on x86; liveouts
2933 // should be computed from returns not tail calls. Consider a void
2934 // function making a tail call to a function returning int.
2935 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2938 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2939 InFlag = Chain.getValue(1);
2941 // Create the CALLSEQ_END node.
2942 unsigned NumBytesForCalleeToPop;
2943 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2944 getTargetMachine().Options.GuaranteedTailCallOpt))
2945 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2946 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2947 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2948 SR == StackStructReturn)
2949 // If this is a call to a struct-return function, the callee
2950 // pops the hidden struct pointer, so we have to push it back.
2951 // This is common for Darwin/X86, Linux & Mingw32 targets.
2952 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2953 NumBytesForCalleeToPop = 4;
2955 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2957 // Returns a flag for retval copy to use.
2959 Chain = DAG.getCALLSEQ_END(Chain,
2960 DAG.getIntPtrConstant(NumBytesToPop, true),
2961 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2964 InFlag = Chain.getValue(1);
2967 // Handle result values, copying them out of physregs into vregs that we
2969 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2970 Ins, dl, DAG, InVals);
2973 //===----------------------------------------------------------------------===//
2974 // Fast Calling Convention (tail call) implementation
2975 //===----------------------------------------------------------------------===//
2977 // Like std call, callee cleans arguments, convention except that ECX is
2978 // reserved for storing the tail called function address. Only 2 registers are
2979 // free for argument passing (inreg). Tail call optimization is performed
2981 // * tailcallopt is enabled
2982 // * caller/callee are fastcc
2983 // On X86_64 architecture with GOT-style position independent code only local
2984 // (within module) calls are supported at the moment.
2985 // To keep the stack aligned according to platform abi the function
2986 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2987 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2988 // If a tail called function callee has more arguments than the caller the
2989 // caller needs to make sure that there is room to move the RETADDR to. This is
2990 // achieved by reserving an area the size of the argument delta right after the
2991 // original REtADDR, but before the saved framepointer or the spilled registers
2992 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3004 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3005 /// for a 16 byte align requirement.
3007 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3008 SelectionDAG& DAG) const {
3009 MachineFunction &MF = DAG.getMachineFunction();
3010 const TargetMachine &TM = MF.getTarget();
3011 const X86RegisterInfo *RegInfo =
3012 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3013 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3014 unsigned StackAlignment = TFI.getStackAlignment();
3015 uint64_t AlignMask = StackAlignment - 1;
3016 int64_t Offset = StackSize;
3017 unsigned SlotSize = RegInfo->getSlotSize();
3018 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3019 // Number smaller than 12 so just add the difference.
3020 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3022 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3023 Offset = ((~AlignMask) & Offset) + StackAlignment +
3024 (StackAlignment-SlotSize);
3029 /// MatchingStackOffset - Return true if the given stack call argument is
3030 /// already available in the same position (relatively) of the caller's
3031 /// incoming argument stack.
3033 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3034 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3035 const X86InstrInfo *TII) {
3036 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3038 if (Arg.getOpcode() == ISD::CopyFromReg) {
3039 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3040 if (!TargetRegisterInfo::isVirtualRegister(VR))
3042 MachineInstr *Def = MRI->getVRegDef(VR);
3045 if (!Flags.isByVal()) {
3046 if (!TII->isLoadFromStackSlot(Def, FI))
3049 unsigned Opcode = Def->getOpcode();
3050 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3051 Def->getOperand(1).isFI()) {
3052 FI = Def->getOperand(1).getIndex();
3053 Bytes = Flags.getByValSize();
3057 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3058 if (Flags.isByVal())
3059 // ByVal argument is passed in as a pointer but it's now being
3060 // dereferenced. e.g.
3061 // define @foo(%struct.X* %A) {
3062 // tail call @bar(%struct.X* byval %A)
3065 SDValue Ptr = Ld->getBasePtr();
3066 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3069 FI = FINode->getIndex();
3070 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3071 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3072 FI = FINode->getIndex();
3073 Bytes = Flags.getByValSize();
3077 assert(FI != INT_MAX);
3078 if (!MFI->isFixedObjectIndex(FI))
3080 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3083 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3084 /// for tail call optimization. Targets which want to do tail call
3085 /// optimization should implement this function.
3087 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3088 CallingConv::ID CalleeCC,
3090 bool isCalleeStructRet,
3091 bool isCallerStructRet,
3093 const SmallVectorImpl<ISD::OutputArg> &Outs,
3094 const SmallVectorImpl<SDValue> &OutVals,
3095 const SmallVectorImpl<ISD::InputArg> &Ins,
3096 SelectionDAG &DAG) const {
3097 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3100 // If -tailcallopt is specified, make fastcc functions tail-callable.
3101 const MachineFunction &MF = DAG.getMachineFunction();
3102 const Function *CallerF = MF.getFunction();
3104 // If the function return type is x86_fp80 and the callee return type is not,
3105 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3106 // perform a tailcall optimization here.
3107 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3110 CallingConv::ID CallerCC = CallerF->getCallingConv();
3111 bool CCMatch = CallerCC == CalleeCC;
3112 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3113 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3115 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3116 if (IsTailCallConvention(CalleeCC) && CCMatch)
3121 // Look for obvious safe cases to perform tail call optimization that do not
3122 // require ABI changes. This is what gcc calls sibcall.
3124 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3125 // emit a special epilogue.
3126 const X86RegisterInfo *RegInfo =
3127 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3128 if (RegInfo->needsStackRealignment(MF))
3131 // Also avoid sibcall optimization if either caller or callee uses struct
3132 // return semantics.
3133 if (isCalleeStructRet || isCallerStructRet)
3136 // An stdcall/thiscall caller is expected to clean up its arguments; the
3137 // callee isn't going to do that.
3138 // FIXME: this is more restrictive than needed. We could produce a tailcall
3139 // when the stack adjustment matches. For example, with a thiscall that takes
3140 // only one argument.
3141 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3142 CallerCC == CallingConv::X86_ThisCall))
3145 // Do not sibcall optimize vararg calls unless all arguments are passed via
3147 if (isVarArg && !Outs.empty()) {
3149 // Optimizing for varargs on Win64 is unlikely to be safe without
3150 // additional testing.
3151 if (IsCalleeWin64 || IsCallerWin64)
3154 SmallVector<CCValAssign, 16> ArgLocs;
3155 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3156 getTargetMachine(), ArgLocs, *DAG.getContext());
3158 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3159 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3160 if (!ArgLocs[i].isRegLoc())
3164 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3165 // stack. Therefore, if it's not used by the call it is not safe to optimize
3166 // this into a sibcall.
3167 bool Unused = false;
3168 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3175 SmallVector<CCValAssign, 16> RVLocs;
3176 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3177 getTargetMachine(), RVLocs, *DAG.getContext());
3178 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3179 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3180 CCValAssign &VA = RVLocs[i];
3181 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3186 // If the calling conventions do not match, then we'd better make sure the
3187 // results are returned in the same way as what the caller expects.
3189 SmallVector<CCValAssign, 16> RVLocs1;
3190 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3191 getTargetMachine(), RVLocs1, *DAG.getContext());
3192 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3194 SmallVector<CCValAssign, 16> RVLocs2;
3195 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3196 getTargetMachine(), RVLocs2, *DAG.getContext());
3197 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3199 if (RVLocs1.size() != RVLocs2.size())
3201 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3202 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3204 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3206 if (RVLocs1[i].isRegLoc()) {
3207 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3210 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3216 // If the callee takes no arguments then go on to check the results of the
3218 if (!Outs.empty()) {
3219 // Check if stack adjustment is needed. For now, do not do this if any
3220 // argument is passed on the stack.
3221 SmallVector<CCValAssign, 16> ArgLocs;
3222 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3223 getTargetMachine(), ArgLocs, *DAG.getContext());
3225 // Allocate shadow area for Win64
3227 CCInfo.AllocateStack(32, 8);
3229 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3230 if (CCInfo.getNextStackOffset()) {
3231 MachineFunction &MF = DAG.getMachineFunction();
3232 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3235 // Check if the arguments are already laid out in the right way as
3236 // the caller's fixed stack objects.
3237 MachineFrameInfo *MFI = MF.getFrameInfo();
3238 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3239 const X86InstrInfo *TII =
3240 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3241 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3242 CCValAssign &VA = ArgLocs[i];
3243 SDValue Arg = OutVals[i];
3244 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3245 if (VA.getLocInfo() == CCValAssign::Indirect)
3247 if (!VA.isRegLoc()) {
3248 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3255 // If the tailcall address may be in a register, then make sure it's
3256 // possible to register allocate for it. In 32-bit, the call address can
3257 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3258 // callee-saved registers are restored. These happen to be the same
3259 // registers used to pass 'inreg' arguments so watch out for those.
3260 if (!Subtarget->is64Bit() &&
3261 ((!isa<GlobalAddressSDNode>(Callee) &&
3262 !isa<ExternalSymbolSDNode>(Callee)) ||
3263 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3264 unsigned NumInRegs = 0;
3265 // In PIC we need an extra register to formulate the address computation
3267 unsigned MaxInRegs =
3268 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3270 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3271 CCValAssign &VA = ArgLocs[i];
3274 unsigned Reg = VA.getLocReg();
3277 case X86::EAX: case X86::EDX: case X86::ECX:
3278 if (++NumInRegs == MaxInRegs)
3290 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3291 const TargetLibraryInfo *libInfo) const {
3292 return X86::createFastISel(funcInfo, libInfo);
3295 //===----------------------------------------------------------------------===//
3296 // Other Lowering Hooks
3297 //===----------------------------------------------------------------------===//
3299 static bool MayFoldLoad(SDValue Op) {
3300 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3303 static bool MayFoldIntoStore(SDValue Op) {
3304 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3307 static bool isTargetShuffle(unsigned Opcode) {
3309 default: return false;
3310 case X86ISD::PSHUFD:
3311 case X86ISD::PSHUFHW:
3312 case X86ISD::PSHUFLW:
3314 case X86ISD::PALIGNR:
3315 case X86ISD::MOVLHPS:
3316 case X86ISD::MOVLHPD:
3317 case X86ISD::MOVHLPS:
3318 case X86ISD::MOVLPS:
3319 case X86ISD::MOVLPD:
3320 case X86ISD::MOVSHDUP:
3321 case X86ISD::MOVSLDUP:
3322 case X86ISD::MOVDDUP:
3325 case X86ISD::UNPCKL:
3326 case X86ISD::UNPCKH:
3327 case X86ISD::VPERMILP:
3328 case X86ISD::VPERM2X128:
3329 case X86ISD::VPERMI:
3334 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3335 SDValue V1, SelectionDAG &DAG) {
3337 default: llvm_unreachable("Unknown x86 shuffle node");
3338 case X86ISD::MOVSHDUP:
3339 case X86ISD::MOVSLDUP:
3340 case X86ISD::MOVDDUP:
3341 return DAG.getNode(Opc, dl, VT, V1);
3345 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3346 SDValue V1, unsigned TargetMask,
3347 SelectionDAG &DAG) {
3349 default: llvm_unreachable("Unknown x86 shuffle node");
3350 case X86ISD::PSHUFD:
3351 case X86ISD::PSHUFHW:
3352 case X86ISD::PSHUFLW:
3353 case X86ISD::VPERMILP:
3354 case X86ISD::VPERMI:
3355 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3359 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3360 SDValue V1, SDValue V2, unsigned TargetMask,
3361 SelectionDAG &DAG) {
3363 default: llvm_unreachable("Unknown x86 shuffle node");
3364 case X86ISD::PALIGNR:
3366 case X86ISD::VPERM2X128:
3367 return DAG.getNode(Opc, dl, VT, V1, V2,
3368 DAG.getConstant(TargetMask, MVT::i8));
3372 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3373 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3375 default: llvm_unreachable("Unknown x86 shuffle node");
3376 case X86ISD::MOVLHPS:
3377 case X86ISD::MOVLHPD:
3378 case X86ISD::MOVHLPS:
3379 case X86ISD::MOVLPS:
3380 case X86ISD::MOVLPD:
3383 case X86ISD::UNPCKL:
3384 case X86ISD::UNPCKH:
3385 return DAG.getNode(Opc, dl, VT, V1, V2);
3389 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3390 MachineFunction &MF = DAG.getMachineFunction();
3391 const X86RegisterInfo *RegInfo =
3392 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3393 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3394 int ReturnAddrIndex = FuncInfo->getRAIndex();
3396 if (ReturnAddrIndex == 0) {
3397 // Set up a frame object for the return address.
3398 unsigned SlotSize = RegInfo->getSlotSize();
3399 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3402 FuncInfo->setRAIndex(ReturnAddrIndex);
3405 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3408 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3409 bool hasSymbolicDisplacement) {
3410 // Offset should fit into 32 bit immediate field.
3411 if (!isInt<32>(Offset))
3414 // If we don't have a symbolic displacement - we don't have any extra
3416 if (!hasSymbolicDisplacement)
3419 // FIXME: Some tweaks might be needed for medium code model.
3420 if (M != CodeModel::Small && M != CodeModel::Kernel)
3423 // For small code model we assume that latest object is 16MB before end of 31
3424 // bits boundary. We may also accept pretty large negative constants knowing
3425 // that all objects are in the positive half of address space.
3426 if (M == CodeModel::Small && Offset < 16*1024*1024)
3429 // For kernel code model we know that all object resist in the negative half
3430 // of 32bits address space. We may not accept negative offsets, since they may
3431 // be just off and we may accept pretty large positive ones.
3432 if (M == CodeModel::Kernel && Offset > 0)
3438 /// isCalleePop - Determines whether the callee is required to pop its
3439 /// own arguments. Callee pop is necessary to support tail calls.
3440 bool X86::isCalleePop(CallingConv::ID CallingConv,
3441 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3445 switch (CallingConv) {
3448 case CallingConv::X86_StdCall:
3450 case CallingConv::X86_FastCall:
3452 case CallingConv::X86_ThisCall:
3454 case CallingConv::Fast:
3456 case CallingConv::GHC:
3458 case CallingConv::HiPE:
3463 /// \brief Return true if the condition is an unsigned comparison operation.
3464 static bool isX86CCUnsigned(unsigned X86CC) {
3466 default: llvm_unreachable("Invalid integer condition!");
3467 case X86::COND_E: return true;
3468 case X86::COND_G: return false;
3469 case X86::COND_GE: return false;
3470 case X86::COND_L: return false;
3471 case X86::COND_LE: return false;
3472 case X86::COND_NE: return true;
3473 case X86::COND_B: return true;
3474 case X86::COND_A: return true;
3475 case X86::COND_BE: return true;
3476 case X86::COND_AE: return true;
3478 llvm_unreachable("covered switch fell through?!");
3481 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3482 /// specific condition code, returning the condition code and the LHS/RHS of the
3483 /// comparison to make.
3484 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3485 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3487 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3488 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3489 // X > -1 -> X == 0, jump !sign.
3490 RHS = DAG.getConstant(0, RHS.getValueType());
3491 return X86::COND_NS;
3493 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3494 // X < 0 -> X == 0, jump on sign.
3497 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3499 RHS = DAG.getConstant(0, RHS.getValueType());
3500 return X86::COND_LE;
3504 switch (SetCCOpcode) {
3505 default: llvm_unreachable("Invalid integer condition!");
3506 case ISD::SETEQ: return X86::COND_E;
3507 case ISD::SETGT: return X86::COND_G;
3508 case ISD::SETGE: return X86::COND_GE;
3509 case ISD::SETLT: return X86::COND_L;
3510 case ISD::SETLE: return X86::COND_LE;
3511 case ISD::SETNE: return X86::COND_NE;
3512 case ISD::SETULT: return X86::COND_B;
3513 case ISD::SETUGT: return X86::COND_A;
3514 case ISD::SETULE: return X86::COND_BE;
3515 case ISD::SETUGE: return X86::COND_AE;
3519 // First determine if it is required or is profitable to flip the operands.
3521 // If LHS is a foldable load, but RHS is not, flip the condition.
3522 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3523 !ISD::isNON_EXTLoad(RHS.getNode())) {
3524 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3525 std::swap(LHS, RHS);
3528 switch (SetCCOpcode) {
3534 std::swap(LHS, RHS);
3538 // On a floating point condition, the flags are set as follows:
3540 // 0 | 0 | 0 | X > Y
3541 // 0 | 0 | 1 | X < Y
3542 // 1 | 0 | 0 | X == Y
3543 // 1 | 1 | 1 | unordered
3544 switch (SetCCOpcode) {
3545 default: llvm_unreachable("Condcode should be pre-legalized away");
3547 case ISD::SETEQ: return X86::COND_E;
3548 case ISD::SETOLT: // flipped
3550 case ISD::SETGT: return X86::COND_A;
3551 case ISD::SETOLE: // flipped
3553 case ISD::SETGE: return X86::COND_AE;
3554 case ISD::SETUGT: // flipped
3556 case ISD::SETLT: return X86::COND_B;
3557 case ISD::SETUGE: // flipped
3559 case ISD::SETLE: return X86::COND_BE;
3561 case ISD::SETNE: return X86::COND_NE;
3562 case ISD::SETUO: return X86::COND_P;
3563 case ISD::SETO: return X86::COND_NP;
3565 case ISD::SETUNE: return X86::COND_INVALID;
3569 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3570 /// code. Current x86 isa includes the following FP cmov instructions:
3571 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3572 static bool hasFPCMov(unsigned X86CC) {
3588 /// isFPImmLegal - Returns true if the target can instruction select the
3589 /// specified FP immediate natively. If false, the legalizer will
3590 /// materialize the FP immediate as a load from a constant pool.
3591 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3592 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3593 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3599 /// \brief Returns true if it is beneficial to convert a load of a constant
3600 /// to just the constant itself.
3601 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3603 assert(Ty->isIntegerTy());
3605 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3606 if (BitSize == 0 || BitSize > 64)
3611 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3612 /// the specified range (L, H].
3613 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3614 return (Val < 0) || (Val >= Low && Val < Hi);
3617 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3618 /// specified value.
3619 static bool isUndefOrEqual(int Val, int CmpVal) {
3620 return (Val < 0 || Val == CmpVal);
3623 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3624 /// from position Pos and ending in Pos+Size, falls within the specified
3625 /// sequential range (L, L+Pos]. or is undef.
3626 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3627 unsigned Pos, unsigned Size, int Low) {
3628 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3629 if (!isUndefOrEqual(Mask[i], Low))
3634 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3635 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3636 /// the second operand.
3637 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3638 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3639 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3640 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3641 return (Mask[0] < 2 && Mask[1] < 2);
3645 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3646 /// is suitable for input to PSHUFHW.
3647 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3648 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3651 // Lower quadword copied in order or undef.
3652 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3655 // Upper quadword shuffled.
3656 for (unsigned i = 4; i != 8; ++i)
3657 if (!isUndefOrInRange(Mask[i], 4, 8))
3660 if (VT == MVT::v16i16) {
3661 // Lower quadword copied in order or undef.
3662 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3665 // Upper quadword shuffled.
3666 for (unsigned i = 12; i != 16; ++i)
3667 if (!isUndefOrInRange(Mask[i], 12, 16))
3674 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3675 /// is suitable for input to PSHUFLW.
3676 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3677 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3680 // Upper quadword copied in order.
3681 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3684 // Lower quadword shuffled.
3685 for (unsigned i = 0; i != 4; ++i)
3686 if (!isUndefOrInRange(Mask[i], 0, 4))
3689 if (VT == MVT::v16i16) {
3690 // Upper quadword copied in order.
3691 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3694 // Lower quadword shuffled.
3695 for (unsigned i = 8; i != 12; ++i)
3696 if (!isUndefOrInRange(Mask[i], 8, 12))
3703 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3704 /// is suitable for input to PALIGNR.
3705 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3706 const X86Subtarget *Subtarget) {
3707 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3708 (VT.is256BitVector() && !Subtarget->hasInt256()))
3711 unsigned NumElts = VT.getVectorNumElements();
3712 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3713 unsigned NumLaneElts = NumElts/NumLanes;
3715 // Do not handle 64-bit element shuffles with palignr.
3716 if (NumLaneElts == 2)
3719 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3721 for (i = 0; i != NumLaneElts; ++i) {
3726 // Lane is all undef, go to next lane
3727 if (i == NumLaneElts)
3730 int Start = Mask[i+l];
3732 // Make sure its in this lane in one of the sources
3733 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3734 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3737 // If not lane 0, then we must match lane 0
3738 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3741 // Correct second source to be contiguous with first source
3742 if (Start >= (int)NumElts)
3743 Start -= NumElts - NumLaneElts;
3745 // Make sure we're shifting in the right direction.
3746 if (Start <= (int)(i+l))
3751 // Check the rest of the elements to see if they are consecutive.
3752 for (++i; i != NumLaneElts; ++i) {
3753 int Idx = Mask[i+l];
3755 // Make sure its in this lane
3756 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3757 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3760 // If not lane 0, then we must match lane 0
3761 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3764 if (Idx >= (int)NumElts)
3765 Idx -= NumElts - NumLaneElts;
3767 if (!isUndefOrEqual(Idx, Start+i))
3776 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3777 /// the two vector operands have swapped position.
3778 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3779 unsigned NumElems) {
3780 for (unsigned i = 0; i != NumElems; ++i) {
3784 else if (idx < (int)NumElems)
3785 Mask[i] = idx + NumElems;
3787 Mask[i] = idx - NumElems;
3791 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3792 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3793 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3794 /// reverse of what x86 shuffles want.
3795 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3797 unsigned NumElems = VT.getVectorNumElements();
3798 unsigned NumLanes = VT.getSizeInBits()/128;
3799 unsigned NumLaneElems = NumElems/NumLanes;
3801 if (NumLaneElems != 2 && NumLaneElems != 4)
3804 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3805 bool symetricMaskRequired =
3806 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3808 // VSHUFPSY divides the resulting vector into 4 chunks.
3809 // The sources are also splitted into 4 chunks, and each destination
3810 // chunk must come from a different source chunk.
3812 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3813 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3815 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3816 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3818 // VSHUFPDY divides the resulting vector into 4 chunks.
3819 // The sources are also splitted into 4 chunks, and each destination
3820 // chunk must come from a different source chunk.
3822 // SRC1 => X3 X2 X1 X0
3823 // SRC2 => Y3 Y2 Y1 Y0
3825 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3827 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3828 unsigned HalfLaneElems = NumLaneElems/2;
3829 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3830 for (unsigned i = 0; i != NumLaneElems; ++i) {
3831 int Idx = Mask[i+l];
3832 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3833 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3835 // For VSHUFPSY, the mask of the second half must be the same as the
3836 // first but with the appropriate offsets. This works in the same way as
3837 // VPERMILPS works with masks.
3838 if (!symetricMaskRequired || Idx < 0)
3840 if (MaskVal[i] < 0) {
3841 MaskVal[i] = Idx - l;
3844 if ((signed)(Idx - l) != MaskVal[i])
3852 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3853 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3854 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3855 if (!VT.is128BitVector())
3858 unsigned NumElems = VT.getVectorNumElements();
3863 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3864 return isUndefOrEqual(Mask[0], 6) &&
3865 isUndefOrEqual(Mask[1], 7) &&
3866 isUndefOrEqual(Mask[2], 2) &&
3867 isUndefOrEqual(Mask[3], 3);
3870 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3871 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3873 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3874 if (!VT.is128BitVector())
3877 unsigned NumElems = VT.getVectorNumElements();
3882 return isUndefOrEqual(Mask[0], 2) &&
3883 isUndefOrEqual(Mask[1], 3) &&
3884 isUndefOrEqual(Mask[2], 2) &&
3885 isUndefOrEqual(Mask[3], 3);
3888 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3889 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3890 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3891 if (!VT.is128BitVector())
3894 unsigned NumElems = VT.getVectorNumElements();
3896 if (NumElems != 2 && NumElems != 4)
3899 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3900 if (!isUndefOrEqual(Mask[i], i + NumElems))
3903 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3904 if (!isUndefOrEqual(Mask[i], i))
3910 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3912 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3913 if (!VT.is128BitVector())
3916 unsigned NumElems = VT.getVectorNumElements();
3918 if (NumElems != 2 && NumElems != 4)
3921 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3922 if (!isUndefOrEqual(Mask[i], i))
3925 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3926 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3932 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3933 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3934 /// i. e: If all but one element come from the same vector.
3935 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3936 // TODO: Deal with AVX's VINSERTPS
3937 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3940 unsigned CorrectPosV1 = 0;
3941 unsigned CorrectPosV2 = 0;
3942 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3945 else if (Mask[i] == i + 4)
3948 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3949 // We have 3 elements from one vector, and one from another.
3956 // Some special combinations that can be optimized.
3959 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3960 SelectionDAG &DAG) {
3961 MVT VT = SVOp->getSimpleValueType(0);
3964 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3967 ArrayRef<int> Mask = SVOp->getMask();
3969 // These are the special masks that may be optimized.
3970 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3971 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3972 bool MatchEvenMask = true;
3973 bool MatchOddMask = true;
3974 for (int i=0; i<8; ++i) {
3975 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3976 MatchEvenMask = false;
3977 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3978 MatchOddMask = false;
3981 if (!MatchEvenMask && !MatchOddMask)
3984 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3986 SDValue Op0 = SVOp->getOperand(0);
3987 SDValue Op1 = SVOp->getOperand(1);
3989 if (MatchEvenMask) {
3990 // Shift the second operand right to 32 bits.
3991 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3992 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3994 // Shift the first operand left to 32 bits.
3995 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3996 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3998 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3999 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4002 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4003 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4004 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4005 bool HasInt256, bool V2IsSplat = false) {
4007 assert(VT.getSizeInBits() >= 128 &&
4008 "Unsupported vector type for unpckl");
4010 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4012 unsigned NumOf256BitLanes;
4013 unsigned NumElts = VT.getVectorNumElements();
4014 if (VT.is256BitVector()) {
4015 if (NumElts != 4 && NumElts != 8 &&
4016 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4019 NumOf256BitLanes = 1;
4020 } else if (VT.is512BitVector()) {
4021 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4022 "Unsupported vector type for unpckh");
4024 NumOf256BitLanes = 2;
4027 NumOf256BitLanes = 1;
4030 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4031 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4033 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4034 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4035 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4036 int BitI = Mask[l256*NumEltsInStride+l+i];
4037 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4038 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4040 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4042 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4050 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4051 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4052 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4053 bool HasInt256, bool V2IsSplat = false) {
4054 assert(VT.getSizeInBits() >= 128 &&
4055 "Unsupported vector type for unpckh");
4057 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4059 unsigned NumOf256BitLanes;
4060 unsigned NumElts = VT.getVectorNumElements();
4061 if (VT.is256BitVector()) {
4062 if (NumElts != 4 && NumElts != 8 &&
4063 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4066 NumOf256BitLanes = 1;
4067 } else if (VT.is512BitVector()) {
4068 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4069 "Unsupported vector type for unpckh");
4071 NumOf256BitLanes = 2;
4074 NumOf256BitLanes = 1;
4077 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4078 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4080 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4081 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4082 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4083 int BitI = Mask[l256*NumEltsInStride+l+i];
4084 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4085 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4087 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4089 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4097 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4098 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4100 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4101 unsigned NumElts = VT.getVectorNumElements();
4102 bool Is256BitVec = VT.is256BitVector();
4104 if (VT.is512BitVector())
4106 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4107 "Unsupported vector type for unpckh");
4109 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4110 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4113 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4114 // FIXME: Need a better way to get rid of this, there's no latency difference
4115 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4116 // the former later. We should also remove the "_undef" special mask.
4117 if (NumElts == 4 && Is256BitVec)
4120 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4121 // independently on 128-bit lanes.
4122 unsigned NumLanes = VT.getSizeInBits()/128;
4123 unsigned NumLaneElts = NumElts/NumLanes;
4125 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4126 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4127 int BitI = Mask[l+i];
4128 int BitI1 = Mask[l+i+1];
4130 if (!isUndefOrEqual(BitI, j))
4132 if (!isUndefOrEqual(BitI1, j))
4140 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4141 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4143 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4144 unsigned NumElts = VT.getVectorNumElements();
4146 if (VT.is512BitVector())
4149 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4150 "Unsupported vector type for unpckh");
4152 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4153 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4156 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4157 // independently on 128-bit lanes.
4158 unsigned NumLanes = VT.getSizeInBits()/128;
4159 unsigned NumLaneElts = NumElts/NumLanes;
4161 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4162 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4163 int BitI = Mask[l+i];
4164 int BitI1 = Mask[l+i+1];
4165 if (!isUndefOrEqual(BitI, j))
4167 if (!isUndefOrEqual(BitI1, j))
4174 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4175 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4176 /// MOVSD, and MOVD, i.e. setting the lowest element.
4177 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4178 if (VT.getVectorElementType().getSizeInBits() < 32)
4180 if (!VT.is128BitVector())
4183 unsigned NumElts = VT.getVectorNumElements();
4185 if (!isUndefOrEqual(Mask[0], NumElts))
4188 for (unsigned i = 1; i != NumElts; ++i)
4189 if (!isUndefOrEqual(Mask[i], i))
4195 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4196 /// as permutations between 128-bit chunks or halves. As an example: this
4198 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4199 /// The first half comes from the second half of V1 and the second half from the
4200 /// the second half of V2.
4201 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4202 if (!HasFp256 || !VT.is256BitVector())
4205 // The shuffle result is divided into half A and half B. In total the two
4206 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4207 // B must come from C, D, E or F.
4208 unsigned HalfSize = VT.getVectorNumElements()/2;
4209 bool MatchA = false, MatchB = false;
4211 // Check if A comes from one of C, D, E, F.
4212 for (unsigned Half = 0; Half != 4; ++Half) {
4213 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4219 // Check if B comes from one of C, D, E, F.
4220 for (unsigned Half = 0; Half != 4; ++Half) {
4221 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4227 return MatchA && MatchB;
4230 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4231 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4232 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4233 MVT VT = SVOp->getSimpleValueType(0);
4235 unsigned HalfSize = VT.getVectorNumElements()/2;
4237 unsigned FstHalf = 0, SndHalf = 0;
4238 for (unsigned i = 0; i < HalfSize; ++i) {
4239 if (SVOp->getMaskElt(i) > 0) {
4240 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4244 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4245 if (SVOp->getMaskElt(i) > 0) {
4246 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4251 return (FstHalf | (SndHalf << 4));
4254 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4255 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4256 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4260 unsigned NumElts = VT.getVectorNumElements();
4262 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4263 for (unsigned i = 0; i != NumElts; ++i) {
4266 Imm8 |= Mask[i] << (i*2);
4271 unsigned LaneSize = 4;
4272 SmallVector<int, 4> MaskVal(LaneSize, -1);
4274 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4275 for (unsigned i = 0; i != LaneSize; ++i) {
4276 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4280 if (MaskVal[i] < 0) {
4281 MaskVal[i] = Mask[i+l] - l;
4282 Imm8 |= MaskVal[i] << (i*2);
4285 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4292 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4293 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4294 /// Note that VPERMIL mask matching is different depending whether theunderlying
4295 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4296 /// to the same elements of the low, but to the higher half of the source.
4297 /// In VPERMILPD the two lanes could be shuffled independently of each other
4298 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4299 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4300 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4301 if (VT.getSizeInBits() < 256 || EltSize < 32)
4303 bool symetricMaskRequired = (EltSize == 32);
4304 unsigned NumElts = VT.getVectorNumElements();
4306 unsigned NumLanes = VT.getSizeInBits()/128;
4307 unsigned LaneSize = NumElts/NumLanes;
4308 // 2 or 4 elements in one lane
4310 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4311 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4312 for (unsigned i = 0; i != LaneSize; ++i) {
4313 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4315 if (symetricMaskRequired) {
4316 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4317 ExpectedMaskVal[i] = Mask[i+l] - l;
4320 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4328 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4329 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4330 /// element of vector 2 and the other elements to come from vector 1 in order.
4331 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4332 bool V2IsSplat = false, bool V2IsUndef = false) {
4333 if (!VT.is128BitVector())
4336 unsigned NumOps = VT.getVectorNumElements();
4337 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4340 if (!isUndefOrEqual(Mask[0], 0))
4343 for (unsigned i = 1; i != NumOps; ++i)
4344 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4345 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4346 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4352 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4353 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4354 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4355 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4356 const X86Subtarget *Subtarget) {
4357 if (!Subtarget->hasSSE3())
4360 unsigned NumElems = VT.getVectorNumElements();
4362 if ((VT.is128BitVector() && NumElems != 4) ||
4363 (VT.is256BitVector() && NumElems != 8) ||
4364 (VT.is512BitVector() && NumElems != 16))
4367 // "i+1" is the value the indexed mask element must have
4368 for (unsigned i = 0; i != NumElems; i += 2)
4369 if (!isUndefOrEqual(Mask[i], i+1) ||
4370 !isUndefOrEqual(Mask[i+1], i+1))
4376 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4377 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4378 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4379 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4380 const X86Subtarget *Subtarget) {
4381 if (!Subtarget->hasSSE3())
4384 unsigned NumElems = VT.getVectorNumElements();
4386 if ((VT.is128BitVector() && NumElems != 4) ||
4387 (VT.is256BitVector() && NumElems != 8) ||
4388 (VT.is512BitVector() && NumElems != 16))
4391 // "i" is the value the indexed mask element must have
4392 for (unsigned i = 0; i != NumElems; i += 2)
4393 if (!isUndefOrEqual(Mask[i], i) ||
4394 !isUndefOrEqual(Mask[i+1], i))
4400 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4401 /// specifies a shuffle of elements that is suitable for input to 256-bit
4402 /// version of MOVDDUP.
4403 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4404 if (!HasFp256 || !VT.is256BitVector())
4407 unsigned NumElts = VT.getVectorNumElements();
4411 for (unsigned i = 0; i != NumElts/2; ++i)
4412 if (!isUndefOrEqual(Mask[i], 0))
4414 for (unsigned i = NumElts/2; i != NumElts; ++i)
4415 if (!isUndefOrEqual(Mask[i], NumElts/2))
4420 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4421 /// specifies a shuffle of elements that is suitable for input to 128-bit
4422 /// version of MOVDDUP.
4423 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4424 if (!VT.is128BitVector())
4427 unsigned e = VT.getVectorNumElements() / 2;
4428 for (unsigned i = 0; i != e; ++i)
4429 if (!isUndefOrEqual(Mask[i], i))
4431 for (unsigned i = 0; i != e; ++i)
4432 if (!isUndefOrEqual(Mask[e+i], i))
4437 /// isVEXTRACTIndex - Return true if the specified
4438 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4439 /// suitable for instruction that extract 128 or 256 bit vectors
4440 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4441 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4442 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4445 // The index should be aligned on a vecWidth-bit boundary.
4447 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4449 MVT VT = N->getSimpleValueType(0);
4450 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4451 bool Result = (Index * ElSize) % vecWidth == 0;
4456 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4457 /// operand specifies a subvector insert that is suitable for input to
4458 /// insertion of 128 or 256-bit subvectors
4459 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4460 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4461 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4463 // The index should be aligned on a vecWidth-bit boundary.
4465 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4467 MVT VT = N->getSimpleValueType(0);
4468 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4469 bool Result = (Index * ElSize) % vecWidth == 0;
4474 bool X86::isVINSERT128Index(SDNode *N) {
4475 return isVINSERTIndex(N, 128);
4478 bool X86::isVINSERT256Index(SDNode *N) {
4479 return isVINSERTIndex(N, 256);
4482 bool X86::isVEXTRACT128Index(SDNode *N) {
4483 return isVEXTRACTIndex(N, 128);
4486 bool X86::isVEXTRACT256Index(SDNode *N) {
4487 return isVEXTRACTIndex(N, 256);
4490 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4491 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4492 /// Handles 128-bit and 256-bit.
4493 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4494 MVT VT = N->getSimpleValueType(0);
4496 assert((VT.getSizeInBits() >= 128) &&
4497 "Unsupported vector type for PSHUF/SHUFP");
4499 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4500 // independently on 128-bit lanes.
4501 unsigned NumElts = VT.getVectorNumElements();
4502 unsigned NumLanes = VT.getSizeInBits()/128;
4503 unsigned NumLaneElts = NumElts/NumLanes;
4505 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4506 "Only supports 2, 4 or 8 elements per lane");
4508 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4510 for (unsigned i = 0; i != NumElts; ++i) {
4511 int Elt = N->getMaskElt(i);
4512 if (Elt < 0) continue;
4513 Elt &= NumLaneElts - 1;
4514 unsigned ShAmt = (i << Shift) % 8;
4515 Mask |= Elt << ShAmt;
4521 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4522 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4523 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4524 MVT VT = N->getSimpleValueType(0);
4526 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4527 "Unsupported vector type for PSHUFHW");
4529 unsigned NumElts = VT.getVectorNumElements();
4532 for (unsigned l = 0; l != NumElts; l += 8) {
4533 // 8 nodes per lane, but we only care about the last 4.
4534 for (unsigned i = 0; i < 4; ++i) {
4535 int Elt = N->getMaskElt(l+i+4);
4536 if (Elt < 0) continue;
4537 Elt &= 0x3; // only 2-bits.
4538 Mask |= Elt << (i * 2);
4545 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4546 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4547 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4548 MVT VT = N->getSimpleValueType(0);
4550 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4551 "Unsupported vector type for PSHUFHW");
4553 unsigned NumElts = VT.getVectorNumElements();
4556 for (unsigned l = 0; l != NumElts; l += 8) {
4557 // 8 nodes per lane, but we only care about the first 4.
4558 for (unsigned i = 0; i < 4; ++i) {
4559 int Elt = N->getMaskElt(l+i);
4560 if (Elt < 0) continue;
4561 Elt &= 0x3; // only 2-bits
4562 Mask |= Elt << (i * 2);
4569 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4570 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4571 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4572 MVT VT = SVOp->getSimpleValueType(0);
4573 unsigned EltSize = VT.is512BitVector() ? 1 :
4574 VT.getVectorElementType().getSizeInBits() >> 3;
4576 unsigned NumElts = VT.getVectorNumElements();
4577 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4578 unsigned NumLaneElts = NumElts/NumLanes;
4582 for (i = 0; i != NumElts; ++i) {
4583 Val = SVOp->getMaskElt(i);
4587 if (Val >= (int)NumElts)
4588 Val -= NumElts - NumLaneElts;
4590 assert(Val - i > 0 && "PALIGNR imm should be positive");
4591 return (Val - i) * EltSize;
4594 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4595 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4596 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4597 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4600 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4602 MVT VecVT = N->getOperand(0).getSimpleValueType();
4603 MVT ElVT = VecVT.getVectorElementType();
4605 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4606 return Index / NumElemsPerChunk;
4609 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4610 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4611 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4612 llvm_unreachable("Illegal insert subvector for VINSERT");
4615 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4617 MVT VecVT = N->getSimpleValueType(0);
4618 MVT ElVT = VecVT.getVectorElementType();
4620 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4621 return Index / NumElemsPerChunk;
4624 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4625 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4626 /// and VINSERTI128 instructions.
4627 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4628 return getExtractVEXTRACTImmediate(N, 128);
4631 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4632 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4633 /// and VINSERTI64x4 instructions.
4634 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4635 return getExtractVEXTRACTImmediate(N, 256);
4638 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4639 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4640 /// and VINSERTI128 instructions.
4641 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4642 return getInsertVINSERTImmediate(N, 128);
4645 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4646 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4647 /// and VINSERTI64x4 instructions.
4648 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4649 return getInsertVINSERTImmediate(N, 256);
4652 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4654 bool X86::isZeroNode(SDValue Elt) {
4655 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4656 return CN->isNullValue();
4657 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4658 return CFP->getValueAPF().isPosZero();
4662 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4663 /// their permute mask.
4664 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4665 SelectionDAG &DAG) {
4666 MVT VT = SVOp->getSimpleValueType(0);
4667 unsigned NumElems = VT.getVectorNumElements();
4668 SmallVector<int, 8> MaskVec;
4670 for (unsigned i = 0; i != NumElems; ++i) {
4671 int Idx = SVOp->getMaskElt(i);
4673 if (Idx < (int)NumElems)
4678 MaskVec.push_back(Idx);
4680 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4681 SVOp->getOperand(0), &MaskVec[0]);
4684 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4685 /// match movhlps. The lower half elements should come from upper half of
4686 /// V1 (and in order), and the upper half elements should come from the upper
4687 /// half of V2 (and in order).
4688 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4689 if (!VT.is128BitVector())
4691 if (VT.getVectorNumElements() != 4)
4693 for (unsigned i = 0, e = 2; i != e; ++i)
4694 if (!isUndefOrEqual(Mask[i], i+2))
4696 for (unsigned i = 2; i != 4; ++i)
4697 if (!isUndefOrEqual(Mask[i], i+4))
4702 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4703 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4705 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4706 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4708 N = N->getOperand(0).getNode();
4709 if (!ISD::isNON_EXTLoad(N))
4712 *LD = cast<LoadSDNode>(N);
4716 // Test whether the given value is a vector value which will be legalized
4718 static bool WillBeConstantPoolLoad(SDNode *N) {
4719 if (N->getOpcode() != ISD::BUILD_VECTOR)
4722 // Check for any non-constant elements.
4723 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4724 switch (N->getOperand(i).getNode()->getOpcode()) {
4726 case ISD::ConstantFP:
4733 // Vectors of all-zeros and all-ones are materialized with special
4734 // instructions rather than being loaded.
4735 return !ISD::isBuildVectorAllZeros(N) &&
4736 !ISD::isBuildVectorAllOnes(N);
4739 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4740 /// match movlp{s|d}. The lower half elements should come from lower half of
4741 /// V1 (and in order), and the upper half elements should come from the upper
4742 /// half of V2 (and in order). And since V1 will become the source of the
4743 /// MOVLP, it must be either a vector load or a scalar load to vector.
4744 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4745 ArrayRef<int> Mask, MVT VT) {
4746 if (!VT.is128BitVector())
4749 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4751 // Is V2 is a vector load, don't do this transformation. We will try to use
4752 // load folding shufps op.
4753 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4756 unsigned NumElems = VT.getVectorNumElements();
4758 if (NumElems != 2 && NumElems != 4)
4760 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4761 if (!isUndefOrEqual(Mask[i], i))
4763 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4764 if (!isUndefOrEqual(Mask[i], i+NumElems))
4769 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4771 static bool isSplatVector(SDNode *N) {
4772 if (N->getOpcode() != ISD::BUILD_VECTOR)
4775 SDValue SplatValue = N->getOperand(0);
4776 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4777 if (N->getOperand(i) != SplatValue)
4782 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4783 /// to an zero vector.
4784 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4785 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4786 SDValue V1 = N->getOperand(0);
4787 SDValue V2 = N->getOperand(1);
4788 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4789 for (unsigned i = 0; i != NumElems; ++i) {
4790 int Idx = N->getMaskElt(i);
4791 if (Idx >= (int)NumElems) {
4792 unsigned Opc = V2.getOpcode();
4793 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4795 if (Opc != ISD::BUILD_VECTOR ||
4796 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4798 } else if (Idx >= 0) {
4799 unsigned Opc = V1.getOpcode();
4800 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4802 if (Opc != ISD::BUILD_VECTOR ||
4803 !X86::isZeroNode(V1.getOperand(Idx)))
4810 /// getZeroVector - Returns a vector of specified type with all zero elements.
4812 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4813 SelectionDAG &DAG, SDLoc dl) {
4814 assert(VT.isVector() && "Expected a vector type");
4816 // Always build SSE zero vectors as <4 x i32> bitcasted
4817 // to their dest type. This ensures they get CSE'd.
4819 if (VT.is128BitVector()) { // SSE
4820 if (Subtarget->hasSSE2()) { // SSE2
4821 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4822 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4824 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4825 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4827 } else if (VT.is256BitVector()) { // AVX
4828 if (Subtarget->hasInt256()) { // AVX2
4829 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4830 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4831 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4833 // 256-bit logic and arithmetic instructions in AVX are all
4834 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4835 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4836 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4837 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4839 } else if (VT.is512BitVector()) { // AVX-512
4840 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4841 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4842 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4843 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4844 } else if (VT.getScalarType() == MVT::i1) {
4845 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4846 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4847 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4848 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4850 llvm_unreachable("Unexpected vector type");
4852 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4855 /// getOnesVector - Returns a vector of specified type with all bits set.
4856 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4857 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4858 /// Then bitcast to their original type, ensuring they get CSE'd.
4859 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4861 assert(VT.isVector() && "Expected a vector type");
4863 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4865 if (VT.is256BitVector()) {
4866 if (HasInt256) { // AVX2
4867 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4868 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4870 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4871 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4873 } else if (VT.is128BitVector()) {
4874 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4876 llvm_unreachable("Unexpected vector type");
4878 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4881 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4882 /// that point to V2 points to its first element.
4883 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4884 for (unsigned i = 0; i != NumElems; ++i) {
4885 if (Mask[i] > (int)NumElems) {
4891 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4892 /// operation of specified width.
4893 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4895 unsigned NumElems = VT.getVectorNumElements();
4896 SmallVector<int, 8> Mask;
4897 Mask.push_back(NumElems);
4898 for (unsigned i = 1; i != NumElems; ++i)
4900 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4903 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4904 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4906 unsigned NumElems = VT.getVectorNumElements();
4907 SmallVector<int, 8> Mask;
4908 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4910 Mask.push_back(i + NumElems);
4912 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4915 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4916 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4918 unsigned NumElems = VT.getVectorNumElements();
4919 SmallVector<int, 8> Mask;
4920 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4921 Mask.push_back(i + Half);
4922 Mask.push_back(i + NumElems + Half);
4924 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4927 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4928 // a generic shuffle instruction because the target has no such instructions.
4929 // Generate shuffles which repeat i16 and i8 several times until they can be
4930 // represented by v4f32 and then be manipulated by target suported shuffles.
4931 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4932 MVT VT = V.getSimpleValueType();
4933 int NumElems = VT.getVectorNumElements();
4936 while (NumElems > 4) {
4937 if (EltNo < NumElems/2) {
4938 V = getUnpackl(DAG, dl, VT, V, V);
4940 V = getUnpackh(DAG, dl, VT, V, V);
4941 EltNo -= NumElems/2;
4948 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4949 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4950 MVT VT = V.getSimpleValueType();
4953 if (VT.is128BitVector()) {
4954 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4955 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4956 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4958 } else if (VT.is256BitVector()) {
4959 // To use VPERMILPS to splat scalars, the second half of indicies must
4960 // refer to the higher part, which is a duplication of the lower one,
4961 // because VPERMILPS can only handle in-lane permutations.
4962 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4963 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4965 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4966 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4969 llvm_unreachable("Vector size not supported");
4971 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4974 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4975 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4976 MVT SrcVT = SV->getSimpleValueType(0);
4977 SDValue V1 = SV->getOperand(0);
4980 int EltNo = SV->getSplatIndex();
4981 int NumElems = SrcVT.getVectorNumElements();
4982 bool Is256BitVec = SrcVT.is256BitVector();
4984 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4985 "Unknown how to promote splat for type");
4987 // Extract the 128-bit part containing the splat element and update
4988 // the splat element index when it refers to the higher register.
4990 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4991 if (EltNo >= NumElems/2)
4992 EltNo -= NumElems/2;
4995 // All i16 and i8 vector types can't be used directly by a generic shuffle
4996 // instruction because the target has no such instruction. Generate shuffles
4997 // which repeat i16 and i8 several times until they fit in i32, and then can
4998 // be manipulated by target suported shuffles.
4999 MVT EltVT = SrcVT.getVectorElementType();
5000 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5001 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5003 // Recreate the 256-bit vector and place the same 128-bit vector
5004 // into the low and high part. This is necessary because we want
5005 // to use VPERM* to shuffle the vectors
5007 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5010 return getLegalSplat(DAG, V1, EltNo);
5013 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5014 /// vector of zero or undef vector. This produces a shuffle where the low
5015 /// element of V2 is swizzled into the zero/undef vector, landing at element
5016 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5017 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5019 const X86Subtarget *Subtarget,
5020 SelectionDAG &DAG) {
5021 MVT VT = V2.getSimpleValueType();
5023 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5024 unsigned NumElems = VT.getVectorNumElements();
5025 SmallVector<int, 16> MaskVec;
5026 for (unsigned i = 0; i != NumElems; ++i)
5027 // If this is the insertion idx, put the low elt of V2 here.
5028 MaskVec.push_back(i == Idx ? NumElems : i);
5029 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5032 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5033 /// target specific opcode. Returns true if the Mask could be calculated.
5034 /// Sets IsUnary to true if only uses one source.
5035 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5036 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5037 unsigned NumElems = VT.getVectorNumElements();
5041 switch(N->getOpcode()) {
5043 ImmN = N->getOperand(N->getNumOperands()-1);
5044 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5046 case X86ISD::UNPCKH:
5047 DecodeUNPCKHMask(VT, Mask);
5049 case X86ISD::UNPCKL:
5050 DecodeUNPCKLMask(VT, Mask);
5052 case X86ISD::MOVHLPS:
5053 DecodeMOVHLPSMask(NumElems, Mask);
5055 case X86ISD::MOVLHPS:
5056 DecodeMOVLHPSMask(NumElems, Mask);
5058 case X86ISD::PALIGNR:
5059 ImmN = N->getOperand(N->getNumOperands()-1);
5060 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5062 case X86ISD::PSHUFD:
5063 case X86ISD::VPERMILP:
5064 ImmN = N->getOperand(N->getNumOperands()-1);
5065 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5068 case X86ISD::PSHUFHW:
5069 ImmN = N->getOperand(N->getNumOperands()-1);
5070 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5073 case X86ISD::PSHUFLW:
5074 ImmN = N->getOperand(N->getNumOperands()-1);
5075 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5078 case X86ISD::VPERMI:
5079 ImmN = N->getOperand(N->getNumOperands()-1);
5080 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5084 case X86ISD::MOVSD: {
5085 // The index 0 always comes from the first element of the second source,
5086 // this is why MOVSS and MOVSD are used in the first place. The other
5087 // elements come from the other positions of the first source vector
5088 Mask.push_back(NumElems);
5089 for (unsigned i = 1; i != NumElems; ++i) {
5094 case X86ISD::VPERM2X128:
5095 ImmN = N->getOperand(N->getNumOperands()-1);
5096 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5097 if (Mask.empty()) return false;
5099 case X86ISD::MOVDDUP:
5100 case X86ISD::MOVLHPD:
5101 case X86ISD::MOVLPD:
5102 case X86ISD::MOVLPS:
5103 case X86ISD::MOVSHDUP:
5104 case X86ISD::MOVSLDUP:
5105 // Not yet implemented
5107 default: llvm_unreachable("unknown target shuffle node");
5113 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5114 /// element of the result of the vector shuffle.
5115 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5118 return SDValue(); // Limit search depth.
5120 SDValue V = SDValue(N, 0);
5121 EVT VT = V.getValueType();
5122 unsigned Opcode = V.getOpcode();
5124 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5125 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5126 int Elt = SV->getMaskElt(Index);
5129 return DAG.getUNDEF(VT.getVectorElementType());
5131 unsigned NumElems = VT.getVectorNumElements();
5132 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5133 : SV->getOperand(1);
5134 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5137 // Recurse into target specific vector shuffles to find scalars.
5138 if (isTargetShuffle(Opcode)) {
5139 MVT ShufVT = V.getSimpleValueType();
5140 unsigned NumElems = ShufVT.getVectorNumElements();
5141 SmallVector<int, 16> ShuffleMask;
5144 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5147 int Elt = ShuffleMask[Index];
5149 return DAG.getUNDEF(ShufVT.getVectorElementType());
5151 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5153 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5157 // Actual nodes that may contain scalar elements
5158 if (Opcode == ISD::BITCAST) {
5159 V = V.getOperand(0);
5160 EVT SrcVT = V.getValueType();
5161 unsigned NumElems = VT.getVectorNumElements();
5163 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5167 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5168 return (Index == 0) ? V.getOperand(0)
5169 : DAG.getUNDEF(VT.getVectorElementType());
5171 if (V.getOpcode() == ISD::BUILD_VECTOR)
5172 return V.getOperand(Index);
5177 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5178 /// shuffle operation which come from a consecutively from a zero. The
5179 /// search can start in two different directions, from left or right.
5180 /// We count undefs as zeros until PreferredNum is reached.
5181 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5182 unsigned NumElems, bool ZerosFromLeft,
5184 unsigned PreferredNum = -1U) {
5185 unsigned NumZeros = 0;
5186 for (unsigned i = 0; i != NumElems; ++i) {
5187 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5188 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5192 if (X86::isZeroNode(Elt))
5194 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5195 NumZeros = std::min(NumZeros + 1, PreferredNum);
5203 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5204 /// correspond consecutively to elements from one of the vector operands,
5205 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5207 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5208 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5209 unsigned NumElems, unsigned &OpNum) {
5210 bool SeenV1 = false;
5211 bool SeenV2 = false;
5213 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5214 int Idx = SVOp->getMaskElt(i);
5215 // Ignore undef indicies
5219 if (Idx < (int)NumElems)
5224 // Only accept consecutive elements from the same vector
5225 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5229 OpNum = SeenV1 ? 0 : 1;
5233 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5234 /// logical left shift of a vector.
5235 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5236 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5238 SVOp->getSimpleValueType(0).getVectorNumElements();
5239 unsigned NumZeros = getNumOfConsecutiveZeros(
5240 SVOp, NumElems, false /* check zeros from right */, DAG,
5241 SVOp->getMaskElt(0));
5247 // Considering the elements in the mask that are not consecutive zeros,
5248 // check if they consecutively come from only one of the source vectors.
5250 // V1 = {X, A, B, C} 0
5252 // vector_shuffle V1, V2 <1, 2, 3, X>
5254 if (!isShuffleMaskConsecutive(SVOp,
5255 0, // Mask Start Index
5256 NumElems-NumZeros, // Mask End Index(exclusive)
5257 NumZeros, // Where to start looking in the src vector
5258 NumElems, // Number of elements in vector
5259 OpSrc)) // Which source operand ?
5264 ShVal = SVOp->getOperand(OpSrc);
5268 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5269 /// logical left shift of a vector.
5270 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5271 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5273 SVOp->getSimpleValueType(0).getVectorNumElements();
5274 unsigned NumZeros = getNumOfConsecutiveZeros(
5275 SVOp, NumElems, true /* check zeros from left */, DAG,
5276 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5282 // Considering the elements in the mask that are not consecutive zeros,
5283 // check if they consecutively come from only one of the source vectors.
5285 // 0 { A, B, X, X } = V2
5287 // vector_shuffle V1, V2 <X, X, 4, 5>
5289 if (!isShuffleMaskConsecutive(SVOp,
5290 NumZeros, // Mask Start Index
5291 NumElems, // Mask End Index(exclusive)
5292 0, // Where to start looking in the src vector
5293 NumElems, // Number of elements in vector
5294 OpSrc)) // Which source operand ?
5299 ShVal = SVOp->getOperand(OpSrc);
5303 /// isVectorShift - Returns true if the shuffle can be implemented as a
5304 /// logical left or right shift of a vector.
5305 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5306 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5307 // Although the logic below support any bitwidth size, there are no
5308 // shift instructions which handle more than 128-bit vectors.
5309 if (!SVOp->getSimpleValueType(0).is128BitVector())
5312 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5313 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5319 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5321 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5322 unsigned NumNonZero, unsigned NumZero,
5324 const X86Subtarget* Subtarget,
5325 const TargetLowering &TLI) {
5332 for (unsigned i = 0; i < 16; ++i) {
5333 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5334 if (ThisIsNonZero && First) {
5336 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5338 V = DAG.getUNDEF(MVT::v8i16);
5343 SDValue ThisElt, LastElt;
5344 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5345 if (LastIsNonZero) {
5346 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5347 MVT::i16, Op.getOperand(i-1));
5349 if (ThisIsNonZero) {
5350 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5351 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5352 ThisElt, DAG.getConstant(8, MVT::i8));
5354 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5358 if (ThisElt.getNode())
5359 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5360 DAG.getIntPtrConstant(i/2));
5364 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5367 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5369 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5370 unsigned NumNonZero, unsigned NumZero,
5372 const X86Subtarget* Subtarget,
5373 const TargetLowering &TLI) {
5380 for (unsigned i = 0; i < 8; ++i) {
5381 bool isNonZero = (NonZeros & (1 << i)) != 0;
5385 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5387 V = DAG.getUNDEF(MVT::v8i16);
5390 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5391 MVT::v8i16, V, Op.getOperand(i),
5392 DAG.getIntPtrConstant(i));
5399 /// getVShift - Return a vector logical shift node.
5401 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5402 unsigned NumBits, SelectionDAG &DAG,
5403 const TargetLowering &TLI, SDLoc dl) {
5404 assert(VT.is128BitVector() && "Unknown type for VShift");
5405 EVT ShVT = MVT::v2i64;
5406 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5407 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5408 return DAG.getNode(ISD::BITCAST, dl, VT,
5409 DAG.getNode(Opc, dl, ShVT, SrcOp,
5410 DAG.getConstant(NumBits,
5411 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5415 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5417 // Check if the scalar load can be widened into a vector load. And if
5418 // the address is "base + cst" see if the cst can be "absorbed" into
5419 // the shuffle mask.
5420 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5421 SDValue Ptr = LD->getBasePtr();
5422 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5424 EVT PVT = LD->getValueType(0);
5425 if (PVT != MVT::i32 && PVT != MVT::f32)
5430 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5431 FI = FINode->getIndex();
5433 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5434 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5435 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5436 Offset = Ptr.getConstantOperandVal(1);
5437 Ptr = Ptr.getOperand(0);
5442 // FIXME: 256-bit vector instructions don't require a strict alignment,
5443 // improve this code to support it better.
5444 unsigned RequiredAlign = VT.getSizeInBits()/8;
5445 SDValue Chain = LD->getChain();
5446 // Make sure the stack object alignment is at least 16 or 32.
5447 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5448 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5449 if (MFI->isFixedObjectIndex(FI)) {
5450 // Can't change the alignment. FIXME: It's possible to compute
5451 // the exact stack offset and reference FI + adjust offset instead.
5452 // If someone *really* cares about this. That's the way to implement it.
5455 MFI->setObjectAlignment(FI, RequiredAlign);
5459 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5460 // Ptr + (Offset & ~15).
5463 if ((Offset % RequiredAlign) & 3)
5465 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5467 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5468 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5470 int EltNo = (Offset - StartOffset) >> 2;
5471 unsigned NumElems = VT.getVectorNumElements();
5473 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5474 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5475 LD->getPointerInfo().getWithOffset(StartOffset),
5476 false, false, false, 0);
5478 SmallVector<int, 8> Mask;
5479 for (unsigned i = 0; i != NumElems; ++i)
5480 Mask.push_back(EltNo);
5482 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5488 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5489 /// vector of type 'VT', see if the elements can be replaced by a single large
5490 /// load which has the same value as a build_vector whose operands are 'elts'.
5492 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5494 /// FIXME: we'd also like to handle the case where the last elements are zero
5495 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5496 /// There's even a handy isZeroNode for that purpose.
5497 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5498 SDLoc &DL, SelectionDAG &DAG,
5499 bool isAfterLegalize) {
5500 EVT EltVT = VT.getVectorElementType();
5501 unsigned NumElems = Elts.size();
5503 LoadSDNode *LDBase = nullptr;
5504 unsigned LastLoadedElt = -1U;
5506 // For each element in the initializer, see if we've found a load or an undef.
5507 // If we don't find an initial load element, or later load elements are
5508 // non-consecutive, bail out.
5509 for (unsigned i = 0; i < NumElems; ++i) {
5510 SDValue Elt = Elts[i];
5512 if (!Elt.getNode() ||
5513 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5516 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5518 LDBase = cast<LoadSDNode>(Elt.getNode());
5522 if (Elt.getOpcode() == ISD::UNDEF)
5525 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5526 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5531 // If we have found an entire vector of loads and undefs, then return a large
5532 // load of the entire vector width starting at the base pointer. If we found
5533 // consecutive loads for the low half, generate a vzext_load node.
5534 if (LastLoadedElt == NumElems - 1) {
5536 if (isAfterLegalize &&
5537 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5540 SDValue NewLd = SDValue();
5542 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5543 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5544 LDBase->getPointerInfo(),
5545 LDBase->isVolatile(), LDBase->isNonTemporal(),
5546 LDBase->isInvariant(), 0);
5547 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5548 LDBase->getPointerInfo(),
5549 LDBase->isVolatile(), LDBase->isNonTemporal(),
5550 LDBase->isInvariant(), LDBase->getAlignment());
5552 if (LDBase->hasAnyUseOfValue(1)) {
5553 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5555 SDValue(NewLd.getNode(), 1));
5556 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5557 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5558 SDValue(NewLd.getNode(), 1));
5563 if (NumElems == 4 && LastLoadedElt == 1 &&
5564 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5565 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5566 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5568 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5569 array_lengthof(Ops), MVT::i64,
5570 LDBase->getPointerInfo(),
5571 LDBase->getAlignment(),
5572 false/*isVolatile*/, true/*ReadMem*/,
5575 // Make sure the newly-created LOAD is in the same position as LDBase in
5576 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5577 // update uses of LDBase's output chain to use the TokenFactor.
5578 if (LDBase->hasAnyUseOfValue(1)) {
5579 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5580 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5581 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5582 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5583 SDValue(ResNode.getNode(), 1));
5586 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5591 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5592 /// to generate a splat value for the following cases:
5593 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5594 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5595 /// a scalar load, or a constant.
5596 /// The VBROADCAST node is returned when a pattern is found,
5597 /// or SDValue() otherwise.
5598 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5599 SelectionDAG &DAG) {
5600 if (!Subtarget->hasFp256())
5603 MVT VT = Op.getSimpleValueType();
5606 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5607 "Unsupported vector type for broadcast.");
5612 switch (Op.getOpcode()) {
5614 // Unknown pattern found.
5617 case ISD::BUILD_VECTOR: {
5618 // The BUILD_VECTOR node must be a splat.
5619 if (!isSplatVector(Op.getNode()))
5622 Ld = Op.getOperand(0);
5623 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5624 Ld.getOpcode() == ISD::ConstantFP);
5626 // The suspected load node has several users. Make sure that all
5627 // of its users are from the BUILD_VECTOR node.
5628 // Constants may have multiple users.
5629 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5634 case ISD::VECTOR_SHUFFLE: {
5635 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5637 // Shuffles must have a splat mask where the first element is
5639 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5642 SDValue Sc = Op.getOperand(0);
5643 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5644 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5646 if (!Subtarget->hasInt256())
5649 // Use the register form of the broadcast instruction available on AVX2.
5650 if (VT.getSizeInBits() >= 256)
5651 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5652 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5655 Ld = Sc.getOperand(0);
5656 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5657 Ld.getOpcode() == ISD::ConstantFP);
5659 // The scalar_to_vector node and the suspected
5660 // load node must have exactly one user.
5661 // Constants may have multiple users.
5663 // AVX-512 has register version of the broadcast
5664 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5665 Ld.getValueType().getSizeInBits() >= 32;
5666 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5673 bool IsGE256 = (VT.getSizeInBits() >= 256);
5675 // Handle the broadcasting a single constant scalar from the constant pool
5676 // into a vector. On Sandybridge it is still better to load a constant vector
5677 // from the constant pool and not to broadcast it from a scalar.
5678 if (ConstSplatVal && Subtarget->hasInt256()) {
5679 EVT CVT = Ld.getValueType();
5680 assert(!CVT.isVector() && "Must not broadcast a vector type");
5681 unsigned ScalarSize = CVT.getSizeInBits();
5683 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5684 const Constant *C = nullptr;
5685 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5686 C = CI->getConstantIntValue();
5687 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5688 C = CF->getConstantFPValue();
5690 assert(C && "Invalid constant type");
5692 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5693 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5694 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5695 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5696 MachinePointerInfo::getConstantPool(),
5697 false, false, false, Alignment);
5699 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5703 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5704 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5706 // Handle AVX2 in-register broadcasts.
5707 if (!IsLoad && Subtarget->hasInt256() &&
5708 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5709 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5711 // The scalar source must be a normal load.
5715 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5716 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5718 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5719 // double since there is no vbroadcastsd xmm
5720 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5721 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5722 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5725 // Unsupported broadcast.
5729 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5730 /// underlying vector and index.
5732 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5734 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5736 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5737 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5740 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5742 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5744 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5745 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5748 // In this case the vector is the extract_subvector expression and the index
5749 // is 2, as specified by the shuffle.
5750 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5751 SDValue ShuffleVec = SVOp->getOperand(0);
5752 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5753 assert(ShuffleVecVT.getVectorElementType() ==
5754 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5756 int ShuffleIdx = SVOp->getMaskElt(Idx);
5757 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5758 ExtractedFromVec = ShuffleVec;
5764 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5765 MVT VT = Op.getSimpleValueType();
5767 // Skip if insert_vec_elt is not supported.
5768 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5769 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5773 unsigned NumElems = Op.getNumOperands();
5777 SmallVector<unsigned, 4> InsertIndices;
5778 SmallVector<int, 8> Mask(NumElems, -1);
5780 for (unsigned i = 0; i != NumElems; ++i) {
5781 unsigned Opc = Op.getOperand(i).getOpcode();
5783 if (Opc == ISD::UNDEF)
5786 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5787 // Quit if more than 1 elements need inserting.
5788 if (InsertIndices.size() > 1)
5791 InsertIndices.push_back(i);
5795 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5796 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5797 // Quit if non-constant index.
5798 if (!isa<ConstantSDNode>(ExtIdx))
5800 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5802 // Quit if extracted from vector of different type.
5803 if (ExtractedFromVec.getValueType() != VT)
5806 if (!VecIn1.getNode())
5807 VecIn1 = ExtractedFromVec;
5808 else if (VecIn1 != ExtractedFromVec) {
5809 if (!VecIn2.getNode())
5810 VecIn2 = ExtractedFromVec;
5811 else if (VecIn2 != ExtractedFromVec)
5812 // Quit if more than 2 vectors to shuffle
5816 if (ExtractedFromVec == VecIn1)
5818 else if (ExtractedFromVec == VecIn2)
5819 Mask[i] = Idx + NumElems;
5822 if (!VecIn1.getNode())
5825 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5826 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5827 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5828 unsigned Idx = InsertIndices[i];
5829 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5830 DAG.getIntPtrConstant(Idx));
5836 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5838 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5840 MVT VT = Op.getSimpleValueType();
5841 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5842 "Unexpected type in LowerBUILD_VECTORvXi1!");
5845 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5846 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5847 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5848 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5851 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5852 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5853 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5854 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5857 bool AllContants = true;
5858 uint64_t Immediate = 0;
5859 int NonConstIdx = -1;
5860 bool IsSplat = true;
5861 unsigned NumNonConsts = 0;
5862 unsigned NumConsts = 0;
5863 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5864 SDValue In = Op.getOperand(idx);
5865 if (In.getOpcode() == ISD::UNDEF)
5867 if (!isa<ConstantSDNode>(In)) {
5868 AllContants = false;
5874 if (cast<ConstantSDNode>(In)->getZExtValue())
5875 Immediate |= (1ULL << idx);
5877 if (In != Op.getOperand(0))
5882 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5883 DAG.getConstant(Immediate, MVT::i16));
5884 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5885 DAG.getIntPtrConstant(0));
5888 if (NumNonConsts == 1 && NonConstIdx != 0) {
5891 SDValue VecAsImm = DAG.getConstant(Immediate,
5892 MVT::getIntegerVT(VT.getSizeInBits()));
5893 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5896 DstVec = DAG.getUNDEF(VT);
5897 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5898 Op.getOperand(NonConstIdx),
5899 DAG.getIntPtrConstant(NonConstIdx));
5901 if (!IsSplat && (NonConstIdx != 0))
5902 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5903 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5906 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5907 DAG.getConstant(-1, SelectVT),
5908 DAG.getConstant(0, SelectVT));
5910 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5911 DAG.getConstant((Immediate | 1), SelectVT),
5912 DAG.getConstant(Immediate, SelectVT));
5913 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5917 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5920 MVT VT = Op.getSimpleValueType();
5921 MVT ExtVT = VT.getVectorElementType();
5922 unsigned NumElems = Op.getNumOperands();
5924 // Generate vectors for predicate vectors.
5925 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5926 return LowerBUILD_VECTORvXi1(Op, DAG);
5928 // Vectors containing all zeros can be matched by pxor and xorps later
5929 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5930 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5931 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5932 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5935 return getZeroVector(VT, Subtarget, DAG, dl);
5938 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5939 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5940 // vpcmpeqd on 256-bit vectors.
5941 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5942 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5945 if (!VT.is512BitVector())
5946 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5949 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5950 if (Broadcast.getNode())
5953 unsigned EVTBits = ExtVT.getSizeInBits();
5955 unsigned NumZero = 0;
5956 unsigned NumNonZero = 0;
5957 unsigned NonZeros = 0;
5958 bool IsAllConstants = true;
5959 SmallSet<SDValue, 8> Values;
5960 for (unsigned i = 0; i < NumElems; ++i) {
5961 SDValue Elt = Op.getOperand(i);
5962 if (Elt.getOpcode() == ISD::UNDEF)
5965 if (Elt.getOpcode() != ISD::Constant &&
5966 Elt.getOpcode() != ISD::ConstantFP)
5967 IsAllConstants = false;
5968 if (X86::isZeroNode(Elt))
5971 NonZeros |= (1 << i);
5976 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5977 if (NumNonZero == 0)
5978 return DAG.getUNDEF(VT);
5980 // Special case for single non-zero, non-undef, element.
5981 if (NumNonZero == 1) {
5982 unsigned Idx = countTrailingZeros(NonZeros);
5983 SDValue Item = Op.getOperand(Idx);
5985 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5986 // the value are obviously zero, truncate the value to i32 and do the
5987 // insertion that way. Only do this if the value is non-constant or if the
5988 // value is a constant being inserted into element 0. It is cheaper to do
5989 // a constant pool load than it is to do a movd + shuffle.
5990 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5991 (!IsAllConstants || Idx == 0)) {
5992 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5994 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5995 EVT VecVT = MVT::v4i32;
5996 unsigned VecElts = 4;
5998 // Truncate the value (which may itself be a constant) to i32, and
5999 // convert it to a vector with movd (S2V+shuffle to zero extend).
6000 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6001 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6002 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6004 // Now we have our 32-bit value zero extended in the low element of
6005 // a vector. If Idx != 0, swizzle it into place.
6007 SmallVector<int, 4> Mask;
6008 Mask.push_back(Idx);
6009 for (unsigned i = 1; i != VecElts; ++i)
6011 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6014 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6018 // If we have a constant or non-constant insertion into the low element of
6019 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6020 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6021 // depending on what the source datatype is.
6024 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6026 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6027 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6028 if (VT.is256BitVector() || VT.is512BitVector()) {
6029 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6030 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6031 Item, DAG.getIntPtrConstant(0));
6033 assert(VT.is128BitVector() && "Expected an SSE value type!");
6034 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6035 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6036 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6039 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6040 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6041 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6042 if (VT.is256BitVector()) {
6043 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6044 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6046 assert(VT.is128BitVector() && "Expected an SSE value type!");
6047 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6049 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6053 // Is it a vector logical left shift?
6054 if (NumElems == 2 && Idx == 1 &&
6055 X86::isZeroNode(Op.getOperand(0)) &&
6056 !X86::isZeroNode(Op.getOperand(1))) {
6057 unsigned NumBits = VT.getSizeInBits();
6058 return getVShift(true, VT,
6059 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6060 VT, Op.getOperand(1)),
6061 NumBits/2, DAG, *this, dl);
6064 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6067 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6068 // is a non-constant being inserted into an element other than the low one,
6069 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6070 // movd/movss) to move this into the low element, then shuffle it into
6072 if (EVTBits == 32) {
6073 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6075 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6076 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6077 SmallVector<int, 8> MaskVec;
6078 for (unsigned i = 0; i != NumElems; ++i)
6079 MaskVec.push_back(i == Idx ? 0 : 1);
6080 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6084 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6085 if (Values.size() == 1) {
6086 if (EVTBits == 32) {
6087 // Instead of a shuffle like this:
6088 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6089 // Check if it's possible to issue this instead.
6090 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6091 unsigned Idx = countTrailingZeros(NonZeros);
6092 SDValue Item = Op.getOperand(Idx);
6093 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6094 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6099 // A vector full of immediates; various special cases are already
6100 // handled, so this is best done with a single constant-pool load.
6104 // For AVX-length vectors, build the individual 128-bit pieces and use
6105 // shuffles to put them in place.
6106 if (VT.is256BitVector() || VT.is512BitVector()) {
6107 SmallVector<SDValue, 64> V;
6108 for (unsigned i = 0; i != NumElems; ++i)
6109 V.push_back(Op.getOperand(i));
6111 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6113 // Build both the lower and upper subvector.
6114 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6115 ArrayRef<SDValue>(&V[0], NumElems/2));
6116 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6117 ArrayRef<SDValue>(&V[NumElems / 2],
6120 // Recreate the wider vector with the lower and upper part.
6121 if (VT.is256BitVector())
6122 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6123 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6126 // Let legalizer expand 2-wide build_vectors.
6127 if (EVTBits == 64) {
6128 if (NumNonZero == 1) {
6129 // One half is zero or undef.
6130 unsigned Idx = countTrailingZeros(NonZeros);
6131 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6132 Op.getOperand(Idx));
6133 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6138 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6139 if (EVTBits == 8 && NumElems == 16) {
6140 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6142 if (V.getNode()) return V;
6145 if (EVTBits == 16 && NumElems == 8) {
6146 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6148 if (V.getNode()) return V;
6151 // If element VT is == 32 bits, turn it into a number of shuffles.
6152 SmallVector<SDValue, 8> V(NumElems);
6153 if (NumElems == 4 && NumZero > 0) {
6154 for (unsigned i = 0; i < 4; ++i) {
6155 bool isZero = !(NonZeros & (1 << i));
6157 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6159 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6162 for (unsigned i = 0; i < 2; ++i) {
6163 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6166 V[i] = V[i*2]; // Must be a zero vector.
6169 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6172 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6175 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6180 bool Reverse1 = (NonZeros & 0x3) == 2;
6181 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6185 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6186 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6188 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6191 if (Values.size() > 1 && VT.is128BitVector()) {
6192 // Check for a build vector of consecutive loads.
6193 for (unsigned i = 0; i < NumElems; ++i)
6194 V[i] = Op.getOperand(i);
6196 // Check for elements which are consecutive loads.
6197 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6201 // Check for a build vector from mostly shuffle plus few inserting.
6202 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6206 // For SSE 4.1, use insertps to put the high elements into the low element.
6207 if (getSubtarget()->hasSSE41()) {
6209 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6210 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6212 Result = DAG.getUNDEF(VT);
6214 for (unsigned i = 1; i < NumElems; ++i) {
6215 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6216 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6217 Op.getOperand(i), DAG.getIntPtrConstant(i));
6222 // Otherwise, expand into a number of unpckl*, start by extending each of
6223 // our (non-undef) elements to the full vector width with the element in the
6224 // bottom slot of the vector (which generates no code for SSE).
6225 for (unsigned i = 0; i < NumElems; ++i) {
6226 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6227 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6229 V[i] = DAG.getUNDEF(VT);
6232 // Next, we iteratively mix elements, e.g. for v4f32:
6233 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6234 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6235 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6236 unsigned EltStride = NumElems >> 1;
6237 while (EltStride != 0) {
6238 for (unsigned i = 0; i < EltStride; ++i) {
6239 // If V[i+EltStride] is undef and this is the first round of mixing,
6240 // then it is safe to just drop this shuffle: V[i] is already in the
6241 // right place, the one element (since it's the first round) being
6242 // inserted as undef can be dropped. This isn't safe for successive
6243 // rounds because they will permute elements within both vectors.
6244 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6245 EltStride == NumElems/2)
6248 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6257 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6258 // to create 256-bit vectors from two other 128-bit ones.
6259 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6261 MVT ResVT = Op.getSimpleValueType();
6263 assert((ResVT.is256BitVector() ||
6264 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6266 SDValue V1 = Op.getOperand(0);
6267 SDValue V2 = Op.getOperand(1);
6268 unsigned NumElems = ResVT.getVectorNumElements();
6269 if(ResVT.is256BitVector())
6270 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6272 if (Op.getNumOperands() == 4) {
6273 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6274 ResVT.getVectorNumElements()/2);
6275 SDValue V3 = Op.getOperand(2);
6276 SDValue V4 = Op.getOperand(3);
6277 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6278 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6280 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6283 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6284 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6285 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6286 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6287 Op.getNumOperands() == 4)));
6289 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6290 // from two other 128-bit ones.
6292 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6293 return LowerAVXCONCAT_VECTORS(Op, DAG);
6296 // Try to lower a shuffle node into a simple blend instruction.
6298 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6299 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6300 SDValue V1 = SVOp->getOperand(0);
6301 SDValue V2 = SVOp->getOperand(1);
6303 MVT VT = SVOp->getSimpleValueType(0);
6304 MVT EltVT = VT.getVectorElementType();
6305 unsigned NumElems = VT.getVectorNumElements();
6307 // There is no blend with immediate in AVX-512.
6308 if (VT.is512BitVector())
6311 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6313 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6316 // Check the mask for BLEND and build the value.
6317 unsigned MaskValue = 0;
6318 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6319 unsigned NumLanes = (NumElems-1)/8 + 1;
6320 unsigned NumElemsInLane = NumElems / NumLanes;
6322 // Blend for v16i16 should be symetric for the both lanes.
6323 for (unsigned i = 0; i < NumElemsInLane; ++i) {
6325 int SndLaneEltIdx = (NumLanes == 2) ?
6326 SVOp->getMaskElt(i + NumElemsInLane) : -1;
6327 int EltIdx = SVOp->getMaskElt(i);
6329 if ((EltIdx < 0 || EltIdx == (int)i) &&
6330 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6333 if (((unsigned)EltIdx == (i + NumElems)) &&
6334 (SndLaneEltIdx < 0 ||
6335 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6336 MaskValue |= (1<<i);
6341 // Convert i32 vectors to floating point if it is not AVX2.
6342 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6344 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6345 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6347 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6348 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6351 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6352 DAG.getConstant(MaskValue, MVT::i32));
6353 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6356 /// In vector type \p VT, return true if the element at index \p InputIdx
6357 /// falls on a different 128-bit lane than \p OutputIdx.
6358 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6359 unsigned OutputIdx) {
6360 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6361 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6364 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
6365 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
6366 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
6367 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6369 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6370 SelectionDAG &DAG) {
6371 MVT VT = V1.getSimpleValueType();
6372 assert(VT.is128BitVector() || VT.is256BitVector());
6374 MVT EltVT = VT.getVectorElementType();
6375 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6376 unsigned NumElts = VT.getVectorNumElements();
6378 SmallVector<SDValue, 32> PshufbMask;
6379 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6380 int InputIdx = MaskVals[OutputIdx];
6381 unsigned InputByteIdx;
6383 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6384 InputByteIdx = 0x80;
6386 // Cross lane is not allowed.
6387 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6389 InputByteIdx = InputIdx * EltSizeInBytes;
6390 // Index is an byte offset within the 128-bit lane.
6391 InputByteIdx &= 0xf;
6394 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6395 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6396 if (InputByteIdx != 0x80)
6401 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6403 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6404 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6405 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6408 // v8i16 shuffles - Prefer shuffles in the following order:
6409 // 1. [all] pshuflw, pshufhw, optional move
6410 // 2. [ssse3] 1 x pshufb
6411 // 3. [ssse3] 2 x pshufb + 1 x por
6412 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6414 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6415 SelectionDAG &DAG) {
6416 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6417 SDValue V1 = SVOp->getOperand(0);
6418 SDValue V2 = SVOp->getOperand(1);
6420 SmallVector<int, 8> MaskVals;
6422 // Determine if more than 1 of the words in each of the low and high quadwords
6423 // of the result come from the same quadword of one of the two inputs. Undef
6424 // mask values count as coming from any quadword, for better codegen.
6426 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6427 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6428 unsigned LoQuad[] = { 0, 0, 0, 0 };
6429 unsigned HiQuad[] = { 0, 0, 0, 0 };
6430 // Indices of quads used.
6431 std::bitset<4> InputQuads;
6432 for (unsigned i = 0; i < 8; ++i) {
6433 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6434 int EltIdx = SVOp->getMaskElt(i);
6435 MaskVals.push_back(EltIdx);
6444 InputQuads.set(EltIdx / 4);
6447 int BestLoQuad = -1;
6448 unsigned MaxQuad = 1;
6449 for (unsigned i = 0; i < 4; ++i) {
6450 if (LoQuad[i] > MaxQuad) {
6452 MaxQuad = LoQuad[i];
6456 int BestHiQuad = -1;
6458 for (unsigned i = 0; i < 4; ++i) {
6459 if (HiQuad[i] > MaxQuad) {
6461 MaxQuad = HiQuad[i];
6465 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6466 // of the two input vectors, shuffle them into one input vector so only a
6467 // single pshufb instruction is necessary. If there are more than 2 input
6468 // quads, disable the next transformation since it does not help SSSE3.
6469 bool V1Used = InputQuads[0] || InputQuads[1];
6470 bool V2Used = InputQuads[2] || InputQuads[3];
6471 if (Subtarget->hasSSSE3()) {
6472 if (InputQuads.count() == 2 && V1Used && V2Used) {
6473 BestLoQuad = InputQuads[0] ? 0 : 1;
6474 BestHiQuad = InputQuads[2] ? 2 : 3;
6476 if (InputQuads.count() > 2) {
6482 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6483 // the shuffle mask. If a quad is scored as -1, that means that it contains
6484 // words from all 4 input quadwords.
6486 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6488 BestLoQuad < 0 ? 0 : BestLoQuad,
6489 BestHiQuad < 0 ? 1 : BestHiQuad
6491 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6492 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6493 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6494 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6496 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6497 // source words for the shuffle, to aid later transformations.
6498 bool AllWordsInNewV = true;
6499 bool InOrder[2] = { true, true };
6500 for (unsigned i = 0; i != 8; ++i) {
6501 int idx = MaskVals[i];
6503 InOrder[i/4] = false;
6504 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6506 AllWordsInNewV = false;
6510 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6511 if (AllWordsInNewV) {
6512 for (int i = 0; i != 8; ++i) {
6513 int idx = MaskVals[i];
6516 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6517 if ((idx != i) && idx < 4)
6519 if ((idx != i) && idx > 3)
6528 // If we've eliminated the use of V2, and the new mask is a pshuflw or
6529 // pshufhw, that's as cheap as it gets. Return the new shuffle.
6530 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6531 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6532 unsigned TargetMask = 0;
6533 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6534 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6535 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6536 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6537 getShufflePSHUFLWImmediate(SVOp);
6538 V1 = NewV.getOperand(0);
6539 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6543 // Promote splats to a larger type which usually leads to more efficient code.
6544 // FIXME: Is this true if pshufb is available?
6545 if (SVOp->isSplat())
6546 return PromoteSplat(SVOp, DAG);
6548 // If we have SSSE3, and all words of the result are from 1 input vector,
6549 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
6550 // is present, fall back to case 4.
6551 if (Subtarget->hasSSSE3()) {
6552 SmallVector<SDValue,16> pshufbMask;
6554 // If we have elements from both input vectors, set the high bit of the
6555 // shuffle mask element to zero out elements that come from V2 in the V1
6556 // mask, and elements that come from V1 in the V2 mask, so that the two
6557 // results can be OR'd together.
6558 bool TwoInputs = V1Used && V2Used;
6559 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6561 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6563 // Calculate the shuffle mask for the second input, shuffle it, and
6564 // OR it with the first shuffled input.
6565 CommuteVectorShuffleMask(MaskVals, 8);
6566 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6567 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6568 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6571 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6572 // and update MaskVals with new element order.
6573 std::bitset<8> InOrder;
6574 if (BestLoQuad >= 0) {
6575 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6576 for (int i = 0; i != 4; ++i) {
6577 int idx = MaskVals[i];
6580 } else if ((idx / 4) == BestLoQuad) {
6585 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6588 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6589 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6590 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6592 getShufflePSHUFLWImmediate(SVOp), DAG);
6596 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6597 // and update MaskVals with the new element order.
6598 if (BestHiQuad >= 0) {
6599 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6600 for (unsigned i = 4; i != 8; ++i) {
6601 int idx = MaskVals[i];
6604 } else if ((idx / 4) == BestHiQuad) {
6605 MaskV[i] = (idx & 3) + 4;
6609 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6612 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6613 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6614 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6616 getShufflePSHUFHWImmediate(SVOp), DAG);
6620 // In case BestHi & BestLo were both -1, which means each quadword has a word
6621 // from each of the four input quadwords, calculate the InOrder bitvector now
6622 // before falling through to the insert/extract cleanup.
6623 if (BestLoQuad == -1 && BestHiQuad == -1) {
6625 for (int i = 0; i != 8; ++i)
6626 if (MaskVals[i] < 0 || MaskVals[i] == i)
6630 // The other elements are put in the right place using pextrw and pinsrw.
6631 for (unsigned i = 0; i != 8; ++i) {
6634 int EltIdx = MaskVals[i];
6637 SDValue ExtOp = (EltIdx < 8) ?
6638 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6639 DAG.getIntPtrConstant(EltIdx)) :
6640 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6641 DAG.getIntPtrConstant(EltIdx - 8));
6642 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6643 DAG.getIntPtrConstant(i));
6648 /// \brief v16i16 shuffles
6650 /// FIXME: We only support generation of a single pshufb currently. We can
6651 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6652 /// well (e.g 2 x pshufb + 1 x por).
6654 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6655 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6656 SDValue V1 = SVOp->getOperand(0);
6657 SDValue V2 = SVOp->getOperand(1);
6660 if (V2.getOpcode() != ISD::UNDEF)
6663 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6664 return getPSHUFB(MaskVals, V1, dl, DAG);
6667 // v16i8 shuffles - Prefer shuffles in the following order:
6668 // 1. [ssse3] 1 x pshufb
6669 // 2. [ssse3] 2 x pshufb + 1 x por
6670 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6671 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6672 const X86Subtarget* Subtarget,
6673 SelectionDAG &DAG) {
6674 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6675 SDValue V1 = SVOp->getOperand(0);
6676 SDValue V2 = SVOp->getOperand(1);
6678 ArrayRef<int> MaskVals = SVOp->getMask();
6680 // Promote splats to a larger type which usually leads to more efficient code.
6681 // FIXME: Is this true if pshufb is available?
6682 if (SVOp->isSplat())
6683 return PromoteSplat(SVOp, DAG);
6685 // If we have SSSE3, case 1 is generated when all result bytes come from
6686 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6687 // present, fall back to case 3.
6689 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6690 if (Subtarget->hasSSSE3()) {
6691 SmallVector<SDValue,16> pshufbMask;
6693 // If all result elements are from one input vector, then only translate
6694 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6696 // Otherwise, we have elements from both input vectors, and must zero out
6697 // elements that come from V2 in the first mask, and V1 in the second mask
6698 // so that we can OR them together.
6699 for (unsigned i = 0; i != 16; ++i) {
6700 int EltIdx = MaskVals[i];
6701 if (EltIdx < 0 || EltIdx >= 16)
6703 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6705 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6706 DAG.getNode(ISD::BUILD_VECTOR, dl,
6707 MVT::v16i8, pshufbMask));
6709 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6710 // the 2nd operand if it's undefined or zero.
6711 if (V2.getOpcode() == ISD::UNDEF ||
6712 ISD::isBuildVectorAllZeros(V2.getNode()))
6715 // Calculate the shuffle mask for the second input, shuffle it, and
6716 // OR it with the first shuffled input.
6718 for (unsigned i = 0; i != 16; ++i) {
6719 int EltIdx = MaskVals[i];
6720 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6721 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6723 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6724 DAG.getNode(ISD::BUILD_VECTOR, dl,
6725 MVT::v16i8, pshufbMask));
6726 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6729 // No SSSE3 - Calculate in place words and then fix all out of place words
6730 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6731 // the 16 different words that comprise the two doublequadword input vectors.
6732 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6733 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6735 for (int i = 0; i != 8; ++i) {
6736 int Elt0 = MaskVals[i*2];
6737 int Elt1 = MaskVals[i*2+1];
6739 // This word of the result is all undef, skip it.
6740 if (Elt0 < 0 && Elt1 < 0)
6743 // This word of the result is already in the correct place, skip it.
6744 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6747 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6748 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6751 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6752 // using a single extract together, load it and store it.
6753 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6754 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6755 DAG.getIntPtrConstant(Elt1 / 2));
6756 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6757 DAG.getIntPtrConstant(i));
6761 // If Elt1 is defined, extract it from the appropriate source. If the
6762 // source byte is not also odd, shift the extracted word left 8 bits
6763 // otherwise clear the bottom 8 bits if we need to do an or.
6765 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6766 DAG.getIntPtrConstant(Elt1 / 2));
6767 if ((Elt1 & 1) == 0)
6768 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6770 TLI.getShiftAmountTy(InsElt.getValueType())));
6772 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6773 DAG.getConstant(0xFF00, MVT::i16));
6775 // If Elt0 is defined, extract it from the appropriate source. If the
6776 // source byte is not also even, shift the extracted word right 8 bits. If
6777 // Elt1 was also defined, OR the extracted values together before
6778 // inserting them in the result.
6780 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6781 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6782 if ((Elt0 & 1) != 0)
6783 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6785 TLI.getShiftAmountTy(InsElt0.getValueType())));
6787 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6788 DAG.getConstant(0x00FF, MVT::i16));
6789 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6792 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6793 DAG.getIntPtrConstant(i));
6795 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6798 // v32i8 shuffles - Translate to VPSHUFB if possible.
6800 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6801 const X86Subtarget *Subtarget,
6802 SelectionDAG &DAG) {
6803 MVT VT = SVOp->getSimpleValueType(0);
6804 SDValue V1 = SVOp->getOperand(0);
6805 SDValue V2 = SVOp->getOperand(1);
6807 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6809 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6810 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6811 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6813 // VPSHUFB may be generated if
6814 // (1) one of input vector is undefined or zeroinitializer.
6815 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6816 // And (2) the mask indexes don't cross the 128-bit lane.
6817 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6818 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6821 if (V1IsAllZero && !V2IsAllZero) {
6822 CommuteVectorShuffleMask(MaskVals, 32);
6825 return getPSHUFB(MaskVals, V1, dl, DAG);
6828 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6829 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6830 /// done when every pair / quad of shuffle mask elements point to elements in
6831 /// the right sequence. e.g.
6832 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6834 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6835 SelectionDAG &DAG) {
6836 MVT VT = SVOp->getSimpleValueType(0);
6838 unsigned NumElems = VT.getVectorNumElements();
6841 switch (VT.SimpleTy) {
6842 default: llvm_unreachable("Unexpected!");
6843 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6844 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6845 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6846 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6847 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6848 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6851 SmallVector<int, 8> MaskVec;
6852 for (unsigned i = 0; i != NumElems; i += Scale) {
6854 for (unsigned j = 0; j != Scale; ++j) {
6855 int EltIdx = SVOp->getMaskElt(i+j);
6859 StartIdx = (EltIdx / Scale);
6860 if (EltIdx != (int)(StartIdx*Scale + j))
6863 MaskVec.push_back(StartIdx);
6866 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6867 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6868 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6871 /// getVZextMovL - Return a zero-extending vector move low node.
6873 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6874 SDValue SrcOp, SelectionDAG &DAG,
6875 const X86Subtarget *Subtarget, SDLoc dl) {
6876 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6877 LoadSDNode *LD = nullptr;
6878 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6879 LD = dyn_cast<LoadSDNode>(SrcOp);
6881 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6883 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6884 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6885 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6886 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6887 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6889 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6890 return DAG.getNode(ISD::BITCAST, dl, VT,
6891 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6892 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6900 return DAG.getNode(ISD::BITCAST, dl, VT,
6901 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6902 DAG.getNode(ISD::BITCAST, dl,
6906 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6907 /// which could not be matched by any known target speficic shuffle
6909 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6911 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6912 if (NewOp.getNode())
6915 MVT VT = SVOp->getSimpleValueType(0);
6917 unsigned NumElems = VT.getVectorNumElements();
6918 unsigned NumLaneElems = NumElems / 2;
6921 MVT EltVT = VT.getVectorElementType();
6922 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6925 SmallVector<int, 16> Mask;
6926 for (unsigned l = 0; l < 2; ++l) {
6927 // Build a shuffle mask for the output, discovering on the fly which
6928 // input vectors to use as shuffle operands (recorded in InputUsed).
6929 // If building a suitable shuffle vector proves too hard, then bail
6930 // out with UseBuildVector set.
6931 bool UseBuildVector = false;
6932 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6933 unsigned LaneStart = l * NumLaneElems;
6934 for (unsigned i = 0; i != NumLaneElems; ++i) {
6935 // The mask element. This indexes into the input.
6936 int Idx = SVOp->getMaskElt(i+LaneStart);
6938 // the mask element does not index into any input vector.
6943 // The input vector this mask element indexes into.
6944 int Input = Idx / NumLaneElems;
6946 // Turn the index into an offset from the start of the input vector.
6947 Idx -= Input * NumLaneElems;
6949 // Find or create a shuffle vector operand to hold this input.
6951 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6952 if (InputUsed[OpNo] == Input)
6953 // This input vector is already an operand.
6955 if (InputUsed[OpNo] < 0) {
6956 // Create a new operand for this input vector.
6957 InputUsed[OpNo] = Input;
6962 if (OpNo >= array_lengthof(InputUsed)) {
6963 // More than two input vectors used! Give up on trying to create a
6964 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6965 UseBuildVector = true;
6969 // Add the mask index for the new shuffle vector.
6970 Mask.push_back(Idx + OpNo * NumLaneElems);
6973 if (UseBuildVector) {
6974 SmallVector<SDValue, 16> SVOps;
6975 for (unsigned i = 0; i != NumLaneElems; ++i) {
6976 // The mask element. This indexes into the input.
6977 int Idx = SVOp->getMaskElt(i+LaneStart);
6979 SVOps.push_back(DAG.getUNDEF(EltVT));
6983 // The input vector this mask element indexes into.
6984 int Input = Idx / NumElems;
6986 // Turn the index into an offset from the start of the input vector.
6987 Idx -= Input * NumElems;
6989 // Extract the vector element by hand.
6990 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6991 SVOp->getOperand(Input),
6992 DAG.getIntPtrConstant(Idx)));
6995 // Construct the output using a BUILD_VECTOR.
6996 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
6997 } else if (InputUsed[0] < 0) {
6998 // No input vectors were used! The result is undefined.
6999 Output[l] = DAG.getUNDEF(NVT);
7001 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7002 (InputUsed[0] % 2) * NumLaneElems,
7004 // If only one input was used, use an undefined vector for the other.
7005 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7006 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7007 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7008 // At least one input vector was used. Create a new shuffle vector.
7009 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7015 // Concatenate the result back
7016 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7019 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7020 /// 4 elements, and match them with several different shuffle types.
7022 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7023 SDValue V1 = SVOp->getOperand(0);
7024 SDValue V2 = SVOp->getOperand(1);
7026 MVT VT = SVOp->getSimpleValueType(0);
7028 assert(VT.is128BitVector() && "Unsupported vector size");
7030 std::pair<int, int> Locs[4];
7031 int Mask1[] = { -1, -1, -1, -1 };
7032 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7036 for (unsigned i = 0; i != 4; ++i) {
7037 int Idx = PermMask[i];
7039 Locs[i] = std::make_pair(-1, -1);
7041 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7043 Locs[i] = std::make_pair(0, NumLo);
7047 Locs[i] = std::make_pair(1, NumHi);
7049 Mask1[2+NumHi] = Idx;
7055 if (NumLo <= 2 && NumHi <= 2) {
7056 // If no more than two elements come from either vector. This can be
7057 // implemented with two shuffles. First shuffle gather the elements.
7058 // The second shuffle, which takes the first shuffle as both of its
7059 // vector operands, put the elements into the right order.
7060 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7062 int Mask2[] = { -1, -1, -1, -1 };
7064 for (unsigned i = 0; i != 4; ++i)
7065 if (Locs[i].first != -1) {
7066 unsigned Idx = (i < 2) ? 0 : 4;
7067 Idx += Locs[i].first * 2 + Locs[i].second;
7071 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7074 if (NumLo == 3 || NumHi == 3) {
7075 // Otherwise, we must have three elements from one vector, call it X, and
7076 // one element from the other, call it Y. First, use a shufps to build an
7077 // intermediate vector with the one element from Y and the element from X
7078 // that will be in the same half in the final destination (the indexes don't
7079 // matter). Then, use a shufps to build the final vector, taking the half
7080 // containing the element from Y from the intermediate, and the other half
7083 // Normalize it so the 3 elements come from V1.
7084 CommuteVectorShuffleMask(PermMask, 4);
7088 // Find the element from V2.
7090 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7091 int Val = PermMask[HiIndex];
7098 Mask1[0] = PermMask[HiIndex];
7100 Mask1[2] = PermMask[HiIndex^1];
7102 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7105 Mask1[0] = PermMask[0];
7106 Mask1[1] = PermMask[1];
7107 Mask1[2] = HiIndex & 1 ? 6 : 4;
7108 Mask1[3] = HiIndex & 1 ? 4 : 6;
7109 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7112 Mask1[0] = HiIndex & 1 ? 2 : 0;
7113 Mask1[1] = HiIndex & 1 ? 0 : 2;
7114 Mask1[2] = PermMask[2];
7115 Mask1[3] = PermMask[3];
7120 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7123 // Break it into (shuffle shuffle_hi, shuffle_lo).
7124 int LoMask[] = { -1, -1, -1, -1 };
7125 int HiMask[] = { -1, -1, -1, -1 };
7127 int *MaskPtr = LoMask;
7128 unsigned MaskIdx = 0;
7131 for (unsigned i = 0; i != 4; ++i) {
7138 int Idx = PermMask[i];
7140 Locs[i] = std::make_pair(-1, -1);
7141 } else if (Idx < 4) {
7142 Locs[i] = std::make_pair(MaskIdx, LoIdx);
7143 MaskPtr[LoIdx] = Idx;
7146 Locs[i] = std::make_pair(MaskIdx, HiIdx);
7147 MaskPtr[HiIdx] = Idx;
7152 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7153 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7154 int MaskOps[] = { -1, -1, -1, -1 };
7155 for (unsigned i = 0; i != 4; ++i)
7156 if (Locs[i].first != -1)
7157 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7158 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7161 static bool MayFoldVectorLoad(SDValue V) {
7162 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7163 V = V.getOperand(0);
7165 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7166 V = V.getOperand(0);
7167 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7168 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7169 // BUILD_VECTOR (load), undef
7170 V = V.getOperand(0);
7172 return MayFoldLoad(V);
7176 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7177 MVT VT = Op.getSimpleValueType();
7179 // Canonizalize to v2f64.
7180 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7181 return DAG.getNode(ISD::BITCAST, dl, VT,
7182 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7187 SDValue getMOVLowToHigh(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::v2i64 && "unsupported shuffle type");
7195 if (HasSSE2 && VT == MVT::v2f64)
7196 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7198 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7199 return DAG.getNode(ISD::BITCAST, dl, VT,
7200 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7201 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7202 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7206 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7207 SDValue V1 = Op.getOperand(0);
7208 SDValue V2 = Op.getOperand(1);
7209 MVT VT = Op.getSimpleValueType();
7211 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7212 "unsupported shuffle type");
7214 if (V2.getOpcode() == ISD::UNDEF)
7218 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7222 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7223 SDValue V1 = Op.getOperand(0);
7224 SDValue V2 = Op.getOperand(1);
7225 MVT VT = Op.getSimpleValueType();
7226 unsigned NumElems = VT.getVectorNumElements();
7228 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7229 // operand of these instructions is only memory, so check if there's a
7230 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7232 bool CanFoldLoad = false;
7234 // Trivial case, when V2 comes from a load.
7235 if (MayFoldVectorLoad(V2))
7238 // When V1 is a load, it can be folded later into a store in isel, example:
7239 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7241 // (MOVLPSmr addr:$src1, VR128:$src2)
7242 // So, recognize this potential and also use MOVLPS or MOVLPD
7243 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7246 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7248 if (HasSSE2 && NumElems == 2)
7249 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7252 // If we don't care about the second element, proceed to use movss.
7253 if (SVOp->getMaskElt(1) != -1)
7254 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7257 // movl and movlp will both match v2i64, but v2i64 is never matched by
7258 // movl earlier because we make it strict to avoid messing with the movlp load
7259 // folding logic (see the code above getMOVLP call). Match it here then,
7260 // this is horrible, but will stay like this until we move all shuffle
7261 // matching to x86 specific nodes. Note that for the 1st condition all
7262 // types are matched with movsd.
7264 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7265 // as to remove this logic from here, as much as possible
7266 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7267 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7268 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7271 assert(VT != MVT::v4i32 && "unsupported shuffle type");
7273 // Invert the operand order and use SHUFPS to match it.
7274 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7275 getShuffleSHUFImmediate(SVOp), DAG);
7278 // It is only safe to call this function if isINSERTPSMask is true for
7279 // this shufflevector mask.
7280 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7281 SelectionDAG &DAG) {
7282 // Generate an insertps instruction when inserting an f32 from memory onto a
7283 // v4f32 or when copying a member from one v4f32 to another.
7284 // We also use it for transferring i32 from one register to another,
7285 // since it simply copies the same bits.
7286 // If we're transfering an i32 from memory to a specific element in a
7287 // register, we output a generic DAG that will match the PINSRD
7289 // TODO: Optimize for AVX cases too (VINSERTPS)
7290 MVT VT = SVOp->getSimpleValueType(0);
7291 MVT EVT = VT.getVectorElementType();
7292 SDValue V1 = SVOp->getOperand(0);
7293 SDValue V2 = SVOp->getOperand(1);
7294 auto Mask = SVOp->getMask();
7295 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7296 "unsupported vector type for insertps/pinsrd");
7298 int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7299 [](const int &i) { return i < 4; });
7307 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7308 [](const int &i) { return i < 4; }) -
7313 DestIndex = std::find_if(Mask.begin(), Mask.end(),
7314 [](const int &i) { return i >= 4; }) -
7318 if (MayFoldLoad(From)) {
7319 // Trivial case, when From comes from a load and is only used by the
7320 // shuffle. Make it use insertps from the vector that we need from that
7322 SDValue Addr = From.getOperand(1);
7324 DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7325 DAG.getConstant(DestIndex * EVT.getStoreSize(),
7326 Addr.getSimpleValueType()));
7328 LoadSDNode *Load = cast<LoadSDNode>(From);
7330 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7331 DAG.getMachineFunction().getMachineMemOperand(
7332 Load->getMemOperand(), 0, EVT.getStoreSize()));
7334 if (EVT == MVT::f32) {
7335 // Create this as a scalar to vector to match the instruction pattern.
7336 SDValue LoadScalarToVector =
7337 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7338 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7339 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7341 } else { // EVT == MVT::i32
7342 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7343 // instruction, to match the PINSRD instruction, which loads an i32 to a
7344 // certain vector element.
7345 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7346 DAG.getConstant(DestIndex, MVT::i32));
7350 // Vector-element-to-vector
7351 unsigned SrcIndex = Mask[DestIndex] % 4;
7352 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7353 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7356 // Reduce a vector shuffle to zext.
7357 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7358 SelectionDAG &DAG) {
7359 // PMOVZX is only available from SSE41.
7360 if (!Subtarget->hasSSE41())
7363 MVT VT = Op.getSimpleValueType();
7365 // Only AVX2 support 256-bit vector integer extending.
7366 if (!Subtarget->hasInt256() && VT.is256BitVector())
7369 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7371 SDValue V1 = Op.getOperand(0);
7372 SDValue V2 = Op.getOperand(1);
7373 unsigned NumElems = VT.getVectorNumElements();
7375 // Extending is an unary operation and the element type of the source vector
7376 // won't be equal to or larger than i64.
7377 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7378 VT.getVectorElementType() == MVT::i64)
7381 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7382 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7383 while ((1U << Shift) < NumElems) {
7384 if (SVOp->getMaskElt(1U << Shift) == 1)
7387 // The maximal ratio is 8, i.e. from i8 to i64.
7392 // Check the shuffle mask.
7393 unsigned Mask = (1U << Shift) - 1;
7394 for (unsigned i = 0; i != NumElems; ++i) {
7395 int EltIdx = SVOp->getMaskElt(i);
7396 if ((i & Mask) != 0 && EltIdx != -1)
7398 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7402 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7403 MVT NeVT = MVT::getIntegerVT(NBits);
7404 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7406 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7409 // Simplify the operand as it's prepared to be fed into shuffle.
7410 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7411 if (V1.getOpcode() == ISD::BITCAST &&
7412 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7413 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7414 V1.getOperand(0).getOperand(0)
7415 .getSimpleValueType().getSizeInBits() == SignificantBits) {
7416 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7417 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7418 ConstantSDNode *CIdx =
7419 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7420 // If it's foldable, i.e. normal load with single use, we will let code
7421 // selection to fold it. Otherwise, we will short the conversion sequence.
7422 if (CIdx && CIdx->getZExtValue() == 0 &&
7423 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7424 MVT FullVT = V.getSimpleValueType();
7425 MVT V1VT = V1.getSimpleValueType();
7426 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7427 // The "ext_vec_elt" node is wider than the result node.
7428 // In this case we should extract subvector from V.
7429 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7430 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7431 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7432 FullVT.getVectorNumElements()/Ratio);
7433 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7434 DAG.getIntPtrConstant(0));
7436 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7440 return DAG.getNode(ISD::BITCAST, DL, VT,
7441 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7445 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7446 SelectionDAG &DAG) {
7447 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7448 MVT VT = Op.getSimpleValueType();
7450 SDValue V1 = Op.getOperand(0);
7451 SDValue V2 = Op.getOperand(1);
7453 if (isZeroShuffle(SVOp))
7454 return getZeroVector(VT, Subtarget, DAG, dl);
7456 // Handle splat operations
7457 if (SVOp->isSplat()) {
7458 // Use vbroadcast whenever the splat comes from a foldable load
7459 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7460 if (Broadcast.getNode())
7464 // Check integer expanding shuffles.
7465 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7466 if (NewOp.getNode())
7469 // If the shuffle can be profitably rewritten as a narrower shuffle, then
7471 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
7472 VT == MVT::v16i16 || VT == MVT::v32i8) {
7473 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7474 if (NewOp.getNode())
7475 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7476 } else if ((VT == MVT::v4i32 ||
7477 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7478 // FIXME: Figure out a cleaner way to do this.
7479 // Try to make use of movq to zero out the top part.
7480 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7481 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7482 if (NewOp.getNode()) {
7483 MVT NewVT = NewOp.getSimpleValueType();
7484 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7485 NewVT, true, false))
7486 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7487 DAG, Subtarget, dl);
7489 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7490 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7491 if (NewOp.getNode()) {
7492 MVT NewVT = NewOp.getSimpleValueType();
7493 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7494 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7495 DAG, Subtarget, dl);
7503 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7504 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7505 SDValue V1 = Op.getOperand(0);
7506 SDValue V2 = Op.getOperand(1);
7507 MVT VT = Op.getSimpleValueType();
7509 unsigned NumElems = VT.getVectorNumElements();
7510 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7511 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7512 bool V1IsSplat = false;
7513 bool V2IsSplat = false;
7514 bool HasSSE2 = Subtarget->hasSSE2();
7515 bool HasFp256 = Subtarget->hasFp256();
7516 bool HasInt256 = Subtarget->hasInt256();
7517 MachineFunction &MF = DAG.getMachineFunction();
7518 bool OptForSize = MF.getFunction()->getAttributes().
7519 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7521 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7523 if (V1IsUndef && V2IsUndef)
7524 return DAG.getUNDEF(VT);
7526 // When we create a shuffle node we put the UNDEF node to second operand,
7527 // but in some cases the first operand may be transformed to UNDEF.
7528 // In this case we should just commute the node.
7530 return CommuteVectorShuffle(SVOp, DAG);
7532 // Vector shuffle lowering takes 3 steps:
7534 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7535 // narrowing and commutation of operands should be handled.
7536 // 2) Matching of shuffles with known shuffle masks to x86 target specific
7538 // 3) Rewriting of unmatched masks into new generic shuffle operations,
7539 // so the shuffle can be broken into other shuffles and the legalizer can
7540 // try the lowering again.
7542 // The general idea is that no vector_shuffle operation should be left to
7543 // be matched during isel, all of them must be converted to a target specific
7546 // Normalize the input vectors. Here splats, zeroed vectors, profitable
7547 // narrowing and commutation of operands should be handled. The actual code
7548 // doesn't include all of those, work in progress...
7549 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7550 if (NewOp.getNode())
7553 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7555 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7556 // unpckh_undef). Only use pshufd if speed is more important than size.
7557 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7558 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7559 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7560 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7562 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7563 V2IsUndef && MayFoldVectorLoad(V1))
7564 return getMOVDDup(Op, dl, V1, DAG);
7566 if (isMOVHLPS_v_undef_Mask(M, VT))
7567 return getMOVHighToLow(Op, dl, DAG);
7569 // Use to match splats
7570 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7571 (VT == MVT::v2f64 || VT == MVT::v2i64))
7572 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7574 if (isPSHUFDMask(M, VT)) {
7575 // The actual implementation will match the mask in the if above and then
7576 // during isel it can match several different instructions, not only pshufd
7577 // as its name says, sad but true, emulate the behavior for now...
7578 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7579 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7581 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7583 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7584 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7586 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7587 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7590 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7594 if (isPALIGNRMask(M, VT, Subtarget))
7595 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7596 getShufflePALIGNRImmediate(SVOp),
7599 // Check if this can be converted into a logical shift.
7600 bool isLeft = false;
7603 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7604 if (isShift && ShVal.hasOneUse()) {
7605 // If the shifted value has multiple uses, it may be cheaper to use
7606 // v_set0 + movlhps or movhlps, etc.
7607 MVT EltVT = VT.getVectorElementType();
7608 ShAmt *= EltVT.getSizeInBits();
7609 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7612 if (isMOVLMask(M, VT)) {
7613 if (ISD::isBuildVectorAllZeros(V1.getNode()))
7614 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7615 if (!isMOVLPMask(M, VT)) {
7616 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7617 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7619 if (VT == MVT::v4i32 || VT == MVT::v4f32)
7620 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7624 // FIXME: fold these into legal mask.
7625 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7626 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7628 if (isMOVHLPSMask(M, VT))
7629 return getMOVHighToLow(Op, dl, DAG);
7631 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7632 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7634 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7635 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7637 if (isMOVLPMask(M, VT))
7638 return getMOVLP(Op, dl, DAG, HasSSE2);
7640 if (ShouldXformToMOVHLPS(M, VT) ||
7641 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7642 return CommuteVectorShuffle(SVOp, DAG);
7645 // No better options. Use a vshldq / vsrldq.
7646 MVT EltVT = VT.getVectorElementType();
7647 ShAmt *= EltVT.getSizeInBits();
7648 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7651 bool Commuted = false;
7652 // FIXME: This should also accept a bitcast of a splat? Be careful, not
7653 // 1,1,1,1 -> v8i16 though.
7654 V1IsSplat = isSplatVector(V1.getNode());
7655 V2IsSplat = isSplatVector(V2.getNode());
7657 // Canonicalize the splat or undef, if present, to be on the RHS.
7658 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7659 CommuteVectorShuffleMask(M, NumElems);
7661 std::swap(V1IsSplat, V2IsSplat);
7665 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7666 // Shuffling low element of v1 into undef, just return v1.
7669 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7670 // the instruction selector will not match, so get a canonical MOVL with
7671 // swapped operands to undo the commute.
7672 return getMOVL(DAG, dl, VT, V2, V1);
7675 if (isUNPCKLMask(M, VT, HasInt256))
7676 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7678 if (isUNPCKHMask(M, VT, HasInt256))
7679 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7682 // Normalize mask so all entries that point to V2 points to its first
7683 // element then try to match unpck{h|l} again. If match, return a
7684 // new vector_shuffle with the corrected mask.p
7685 SmallVector<int, 8> NewMask(M.begin(), M.end());
7686 NormalizeMask(NewMask, NumElems);
7687 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7688 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7689 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7690 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7694 // Commute is back and try unpck* again.
7695 // FIXME: this seems wrong.
7696 CommuteVectorShuffleMask(M, NumElems);
7698 std::swap(V1IsSplat, V2IsSplat);
7700 if (isUNPCKLMask(M, VT, HasInt256))
7701 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7703 if (isUNPCKHMask(M, VT, HasInt256))
7704 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7707 // Normalize the node to match x86 shuffle ops if needed
7708 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7709 return CommuteVectorShuffle(SVOp, DAG);
7711 // The checks below are all present in isShuffleMaskLegal, but they are
7712 // inlined here right now to enable us to directly emit target specific
7713 // nodes, and remove one by one until they don't return Op anymore.
7715 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7716 SVOp->getSplatIndex() == 0 && V2IsUndef) {
7717 if (VT == MVT::v2f64 || VT == MVT::v2i64)
7718 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7721 if (isPSHUFHWMask(M, VT, HasInt256))
7722 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7723 getShufflePSHUFHWImmediate(SVOp),
7726 if (isPSHUFLWMask(M, VT, HasInt256))
7727 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7728 getShufflePSHUFLWImmediate(SVOp),
7731 if (isSHUFPMask(M, VT))
7732 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7733 getShuffleSHUFImmediate(SVOp), DAG);
7735 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7736 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7737 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7738 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7740 //===--------------------------------------------------------------------===//
7741 // Generate target specific nodes for 128 or 256-bit shuffles only
7742 // supported in the AVX instruction set.
7745 // Handle VMOVDDUPY permutations
7746 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7747 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7749 // Handle VPERMILPS/D* permutations
7750 if (isVPERMILPMask(M, VT)) {
7751 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7752 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7753 getShuffleSHUFImmediate(SVOp), DAG);
7754 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7755 getShuffleSHUFImmediate(SVOp), DAG);
7758 // Handle VPERM2F128/VPERM2I128 permutations
7759 if (isVPERM2X128Mask(M, VT, HasFp256))
7760 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7761 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7763 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7764 if (BlendOp.getNode())
7767 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7768 return getINSERTPS(SVOp, dl, DAG);
7771 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7772 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7774 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7775 VT.is512BitVector()) {
7776 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7777 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7778 SmallVector<SDValue, 16> permclMask;
7779 for (unsigned i = 0; i != NumElems; ++i) {
7780 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7783 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7785 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7786 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7787 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7788 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7789 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7792 //===--------------------------------------------------------------------===//
7793 // Since no target specific shuffle was selected for this generic one,
7794 // lower it into other known shuffles. FIXME: this isn't true yet, but
7795 // this is the plan.
7798 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7799 if (VT == MVT::v8i16) {
7800 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7801 if (NewOp.getNode())
7805 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7806 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7807 if (NewOp.getNode())
7811 if (VT == MVT::v16i8) {
7812 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7813 if (NewOp.getNode())
7817 if (VT == MVT::v32i8) {
7818 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7819 if (NewOp.getNode())
7823 // Handle all 128-bit wide vectors with 4 elements, and match them with
7824 // several different shuffle types.
7825 if (NumElems == 4 && VT.is128BitVector())
7826 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7828 // Handle general 256-bit shuffles
7829 if (VT.is256BitVector())
7830 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7835 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7836 MVT VT = Op.getSimpleValueType();
7839 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7842 if (VT.getSizeInBits() == 8) {
7843 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7844 Op.getOperand(0), Op.getOperand(1));
7845 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7846 DAG.getValueType(VT));
7847 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7850 if (VT.getSizeInBits() == 16) {
7851 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7852 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7854 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7855 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7856 DAG.getNode(ISD::BITCAST, dl,
7860 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7861 Op.getOperand(0), Op.getOperand(1));
7862 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7863 DAG.getValueType(VT));
7864 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7867 if (VT == MVT::f32) {
7868 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7869 // the result back to FR32 register. It's only worth matching if the
7870 // result has a single use which is a store or a bitcast to i32. And in
7871 // the case of a store, it's not worth it if the index is a constant 0,
7872 // because a MOVSSmr can be used instead, which is smaller and faster.
7873 if (!Op.hasOneUse())
7875 SDNode *User = *Op.getNode()->use_begin();
7876 if ((User->getOpcode() != ISD::STORE ||
7877 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7878 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7879 (User->getOpcode() != ISD::BITCAST ||
7880 User->getValueType(0) != MVT::i32))
7882 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7883 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7886 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7889 if (VT == MVT::i32 || VT == MVT::i64) {
7890 // ExtractPS/pextrq works with constant index.
7891 if (isa<ConstantSDNode>(Op.getOperand(1)))
7897 /// Extract one bit from mask vector, like v16i1 or v8i1.
7898 /// AVX-512 feature.
7900 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7901 SDValue Vec = Op.getOperand(0);
7903 MVT VecVT = Vec.getSimpleValueType();
7904 SDValue Idx = Op.getOperand(1);
7905 MVT EltVT = Op.getSimpleValueType();
7907 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7909 // variable index can't be handled in mask registers,
7910 // extend vector to VR512
7911 if (!isa<ConstantSDNode>(Idx)) {
7912 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
7913 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7914 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7915 ExtVT.getVectorElementType(), Ext, Idx);
7916 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7919 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7920 const TargetRegisterClass* rc = getRegClassFor(VecVT);
7921 unsigned MaxSift = rc->getSize()*8 - 1;
7922 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7923 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7924 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7925 DAG.getConstant(MaxSift, MVT::i8));
7926 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7927 DAG.getIntPtrConstant(0));
7931 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7932 SelectionDAG &DAG) const {
7934 SDValue Vec = Op.getOperand(0);
7935 MVT VecVT = Vec.getSimpleValueType();
7936 SDValue Idx = Op.getOperand(1);
7938 if (Op.getSimpleValueType() == MVT::i1)
7939 return ExtractBitFromMaskVector(Op, DAG);
7941 if (!isa<ConstantSDNode>(Idx)) {
7942 if (VecVT.is512BitVector() ||
7943 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7944 VecVT.getVectorElementType().getSizeInBits() == 32)) {
7947 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7948 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7949 MaskEltVT.getSizeInBits());
7951 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7952 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7953 getZeroVector(MaskVT, Subtarget, DAG, dl),
7954 Idx, DAG.getConstant(0, getPointerTy()));
7955 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7956 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7957 Perm, DAG.getConstant(0, getPointerTy()));
7962 // If this is a 256-bit vector result, first extract the 128-bit vector and
7963 // then extract the element from the 128-bit vector.
7964 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7966 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7967 // Get the 128-bit vector.
7968 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7969 MVT EltVT = VecVT.getVectorElementType();
7971 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7973 //if (IdxVal >= NumElems/2)
7974 // IdxVal -= NumElems/2;
7975 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7976 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7977 DAG.getConstant(IdxVal, MVT::i32));
7980 assert(VecVT.is128BitVector() && "Unexpected vector length");
7982 if (Subtarget->hasSSE41()) {
7983 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7988 MVT VT = Op.getSimpleValueType();
7989 // TODO: handle v16i8.
7990 if (VT.getSizeInBits() == 16) {
7991 SDValue Vec = Op.getOperand(0);
7992 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7994 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7995 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7996 DAG.getNode(ISD::BITCAST, dl,
7999 // Transform it so it match pextrw which produces a 32-bit result.
8000 MVT EltVT = MVT::i32;
8001 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8002 Op.getOperand(0), Op.getOperand(1));
8003 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8004 DAG.getValueType(VT));
8005 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8008 if (VT.getSizeInBits() == 32) {
8009 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8013 // SHUFPS the element to the lowest double word, then movss.
8014 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8015 MVT VVT = Op.getOperand(0).getSimpleValueType();
8016 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8017 DAG.getUNDEF(VVT), Mask);
8018 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8019 DAG.getIntPtrConstant(0));
8022 if (VT.getSizeInBits() == 64) {
8023 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8024 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8025 // to match extract_elt for f64.
8026 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8030 // UNPCKHPD the element to the lowest double word, then movsd.
8031 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8032 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8033 int Mask[2] = { 1, -1 };
8034 MVT VVT = Op.getOperand(0).getSimpleValueType();
8035 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8036 DAG.getUNDEF(VVT), Mask);
8037 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8038 DAG.getIntPtrConstant(0));
8044 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8045 MVT VT = Op.getSimpleValueType();
8046 MVT EltVT = VT.getVectorElementType();
8049 SDValue N0 = Op.getOperand(0);
8050 SDValue N1 = Op.getOperand(1);
8051 SDValue N2 = Op.getOperand(2);
8053 if (!VT.is128BitVector())
8056 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8057 isa<ConstantSDNode>(N2)) {
8059 if (VT == MVT::v8i16)
8060 Opc = X86ISD::PINSRW;
8061 else if (VT == MVT::v16i8)
8062 Opc = X86ISD::PINSRB;
8064 Opc = X86ISD::PINSRB;
8066 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8068 if (N1.getValueType() != MVT::i32)
8069 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8070 if (N2.getValueType() != MVT::i32)
8071 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8072 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8075 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8076 // Bits [7:6] of the constant are the source select. This will always be
8077 // zero here. The DAG Combiner may combine an extract_elt index into these
8078 // bits. For example (insert (extract, 3), 2) could be matched by putting
8079 // the '3' into bits [7:6] of X86ISD::INSERTPS.
8080 // Bits [5:4] of the constant are the destination select. This is the
8081 // value of the incoming immediate.
8082 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
8083 // combine either bitwise AND or insert of float 0.0 to set these bits.
8084 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8085 // Create this as a scalar to vector..
8086 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8087 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8090 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8091 // PINSR* works with constant index.
8097 /// Insert one bit to mask vector, like v16i1 or v8i1.
8098 /// AVX-512 feature.
8100 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8102 SDValue Vec = Op.getOperand(0);
8103 SDValue Elt = Op.getOperand(1);
8104 SDValue Idx = Op.getOperand(2);
8105 MVT VecVT = Vec.getSimpleValueType();
8107 if (!isa<ConstantSDNode>(Idx)) {
8108 // Non constant index. Extend source and destination,
8109 // insert element and then truncate the result.
8110 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
8111 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
8112 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
8113 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8114 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8115 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8118 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8119 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8120 if (Vec.getOpcode() == ISD::UNDEF)
8121 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8122 DAG.getConstant(IdxVal, MVT::i8));
8123 const TargetRegisterClass* rc = getRegClassFor(VecVT);
8124 unsigned MaxSift = rc->getSize()*8 - 1;
8125 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8126 DAG.getConstant(MaxSift, MVT::i8));
8127 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8128 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8129 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8132 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8133 MVT VT = Op.getSimpleValueType();
8134 MVT EltVT = VT.getVectorElementType();
8136 if (EltVT == MVT::i1)
8137 return InsertBitToMaskVector(Op, DAG);
8140 SDValue N0 = Op.getOperand(0);
8141 SDValue N1 = Op.getOperand(1);
8142 SDValue N2 = Op.getOperand(2);
8144 // If this is a 256-bit vector result, first extract the 128-bit vector,
8145 // insert the element into the extracted half and then place it back.
8146 if (VT.is256BitVector() || VT.is512BitVector()) {
8147 if (!isa<ConstantSDNode>(N2))
8150 // Get the desired 128-bit vector half.
8151 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8152 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8154 // Insert the element into the desired half.
8155 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8156 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8158 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8159 DAG.getConstant(IdxIn128, MVT::i32));
8161 // Insert the changed part back to the 256-bit vector
8162 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8165 if (Subtarget->hasSSE41())
8166 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8168 if (EltVT == MVT::i8)
8171 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8172 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8173 // as its second argument.
8174 if (N1.getValueType() != MVT::i32)
8175 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8176 if (N2.getValueType() != MVT::i32)
8177 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8178 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8183 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8185 MVT OpVT = Op.getSimpleValueType();
8187 // If this is a 256-bit vector result, first insert into a 128-bit
8188 // vector and then insert into the 256-bit vector.
8189 if (!OpVT.is128BitVector()) {
8190 // Insert into a 128-bit vector.
8191 unsigned SizeFactor = OpVT.getSizeInBits()/128;
8192 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8193 OpVT.getVectorNumElements() / SizeFactor);
8195 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8197 // Insert the 128-bit vector.
8198 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8201 if (OpVT == MVT::v1i64 &&
8202 Op.getOperand(0).getValueType() == MVT::i64)
8203 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8205 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8206 assert(OpVT.is128BitVector() && "Expected an SSE type!");
8207 return DAG.getNode(ISD::BITCAST, dl, OpVT,
8208 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8211 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
8212 // a simple subregister reference or explicit instructions to grab
8213 // upper bits of a vector.
8214 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8215 SelectionDAG &DAG) {
8217 SDValue In = Op.getOperand(0);
8218 SDValue Idx = Op.getOperand(1);
8219 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8220 MVT ResVT = Op.getSimpleValueType();
8221 MVT InVT = In.getSimpleValueType();
8223 if (Subtarget->hasFp256()) {
8224 if (ResVT.is128BitVector() &&
8225 (InVT.is256BitVector() || InVT.is512BitVector()) &&
8226 isa<ConstantSDNode>(Idx)) {
8227 return Extract128BitVector(In, IdxVal, DAG, dl);
8229 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8230 isa<ConstantSDNode>(Idx)) {
8231 return Extract256BitVector(In, IdxVal, DAG, dl);
8237 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
8238 // simple superregister reference or explicit instructions to insert
8239 // the upper bits of a vector.
8240 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8241 SelectionDAG &DAG) {
8242 if (Subtarget->hasFp256()) {
8243 SDLoc dl(Op.getNode());
8244 SDValue Vec = Op.getNode()->getOperand(0);
8245 SDValue SubVec = Op.getNode()->getOperand(1);
8246 SDValue Idx = Op.getNode()->getOperand(2);
8248 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8249 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8250 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8251 isa<ConstantSDNode>(Idx)) {
8252 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8253 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8256 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8257 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8258 isa<ConstantSDNode>(Idx)) {
8259 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8260 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8266 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8267 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8268 // one of the above mentioned nodes. It has to be wrapped because otherwise
8269 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8270 // be used to form addressing mode. These wrapped nodes will be selected
8273 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8274 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8276 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8278 unsigned char OpFlag = 0;
8279 unsigned WrapperKind = X86ISD::Wrapper;
8280 CodeModel::Model M = getTargetMachine().getCodeModel();
8282 if (Subtarget->isPICStyleRIPRel() &&
8283 (M == CodeModel::Small || M == CodeModel::Kernel))
8284 WrapperKind = X86ISD::WrapperRIP;
8285 else if (Subtarget->isPICStyleGOT())
8286 OpFlag = X86II::MO_GOTOFF;
8287 else if (Subtarget->isPICStyleStubPIC())
8288 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8290 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8292 CP->getOffset(), OpFlag);
8294 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8295 // With PIC, the address is actually $g + Offset.
8297 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8298 DAG.getNode(X86ISD::GlobalBaseReg,
8299 SDLoc(), getPointerTy()),
8306 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8307 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8309 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8311 unsigned char OpFlag = 0;
8312 unsigned WrapperKind = X86ISD::Wrapper;
8313 CodeModel::Model M = getTargetMachine().getCodeModel();
8315 if (Subtarget->isPICStyleRIPRel() &&
8316 (M == CodeModel::Small || M == CodeModel::Kernel))
8317 WrapperKind = X86ISD::WrapperRIP;
8318 else if (Subtarget->isPICStyleGOT())
8319 OpFlag = X86II::MO_GOTOFF;
8320 else if (Subtarget->isPICStyleStubPIC())
8321 OpFlag = X86II::MO_PIC_BASE_OFFSET;
8323 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8326 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8328 // With PIC, the address is actually $g + Offset.
8330 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8331 DAG.getNode(X86ISD::GlobalBaseReg,
8332 SDLoc(), getPointerTy()),
8339 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8340 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8342 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8344 unsigned char OpFlag = 0;
8345 unsigned WrapperKind = X86ISD::Wrapper;
8346 CodeModel::Model M = getTargetMachine().getCodeModel();
8348 if (Subtarget->isPICStyleRIPRel() &&
8349 (M == CodeModel::Small || M == CodeModel::Kernel)) {
8350 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8351 OpFlag = X86II::MO_GOTPCREL;
8352 WrapperKind = X86ISD::WrapperRIP;
8353 } else if (Subtarget->isPICStyleGOT()) {
8354 OpFlag = X86II::MO_GOT;
8355 } else if (Subtarget->isPICStyleStubPIC()) {
8356 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8357 } else if (Subtarget->isPICStyleStubNoDynamic()) {
8358 OpFlag = X86II::MO_DARWIN_NONLAZY;
8361 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8364 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8366 // With PIC, the address is actually $g + Offset.
8367 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8368 !Subtarget->is64Bit()) {
8369 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8370 DAG.getNode(X86ISD::GlobalBaseReg,
8371 SDLoc(), getPointerTy()),
8375 // For symbols that require a load from a stub to get the address, emit the
8377 if (isGlobalStubReference(OpFlag))
8378 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8379 MachinePointerInfo::getGOT(), false, false, false, 0);
8385 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8386 // Create the TargetBlockAddressAddress node.
8387 unsigned char OpFlags =
8388 Subtarget->ClassifyBlockAddressReference();
8389 CodeModel::Model M = getTargetMachine().getCodeModel();
8390 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8391 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8393 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8396 if (Subtarget->isPICStyleRIPRel() &&
8397 (M == CodeModel::Small || M == CodeModel::Kernel))
8398 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8400 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8402 // With PIC, the address is actually $g + Offset.
8403 if (isGlobalRelativeToPICBase(OpFlags)) {
8404 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8405 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8413 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8414 int64_t Offset, SelectionDAG &DAG) const {
8415 // Create the TargetGlobalAddress node, folding in the constant
8416 // offset if it is legal.
8417 unsigned char OpFlags =
8418 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8419 CodeModel::Model M = getTargetMachine().getCodeModel();
8421 if (OpFlags == X86II::MO_NO_FLAG &&
8422 X86::isOffsetSuitableForCodeModel(Offset, M)) {
8423 // A direct static reference to a global.
8424 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8427 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8430 if (Subtarget->isPICStyleRIPRel() &&
8431 (M == CodeModel::Small || M == CodeModel::Kernel))
8432 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8434 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8436 // With PIC, the address is actually $g + Offset.
8437 if (isGlobalRelativeToPICBase(OpFlags)) {
8438 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8439 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8443 // For globals that require a load from a stub to get the address, emit the
8445 if (isGlobalStubReference(OpFlags))
8446 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8447 MachinePointerInfo::getGOT(), false, false, false, 0);
8449 // If there was a non-zero offset that we didn't fold, create an explicit
8452 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8453 DAG.getConstant(Offset, getPointerTy()));
8459 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8460 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8461 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8462 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8466 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8467 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8468 unsigned char OperandFlags, bool LocalDynamic = false) {
8469 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8470 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8472 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8473 GA->getValueType(0),
8477 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8481 SDValue Ops[] = { Chain, TGA, *InFlag };
8482 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8484 SDValue Ops[] = { Chain, TGA };
8485 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8488 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8489 MFI->setAdjustsStack(true);
8491 SDValue Flag = Chain.getValue(1);
8492 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8495 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8497 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8500 SDLoc dl(GA); // ? function entry point might be better
8501 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8502 DAG.getNode(X86ISD::GlobalBaseReg,
8503 SDLoc(), PtrVT), InFlag);
8504 InFlag = Chain.getValue(1);
8506 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8509 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8511 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8513 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8514 X86::RAX, X86II::MO_TLSGD);
8517 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8523 // Get the start address of the TLS block for this module.
8524 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8525 .getInfo<X86MachineFunctionInfo>();
8526 MFI->incNumLocalDynamicTLSAccesses();
8530 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8531 X86II::MO_TLSLD, /*LocalDynamic=*/true);
8534 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8535 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8536 InFlag = Chain.getValue(1);
8537 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8538 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8541 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8545 unsigned char OperandFlags = X86II::MO_DTPOFF;
8546 unsigned WrapperKind = X86ISD::Wrapper;
8547 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8548 GA->getValueType(0),
8549 GA->getOffset(), OperandFlags);
8550 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8552 // Add x@dtpoff with the base.
8553 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8556 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8557 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8558 const EVT PtrVT, TLSModel::Model model,
8559 bool is64Bit, bool isPIC) {
8562 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8563 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8564 is64Bit ? 257 : 256));
8566 SDValue ThreadPointer =
8567 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8568 MachinePointerInfo(Ptr), false, false, false, 0);
8570 unsigned char OperandFlags = 0;
8571 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
8573 unsigned WrapperKind = X86ISD::Wrapper;
8574 if (model == TLSModel::LocalExec) {
8575 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8576 } else if (model == TLSModel::InitialExec) {
8578 OperandFlags = X86II::MO_GOTTPOFF;
8579 WrapperKind = X86ISD::WrapperRIP;
8581 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8584 llvm_unreachable("Unexpected model");
8587 // emit "addl x@ntpoff,%eax" (local exec)
8588 // or "addl x@indntpoff,%eax" (initial exec)
8589 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8591 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8592 GA->getOffset(), OperandFlags);
8593 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8595 if (model == TLSModel::InitialExec) {
8596 if (isPIC && !is64Bit) {
8597 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8598 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8602 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8603 MachinePointerInfo::getGOT(), false, false, false, 0);
8606 // The address of the thread local variable is the add of the thread
8607 // pointer with the offset of the variable.
8608 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8612 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8614 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8615 const GlobalValue *GV = GA->getGlobal();
8617 if (Subtarget->isTargetELF()) {
8618 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8621 case TLSModel::GeneralDynamic:
8622 if (Subtarget->is64Bit())
8623 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8624 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8625 case TLSModel::LocalDynamic:
8626 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8627 Subtarget->is64Bit());
8628 case TLSModel::InitialExec:
8629 case TLSModel::LocalExec:
8630 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8631 Subtarget->is64Bit(),
8632 getTargetMachine().getRelocationModel() == Reloc::PIC_);
8634 llvm_unreachable("Unknown TLS model.");
8637 if (Subtarget->isTargetDarwin()) {
8638 // Darwin only has one model of TLS. Lower to that.
8639 unsigned char OpFlag = 0;
8640 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8641 X86ISD::WrapperRIP : X86ISD::Wrapper;
8643 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8645 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8646 !Subtarget->is64Bit();
8648 OpFlag = X86II::MO_TLVP_PIC_BASE;
8650 OpFlag = X86II::MO_TLVP;
8652 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8653 GA->getValueType(0),
8654 GA->getOffset(), OpFlag);
8655 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8657 // With PIC32, the address is actually $g + Offset.
8659 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8660 DAG.getNode(X86ISD::GlobalBaseReg,
8661 SDLoc(), getPointerTy()),
8664 // Lowering the machine isd will make sure everything is in the right
8666 SDValue Chain = DAG.getEntryNode();
8667 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8668 SDValue Args[] = { Chain, Offset };
8669 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8671 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8672 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8673 MFI->setAdjustsStack(true);
8675 // And our return value (tls address) is in the standard call return value
8677 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8678 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8682 if (Subtarget->isTargetKnownWindowsMSVC() ||
8683 Subtarget->isTargetWindowsGNU()) {
8684 // Just use the implicit TLS architecture
8685 // Need to generate someting similar to:
8686 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8688 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
8689 // mov rcx, qword [rdx+rcx*8]
8690 // mov eax, .tls$:tlsvar
8691 // [rax+rcx] contains the address
8692 // Windows 64bit: gs:0x58
8693 // Windows 32bit: fs:__tls_array
8695 // If GV is an alias then use the aliasee for determining
8696 // thread-localness.
8697 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8698 GV = GA->getAliasedGlobal();
8700 SDValue Chain = DAG.getEntryNode();
8702 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8703 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8704 // use its literal value of 0x2C.
8705 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8706 ? Type::getInt8PtrTy(*DAG.getContext(),
8708 : Type::getInt32PtrTy(*DAG.getContext(),
8712 Subtarget->is64Bit()
8713 ? DAG.getIntPtrConstant(0x58)
8714 : (Subtarget->isTargetWindowsGNU()
8715 ? DAG.getIntPtrConstant(0x2C)
8716 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8718 SDValue ThreadPointer =
8719 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8720 MachinePointerInfo(Ptr), false, false, false, 0);
8722 // Load the _tls_index variable
8723 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8724 if (Subtarget->is64Bit())
8725 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8726 IDX, MachinePointerInfo(), MVT::i32,
8729 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8730 false, false, false, 0);
8732 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8734 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8736 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8737 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8738 false, false, false, 0);
8740 // Get the offset of start of .tls section
8741 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8742 GA->getValueType(0),
8743 GA->getOffset(), X86II::MO_SECREL);
8744 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8746 // The address of the thread local variable is the add of the thread
8747 // pointer with the offset of the variable.
8748 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8751 llvm_unreachable("TLS not implemented for this target.");
8754 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8755 /// and take a 2 x i32 value to shift plus a shift amount.
8756 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8757 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8758 MVT VT = Op.getSimpleValueType();
8759 unsigned VTBits = VT.getSizeInBits();
8761 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8762 SDValue ShOpLo = Op.getOperand(0);
8763 SDValue ShOpHi = Op.getOperand(1);
8764 SDValue ShAmt = Op.getOperand(2);
8765 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8766 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8768 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8769 DAG.getConstant(VTBits - 1, MVT::i8));
8770 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8771 DAG.getConstant(VTBits - 1, MVT::i8))
8772 : DAG.getConstant(0, VT);
8775 if (Op.getOpcode() == ISD::SHL_PARTS) {
8776 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8777 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8779 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8780 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8783 // If the shift amount is larger or equal than the width of a part we can't
8784 // rely on the results of shld/shrd. Insert a test and select the appropriate
8785 // values for large shift amounts.
8786 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8787 DAG.getConstant(VTBits, MVT::i8));
8788 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8789 AndNode, DAG.getConstant(0, MVT::i8));
8792 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8793 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8794 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8796 if (Op.getOpcode() == ISD::SHL_PARTS) {
8797 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8798 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8800 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8801 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8804 SDValue Ops[2] = { Lo, Hi };
8805 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8808 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8809 SelectionDAG &DAG) const {
8810 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8812 if (SrcVT.isVector())
8815 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8816 "Unknown SINT_TO_FP to lower!");
8818 // These are really Legal; return the operand so the caller accepts it as
8820 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8822 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8823 Subtarget->is64Bit()) {
8828 unsigned Size = SrcVT.getSizeInBits()/8;
8829 MachineFunction &MF = DAG.getMachineFunction();
8830 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8831 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8832 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8834 MachinePointerInfo::getFixedStack(SSFI),
8836 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8839 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8841 SelectionDAG &DAG) const {
8845 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8847 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8849 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8851 unsigned ByteSize = SrcVT.getSizeInBits()/8;
8853 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8854 MachineMemOperand *MMO;
8856 int SSFI = FI->getIndex();
8858 DAG.getMachineFunction()
8859 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8860 MachineMemOperand::MOLoad, ByteSize, ByteSize);
8862 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8863 StackSlot = StackSlot.getOperand(1);
8865 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8866 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8868 Tys, Ops, array_lengthof(Ops),
8872 Chain = Result.getValue(1);
8873 SDValue InFlag = Result.getValue(2);
8875 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8876 // shouldn't be necessary except that RFP cannot be live across
8877 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8878 MachineFunction &MF = DAG.getMachineFunction();
8879 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8880 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8881 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8882 Tys = DAG.getVTList(MVT::Other);
8884 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8886 MachineMemOperand *MMO =
8887 DAG.getMachineFunction()
8888 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8889 MachineMemOperand::MOStore, SSFISize, SSFISize);
8891 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8892 Ops, array_lengthof(Ops),
8893 Op.getValueType(), MMO);
8894 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8895 MachinePointerInfo::getFixedStack(SSFI),
8896 false, false, false, 0);
8902 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8903 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8904 SelectionDAG &DAG) const {
8905 // This algorithm is not obvious. Here it is what we're trying to output:
8908 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8909 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8913 pshufd $0x4e, %xmm0, %xmm1
8919 LLVMContext *Context = DAG.getContext();
8921 // Build some magic constants.
8922 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8923 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8924 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8926 SmallVector<Constant*,2> CV1;
8928 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8929 APInt(64, 0x4330000000000000ULL))));
8931 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8932 APInt(64, 0x4530000000000000ULL))));
8933 Constant *C1 = ConstantVector::get(CV1);
8934 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8936 // Load the 64-bit value into an XMM register.
8937 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8939 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8940 MachinePointerInfo::getConstantPool(),
8941 false, false, false, 16);
8942 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8943 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8946 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8947 MachinePointerInfo::getConstantPool(),
8948 false, false, false, 16);
8949 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8950 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8953 if (Subtarget->hasSSE3()) {
8954 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8955 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8957 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8958 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8960 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8961 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8965 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8966 DAG.getIntPtrConstant(0));
8969 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8970 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8971 SelectionDAG &DAG) const {
8973 // FP constant to bias correct the final result.
8974 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8977 // Load the 32-bit value into an XMM register.
8978 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8981 // Zero out the upper parts of the register.
8982 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8984 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8985 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8986 DAG.getIntPtrConstant(0));
8988 // Or the load with the bias.
8989 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8990 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8991 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8993 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8994 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8995 MVT::v2f64, Bias)));
8996 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8997 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8998 DAG.getIntPtrConstant(0));
9000 // Subtract the bias.
9001 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9003 // Handle final rounding.
9004 EVT DestVT = Op.getValueType();
9006 if (DestVT.bitsLT(MVT::f64))
9007 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9008 DAG.getIntPtrConstant(0));
9009 if (DestVT.bitsGT(MVT::f64))
9010 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9012 // Handle final rounding.
9016 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9017 SelectionDAG &DAG) const {
9018 SDValue N0 = Op.getOperand(0);
9019 MVT SVT = N0.getSimpleValueType();
9022 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9023 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9024 "Custom UINT_TO_FP is not supported!");
9026 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9027 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9028 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9031 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9032 SelectionDAG &DAG) const {
9033 SDValue N0 = Op.getOperand(0);
9036 if (Op.getValueType().isVector())
9037 return lowerUINT_TO_FP_vec(Op, DAG);
9039 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9040 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9041 // the optimization here.
9042 if (DAG.SignBitIsZero(N0))
9043 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9045 MVT SrcVT = N0.getSimpleValueType();
9046 MVT DstVT = Op.getSimpleValueType();
9047 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9048 return LowerUINT_TO_FP_i64(Op, DAG);
9049 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9050 return LowerUINT_TO_FP_i32(Op, DAG);
9051 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9054 // Make a 64-bit buffer, and use it to build an FILD.
9055 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9056 if (SrcVT == MVT::i32) {
9057 SDValue WordOff = DAG.getConstant(4, getPointerTy());
9058 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9059 getPointerTy(), StackSlot, WordOff);
9060 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9061 StackSlot, MachinePointerInfo(),
9063 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9064 OffsetSlot, MachinePointerInfo(),
9066 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9070 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9071 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9072 StackSlot, MachinePointerInfo(),
9074 // For i64 source, we need to add the appropriate power of 2 if the input
9075 // was negative. This is the same as the optimization in
9076 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9077 // we must be careful to do the computation in x87 extended precision, not
9078 // in SSE. (The generic code can't know it's OK to do this, or how to.)
9079 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9080 MachineMemOperand *MMO =
9081 DAG.getMachineFunction()
9082 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9083 MachineMemOperand::MOLoad, 8, 8);
9085 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9086 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9087 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9088 array_lengthof(Ops), MVT::i64, MMO);
9090 APInt FF(32, 0x5F800000ULL);
9092 // Check whether the sign bit is set.
9093 SDValue SignSet = DAG.getSetCC(dl,
9094 getSetCCResultType(*DAG.getContext(), MVT::i64),
9095 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9098 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9099 SDValue FudgePtr = DAG.getConstantPool(
9100 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9103 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9104 SDValue Zero = DAG.getIntPtrConstant(0);
9105 SDValue Four = DAG.getIntPtrConstant(4);
9106 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9108 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9110 // Load the value out, extending it from f32 to f80.
9111 // FIXME: Avoid the extend by constructing the right constant pool?
9112 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9113 FudgePtr, MachinePointerInfo::getConstantPool(),
9114 MVT::f32, false, false, 4);
9115 // Extend everything to 80 bits to force it to be done on x87.
9116 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9117 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9120 std::pair<SDValue,SDValue>
9121 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9122 bool IsSigned, bool IsReplace) const {
9125 EVT DstTy = Op.getValueType();
9127 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9128 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9132 assert(DstTy.getSimpleVT() <= MVT::i64 &&
9133 DstTy.getSimpleVT() >= MVT::i16 &&
9134 "Unknown FP_TO_INT to lower!");
9136 // These are really Legal.
9137 if (DstTy == MVT::i32 &&
9138 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9139 return std::make_pair(SDValue(), SDValue());
9140 if (Subtarget->is64Bit() &&
9141 DstTy == MVT::i64 &&
9142 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9143 return std::make_pair(SDValue(), SDValue());
9145 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9146 // stack slot, or into the FTOL runtime function.
9147 MachineFunction &MF = DAG.getMachineFunction();
9148 unsigned MemSize = DstTy.getSizeInBits()/8;
9149 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9150 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9153 if (!IsSigned && isIntegerTypeFTOL(DstTy))
9154 Opc = X86ISD::WIN_FTOL;
9156 switch (DstTy.getSimpleVT().SimpleTy) {
9157 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9158 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9159 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9160 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9163 SDValue Chain = DAG.getEntryNode();
9164 SDValue Value = Op.getOperand(0);
9165 EVT TheVT = Op.getOperand(0).getValueType();
9166 // FIXME This causes a redundant load/store if the SSE-class value is already
9167 // in memory, such as if it is on the callstack.
9168 if (isScalarFPTypeInSSEReg(TheVT)) {
9169 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9170 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9171 MachinePointerInfo::getFixedStack(SSFI),
9173 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9175 Chain, StackSlot, DAG.getValueType(TheVT)
9178 MachineMemOperand *MMO =
9179 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9180 MachineMemOperand::MOLoad, MemSize, MemSize);
9181 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9182 array_lengthof(Ops), DstTy, MMO);
9183 Chain = Value.getValue(1);
9184 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9185 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9188 MachineMemOperand *MMO =
9189 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9190 MachineMemOperand::MOStore, MemSize, MemSize);
9192 if (Opc != X86ISD::WIN_FTOL) {
9193 // Build the FP_TO_INT*_IN_MEM
9194 SDValue Ops[] = { Chain, Value, StackSlot };
9195 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9196 Ops, array_lengthof(Ops), DstTy,
9198 return std::make_pair(FIST, StackSlot);
9200 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9201 DAG.getVTList(MVT::Other, MVT::Glue),
9203 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9204 MVT::i32, ftol.getValue(1));
9205 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9206 MVT::i32, eax.getValue(2));
9207 SDValue Ops[] = { eax, edx };
9208 SDValue pair = IsReplace
9209 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9210 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9211 return std::make_pair(pair, SDValue());
9215 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9216 const X86Subtarget *Subtarget) {
9217 MVT VT = Op->getSimpleValueType(0);
9218 SDValue In = Op->getOperand(0);
9219 MVT InVT = In.getSimpleValueType();
9222 // Optimize vectors in AVX mode:
9225 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
9226 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
9227 // Concat upper and lower parts.
9230 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
9231 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
9232 // Concat upper and lower parts.
9235 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9236 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9237 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9240 if (Subtarget->hasInt256())
9241 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9243 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9244 SDValue Undef = DAG.getUNDEF(InVT);
9245 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9246 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9247 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9249 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9250 VT.getVectorNumElements()/2);
9252 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9253 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9255 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9258 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9259 SelectionDAG &DAG) {
9260 MVT VT = Op->getSimpleValueType(0);
9261 SDValue In = Op->getOperand(0);
9262 MVT InVT = In.getSimpleValueType();
9264 unsigned int NumElts = VT.getVectorNumElements();
9265 if (NumElts != 8 && NumElts != 16)
9268 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9269 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9271 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9272 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9273 // Now we have only mask extension
9274 assert(InVT.getVectorElementType() == MVT::i1);
9275 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9276 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9277 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9278 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9279 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9280 MachinePointerInfo::getConstantPool(),
9281 false, false, false, Alignment);
9283 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9284 if (VT.is512BitVector())
9286 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9289 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9290 SelectionDAG &DAG) {
9291 if (Subtarget->hasFp256()) {
9292 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9300 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9301 SelectionDAG &DAG) {
9303 MVT VT = Op.getSimpleValueType();
9304 SDValue In = Op.getOperand(0);
9305 MVT SVT = In.getSimpleValueType();
9307 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9308 return LowerZERO_EXTEND_AVX512(Op, DAG);
9310 if (Subtarget->hasFp256()) {
9311 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9316 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9317 VT.getVectorNumElements() != SVT.getVectorNumElements());
9321 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9323 MVT VT = Op.getSimpleValueType();
9324 SDValue In = Op.getOperand(0);
9325 MVT InVT = In.getSimpleValueType();
9327 if (VT == MVT::i1) {
9328 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9329 "Invalid scalar TRUNCATE operation");
9330 if (InVT == MVT::i32)
9332 if (InVT.getSizeInBits() == 64)
9333 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9334 else if (InVT.getSizeInBits() < 32)
9335 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9336 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9338 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9339 "Invalid TRUNCATE operation");
9341 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9342 if (VT.getVectorElementType().getSizeInBits() >=8)
9343 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9345 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9346 unsigned NumElts = InVT.getVectorNumElements();
9347 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9348 if (InVT.getSizeInBits() < 512) {
9349 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9350 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9354 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9355 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9356 SDValue CP = DAG.getConstantPool(C, getPointerTy());
9357 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9358 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9359 MachinePointerInfo::getConstantPool(),
9360 false, false, false, Alignment);
9361 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9362 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9363 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9366 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9367 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9368 if (Subtarget->hasInt256()) {
9369 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9370 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9371 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9373 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9374 DAG.getIntPtrConstant(0));
9377 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9378 DAG.getIntPtrConstant(0));
9379 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9380 DAG.getIntPtrConstant(2));
9381 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9382 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9383 static const int ShufMask[] = {0, 2, 4, 6};
9384 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9387 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9388 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9389 if (Subtarget->hasInt256()) {
9390 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9392 SmallVector<SDValue,32> pshufbMask;
9393 for (unsigned i = 0; i < 2; ++i) {
9394 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9395 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9396 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9397 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9398 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9399 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9400 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9401 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9402 for (unsigned j = 0; j < 8; ++j)
9403 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9405 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9406 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9407 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9409 static const int ShufMask[] = {0, 2, -1, -1};
9410 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
9412 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9413 DAG.getIntPtrConstant(0));
9414 return DAG.getNode(ISD::BITCAST, DL, VT, In);
9417 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9418 DAG.getIntPtrConstant(0));
9420 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9421 DAG.getIntPtrConstant(4));
9423 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9424 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9427 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
9428 -1, -1, -1, -1, -1, -1, -1, -1};
9430 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9431 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9432 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9434 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9435 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9437 // The MOVLHPS Mask:
9438 static const int ShufMask2[] = {0, 1, 4, 5};
9439 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9440 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9443 // Handle truncation of V256 to V128 using shuffles.
9444 if (!VT.is128BitVector() || !InVT.is256BitVector())
9447 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9449 unsigned NumElems = VT.getVectorNumElements();
9450 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9452 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9453 // Prepare truncation shuffle mask
9454 for (unsigned i = 0; i != NumElems; ++i)
9456 SDValue V = DAG.getVectorShuffle(NVT, DL,
9457 DAG.getNode(ISD::BITCAST, DL, NVT, In),
9458 DAG.getUNDEF(NVT), &MaskVec[0]);
9459 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9460 DAG.getIntPtrConstant(0));
9463 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9464 SelectionDAG &DAG) const {
9465 assert(!Op.getSimpleValueType().isVector());
9467 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9468 /*IsSigned=*/ true, /*IsReplace=*/ false);
9469 SDValue FIST = Vals.first, StackSlot = Vals.second;
9470 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9471 if (!FIST.getNode()) return Op;
9473 if (StackSlot.getNode())
9475 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9476 FIST, StackSlot, MachinePointerInfo(),
9477 false, false, false, 0);
9479 // The node is the result.
9483 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9484 SelectionDAG &DAG) const {
9485 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9486 /*IsSigned=*/ false, /*IsReplace=*/ false);
9487 SDValue FIST = Vals.first, StackSlot = Vals.second;
9488 assert(FIST.getNode() && "Unexpected failure");
9490 if (StackSlot.getNode())
9492 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9493 FIST, StackSlot, MachinePointerInfo(),
9494 false, false, false, 0);
9496 // The node is the result.
9500 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9502 MVT VT = Op.getSimpleValueType();
9503 SDValue In = Op.getOperand(0);
9504 MVT SVT = In.getSimpleValueType();
9506 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9508 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9509 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9510 In, DAG.getUNDEF(SVT)));
9513 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9514 LLVMContext *Context = DAG.getContext();
9516 MVT VT = Op.getSimpleValueType();
9518 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9519 if (VT.isVector()) {
9520 EltVT = VT.getVectorElementType();
9521 NumElts = VT.getVectorNumElements();
9524 if (EltVT == MVT::f64)
9525 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9526 APInt(64, ~(1ULL << 63))));
9528 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9529 APInt(32, ~(1U << 31))));
9530 C = ConstantVector::getSplat(NumElts, C);
9531 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9532 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9533 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9534 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9535 MachinePointerInfo::getConstantPool(),
9536 false, false, false, Alignment);
9537 if (VT.isVector()) {
9538 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9539 return DAG.getNode(ISD::BITCAST, dl, VT,
9540 DAG.getNode(ISD::AND, dl, ANDVT,
9541 DAG.getNode(ISD::BITCAST, dl, ANDVT,
9543 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9545 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9548 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9549 LLVMContext *Context = DAG.getContext();
9551 MVT VT = Op.getSimpleValueType();
9553 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9554 if (VT.isVector()) {
9555 EltVT = VT.getVectorElementType();
9556 NumElts = VT.getVectorNumElements();
9559 if (EltVT == MVT::f64)
9560 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9561 APInt(64, 1ULL << 63)));
9563 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9564 APInt(32, 1U << 31)));
9565 C = ConstantVector::getSplat(NumElts, C);
9566 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9567 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9568 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9569 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9570 MachinePointerInfo::getConstantPool(),
9571 false, false, false, Alignment);
9572 if (VT.isVector()) {
9573 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9574 return DAG.getNode(ISD::BITCAST, dl, VT,
9575 DAG.getNode(ISD::XOR, dl, XORVT,
9576 DAG.getNode(ISD::BITCAST, dl, XORVT,
9578 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9581 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9584 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9585 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9586 LLVMContext *Context = DAG.getContext();
9587 SDValue Op0 = Op.getOperand(0);
9588 SDValue Op1 = Op.getOperand(1);
9590 MVT VT = Op.getSimpleValueType();
9591 MVT SrcVT = Op1.getSimpleValueType();
9593 // If second operand is smaller, extend it first.
9594 if (SrcVT.bitsLT(VT)) {
9595 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9598 // And if it is bigger, shrink it first.
9599 if (SrcVT.bitsGT(VT)) {
9600 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9604 // At this point the operands and the result should have the same
9605 // type, and that won't be f80 since that is not custom lowered.
9607 // First get the sign bit of second operand.
9608 SmallVector<Constant*,4> CV;
9609 if (SrcVT == MVT::f64) {
9610 const fltSemantics &Sem = APFloat::IEEEdouble;
9611 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9612 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9614 const fltSemantics &Sem = APFloat::IEEEsingle;
9615 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9616 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9617 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9618 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9620 Constant *C = ConstantVector::get(CV);
9621 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9622 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9623 MachinePointerInfo::getConstantPool(),
9624 false, false, false, 16);
9625 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9627 // Shift sign bit right or left if the two operands have different types.
9628 if (SrcVT.bitsGT(VT)) {
9629 // Op0 is MVT::f32, Op1 is MVT::f64.
9630 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9631 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9632 DAG.getConstant(32, MVT::i32));
9633 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9634 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9635 DAG.getIntPtrConstant(0));
9638 // Clear first operand sign bit.
9640 if (VT == MVT::f64) {
9641 const fltSemantics &Sem = APFloat::IEEEdouble;
9642 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9643 APInt(64, ~(1ULL << 63)))));
9644 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9646 const fltSemantics &Sem = APFloat::IEEEsingle;
9647 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9648 APInt(32, ~(1U << 31)))));
9649 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9650 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9651 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9653 C = ConstantVector::get(CV);
9654 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9655 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9656 MachinePointerInfo::getConstantPool(),
9657 false, false, false, 16);
9658 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9660 // Or the value with the sign bit.
9661 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9664 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9665 SDValue N0 = Op.getOperand(0);
9667 MVT VT = Op.getSimpleValueType();
9669 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9670 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9671 DAG.getConstant(1, VT));
9672 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9675 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9677 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9678 SelectionDAG &DAG) {
9679 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9681 if (!Subtarget->hasSSE41())
9684 if (!Op->hasOneUse())
9687 SDNode *N = Op.getNode();
9690 SmallVector<SDValue, 8> Opnds;
9691 DenseMap<SDValue, unsigned> VecInMap;
9692 SmallVector<SDValue, 8> VecIns;
9693 EVT VT = MVT::Other;
9695 // Recognize a special case where a vector is casted into wide integer to
9697 Opnds.push_back(N->getOperand(0));
9698 Opnds.push_back(N->getOperand(1));
9700 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9701 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9702 // BFS traverse all OR'd operands.
9703 if (I->getOpcode() == ISD::OR) {
9704 Opnds.push_back(I->getOperand(0));
9705 Opnds.push_back(I->getOperand(1));
9706 // Re-evaluate the number of nodes to be traversed.
9707 e += 2; // 2 more nodes (LHS and RHS) are pushed.
9711 // Quit if a non-EXTRACT_VECTOR_ELT
9712 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9715 // Quit if without a constant index.
9716 SDValue Idx = I->getOperand(1);
9717 if (!isa<ConstantSDNode>(Idx))
9720 SDValue ExtractedFromVec = I->getOperand(0);
9721 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9722 if (M == VecInMap.end()) {
9723 VT = ExtractedFromVec.getValueType();
9724 // Quit if not 128/256-bit vector.
9725 if (!VT.is128BitVector() && !VT.is256BitVector())
9727 // Quit if not the same type.
9728 if (VecInMap.begin() != VecInMap.end() &&
9729 VT != VecInMap.begin()->first.getValueType())
9731 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9732 VecIns.push_back(ExtractedFromVec);
9734 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9737 assert((VT.is128BitVector() || VT.is256BitVector()) &&
9738 "Not extracted from 128-/256-bit vector.");
9740 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9742 for (DenseMap<SDValue, unsigned>::const_iterator
9743 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9744 // Quit if not all elements are used.
9745 if (I->second != FullMask)
9749 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9751 // Cast all vectors into TestVT for PTEST.
9752 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9753 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9755 // If more than one full vectors are evaluated, OR them first before PTEST.
9756 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9757 // Each iteration will OR 2 nodes and append the result until there is only
9758 // 1 node left, i.e. the final OR'd value of all vectors.
9759 SDValue LHS = VecIns[Slot];
9760 SDValue RHS = VecIns[Slot + 1];
9761 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9764 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9765 VecIns.back(), VecIns.back());
9768 /// \brief return true if \c Op has a use that doesn't just read flags.
9769 static bool hasNonFlagsUse(SDValue Op) {
9770 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9773 unsigned UOpNo = UI.getOperandNo();
9774 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9775 // Look pass truncate.
9776 UOpNo = User->use_begin().getOperandNo();
9777 User = *User->use_begin();
9780 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9781 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9787 /// Emit nodes that will be selected as "test Op0,Op0", or something
9789 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9790 SelectionDAG &DAG) const {
9791 if (Op.getValueType() == MVT::i1)
9792 // KORTEST instruction should be selected
9793 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9794 DAG.getConstant(0, Op.getValueType()));
9796 // CF and OF aren't always set the way we want. Determine which
9797 // of these we need.
9798 bool NeedCF = false;
9799 bool NeedOF = false;
9802 case X86::COND_A: case X86::COND_AE:
9803 case X86::COND_B: case X86::COND_BE:
9806 case X86::COND_G: case X86::COND_GE:
9807 case X86::COND_L: case X86::COND_LE:
9808 case X86::COND_O: case X86::COND_NO:
9812 // See if we can use the EFLAGS value from the operand instead of
9813 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9814 // we prove that the arithmetic won't overflow, we can't use OF or CF.
9815 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9816 // Emit a CMP with 0, which is the TEST pattern.
9817 //if (Op.getValueType() == MVT::i1)
9818 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9819 // DAG.getConstant(0, MVT::i1));
9820 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9821 DAG.getConstant(0, Op.getValueType()));
9823 unsigned Opcode = 0;
9824 unsigned NumOperands = 0;
9826 // Truncate operations may prevent the merge of the SETCC instruction
9827 // and the arithmetic instruction before it. Attempt to truncate the operands
9828 // of the arithmetic instruction and use a reduced bit-width instruction.
9829 bool NeedTruncation = false;
9830 SDValue ArithOp = Op;
9831 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9832 SDValue Arith = Op->getOperand(0);
9833 // Both the trunc and the arithmetic op need to have one user each.
9834 if (Arith->hasOneUse())
9835 switch (Arith.getOpcode()) {
9842 NeedTruncation = true;
9848 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9849 // which may be the result of a CAST. We use the variable 'Op', which is the
9850 // non-casted variable when we check for possible users.
9851 switch (ArithOp.getOpcode()) {
9853 // Due to an isel shortcoming, be conservative if this add is likely to be
9854 // selected as part of a load-modify-store instruction. When the root node
9855 // in a match is a store, isel doesn't know how to remap non-chain non-flag
9856 // uses of other nodes in the match, such as the ADD in this case. This
9857 // leads to the ADD being left around and reselected, with the result being
9858 // two adds in the output. Alas, even if none our users are stores, that
9859 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
9860 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
9861 // climbing the DAG back to the root, and it doesn't seem to be worth the
9863 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9864 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9865 if (UI->getOpcode() != ISD::CopyToReg &&
9866 UI->getOpcode() != ISD::SETCC &&
9867 UI->getOpcode() != ISD::STORE)
9870 if (ConstantSDNode *C =
9871 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9872 // An add of one will be selected as an INC.
9873 if (C->getAPIntValue() == 1) {
9874 Opcode = X86ISD::INC;
9879 // An add of negative one (subtract of one) will be selected as a DEC.
9880 if (C->getAPIntValue().isAllOnesValue()) {
9881 Opcode = X86ISD::DEC;
9887 // Otherwise use a regular EFLAGS-setting add.
9888 Opcode = X86ISD::ADD;
9893 // If we have a constant logical shift that's only used in a comparison
9894 // against zero turn it into an equivalent AND. This allows turning it into
9895 // a TEST instruction later.
9896 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9897 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9898 EVT VT = Op.getValueType();
9899 unsigned BitWidth = VT.getSizeInBits();
9900 unsigned ShAmt = Op->getConstantOperandVal(1);
9901 if (ShAmt >= BitWidth) // Avoid undefined shifts.
9903 APInt Mask = ArithOp.getOpcode() == ISD::SRL
9904 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9905 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9906 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9908 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9909 DAG.getConstant(Mask, VT));
9910 DAG.ReplaceAllUsesWith(Op, New);
9916 // If the primary and result isn't used, don't bother using X86ISD::AND,
9917 // because a TEST instruction will be better.
9918 if (!hasNonFlagsUse(Op))
9924 // Due to the ISEL shortcoming noted above, be conservative if this op is
9925 // likely to be selected as part of a load-modify-store instruction.
9926 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9927 UE = Op.getNode()->use_end(); UI != UE; ++UI)
9928 if (UI->getOpcode() == ISD::STORE)
9931 // Otherwise use a regular EFLAGS-setting instruction.
9932 switch (ArithOp.getOpcode()) {
9933 default: llvm_unreachable("unexpected operator!");
9934 case ISD::SUB: Opcode = X86ISD::SUB; break;
9935 case ISD::XOR: Opcode = X86ISD::XOR; break;
9936 case ISD::AND: Opcode = X86ISD::AND; break;
9938 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9939 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9940 if (EFLAGS.getNode())
9943 Opcode = X86ISD::OR;
9957 return SDValue(Op.getNode(), 1);
9963 // If we found that truncation is beneficial, perform the truncation and
9965 if (NeedTruncation) {
9966 EVT VT = Op.getValueType();
9967 SDValue WideVal = Op->getOperand(0);
9968 EVT WideVT = WideVal.getValueType();
9969 unsigned ConvertedOp = 0;
9970 // Use a target machine opcode to prevent further DAGCombine
9971 // optimizations that may separate the arithmetic operations
9972 // from the setcc node.
9973 switch (WideVal.getOpcode()) {
9975 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9976 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9977 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9978 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9979 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9983 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9984 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9985 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9986 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9987 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9993 // Emit a CMP with 0, which is the TEST pattern.
9994 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9995 DAG.getConstant(0, Op.getValueType()));
9997 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9998 SmallVector<SDValue, 4> Ops;
9999 for (unsigned i = 0; i != NumOperands; ++i)
10000 Ops.push_back(Op.getOperand(i));
10002 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10003 DAG.ReplaceAllUsesWith(Op, New);
10004 return SDValue(New.getNode(), 1);
10007 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10009 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10010 SDLoc dl, SelectionDAG &DAG) const {
10011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10012 if (C->getAPIntValue() == 0)
10013 return EmitTest(Op0, X86CC, dl, DAG);
10015 if (Op0.getValueType() == MVT::i1)
10016 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10019 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10020 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10021 // Do the comparison at i32 if it's smaller, besides the Atom case.
10022 // This avoids subregister aliasing issues. Keep the smaller reference
10023 // if we're optimizing for size, however, as that'll allow better folding
10024 // of memory operations.
10025 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10026 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10027 AttributeSet::FunctionIndex, Attribute::MinSize) &&
10028 !Subtarget->isAtom()) {
10029 unsigned ExtendOp =
10030 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10031 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10032 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10034 // Use SUB instead of CMP to enable CSE between SUB and CMP.
10035 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10036 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10038 return SDValue(Sub.getNode(), 1);
10040 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10043 /// Convert a comparison if required by the subtarget.
10044 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10045 SelectionDAG &DAG) const {
10046 // If the subtarget does not support the FUCOMI instruction, floating-point
10047 // comparisons have to be converted.
10048 if (Subtarget->hasCMov() ||
10049 Cmp.getOpcode() != X86ISD::CMP ||
10050 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10051 !Cmp.getOperand(1).getValueType().isFloatingPoint())
10054 // The instruction selector will select an FUCOM instruction instead of
10055 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10056 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10057 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10059 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10060 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10061 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10062 DAG.getConstant(8, MVT::i8));
10063 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10064 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10067 static bool isAllOnes(SDValue V) {
10068 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10069 return C && C->isAllOnesValue();
10072 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10073 /// if it's possible.
10074 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10075 SDLoc dl, SelectionDAG &DAG) const {
10076 SDValue Op0 = And.getOperand(0);
10077 SDValue Op1 = And.getOperand(1);
10078 if (Op0.getOpcode() == ISD::TRUNCATE)
10079 Op0 = Op0.getOperand(0);
10080 if (Op1.getOpcode() == ISD::TRUNCATE)
10081 Op1 = Op1.getOperand(0);
10084 if (Op1.getOpcode() == ISD::SHL)
10085 std::swap(Op0, Op1);
10086 if (Op0.getOpcode() == ISD::SHL) {
10087 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10088 if (And00C->getZExtValue() == 1) {
10089 // If we looked past a truncate, check that it's only truncating away
10091 unsigned BitWidth = Op0.getValueSizeInBits();
10092 unsigned AndBitWidth = And.getValueSizeInBits();
10093 if (BitWidth > AndBitWidth) {
10095 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10096 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10100 RHS = Op0.getOperand(1);
10102 } else if (Op1.getOpcode() == ISD::Constant) {
10103 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10104 uint64_t AndRHSVal = AndRHS->getZExtValue();
10105 SDValue AndLHS = Op0;
10107 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10108 LHS = AndLHS.getOperand(0);
10109 RHS = AndLHS.getOperand(1);
10112 // Use BT if the immediate can't be encoded in a TEST instruction.
10113 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10115 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10119 if (LHS.getNode()) {
10120 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
10121 // instruction. Since the shift amount is in-range-or-undefined, we know
10122 // that doing a bittest on the i32 value is ok. We extend to i32 because
10123 // the encoding for the i16 version is larger than the i32 version.
10124 // Also promote i16 to i32 for performance / code size reason.
10125 if (LHS.getValueType() == MVT::i8 ||
10126 LHS.getValueType() == MVT::i16)
10127 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10129 // If the operand types disagree, extend the shift amount to match. Since
10130 // BT ignores high bits (like shifts) we can use anyextend.
10131 if (LHS.getValueType() != RHS.getValueType())
10132 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10134 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10135 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10136 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10137 DAG.getConstant(Cond, MVT::i8), BT);
10143 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10145 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10150 // SSE Condition code mapping:
10159 switch (SetCCOpcode) {
10160 default: llvm_unreachable("Unexpected SETCC condition");
10162 case ISD::SETEQ: SSECC = 0; break;
10164 case ISD::SETGT: Swap = true; // Fallthrough
10166 case ISD::SETOLT: SSECC = 1; break;
10168 case ISD::SETGE: Swap = true; // Fallthrough
10170 case ISD::SETOLE: SSECC = 2; break;
10171 case ISD::SETUO: SSECC = 3; break;
10173 case ISD::SETNE: SSECC = 4; break;
10174 case ISD::SETULE: Swap = true; // Fallthrough
10175 case ISD::SETUGE: SSECC = 5; break;
10176 case ISD::SETULT: Swap = true; // Fallthrough
10177 case ISD::SETUGT: SSECC = 6; break;
10178 case ISD::SETO: SSECC = 7; break;
10180 case ISD::SETONE: SSECC = 8; break;
10183 std::swap(Op0, Op1);
10188 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10189 // ones, and then concatenate the result back.
10190 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10191 MVT VT = Op.getSimpleValueType();
10193 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10194 "Unsupported value type for operation");
10196 unsigned NumElems = VT.getVectorNumElements();
10198 SDValue CC = Op.getOperand(2);
10200 // Extract the LHS vectors
10201 SDValue LHS = Op.getOperand(0);
10202 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10203 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10205 // Extract the RHS vectors
10206 SDValue RHS = Op.getOperand(1);
10207 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10208 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10210 // Issue the operation on the smaller types and concatenate the result back
10211 MVT EltVT = VT.getVectorElementType();
10212 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10213 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10214 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10215 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10218 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10219 const X86Subtarget *Subtarget) {
10220 SDValue Op0 = Op.getOperand(0);
10221 SDValue Op1 = Op.getOperand(1);
10222 SDValue CC = Op.getOperand(2);
10223 MVT VT = Op.getSimpleValueType();
10226 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10227 Op.getValueType().getScalarType() == MVT::i1 &&
10228 "Cannot set masked compare for this operation");
10230 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10232 bool Unsigned = false;
10235 switch (SetCCOpcode) {
10236 default: llvm_unreachable("Unexpected SETCC condition");
10237 case ISD::SETNE: SSECC = 4; break;
10238 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
10239 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10240 case ISD::SETLT: Swap = true; //fall-through
10241 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
10242 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10243 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10244 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
10245 case ISD::SETULE: Unsigned = true; //fall-through
10246 case ISD::SETLE: SSECC = 2; break;
10250 std::swap(Op0, Op1);
10252 return DAG.getNode(Opc, dl, VT, Op0, Op1);
10253 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10254 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10255 DAG.getConstant(SSECC, MVT::i8));
10258 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10259 /// operand \p Op1. If non-trivial (for example because it's not constant)
10260 /// return an empty value.
10261 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10263 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10267 MVT VT = Op1.getSimpleValueType();
10268 MVT EVT = VT.getVectorElementType();
10269 unsigned n = VT.getVectorNumElements();
10270 SmallVector<SDValue, 8> ULTOp1;
10272 for (unsigned i = 0; i < n; ++i) {
10273 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10274 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10277 // Avoid underflow.
10278 APInt Val = Elt->getAPIntValue();
10282 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10285 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10288 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10289 SelectionDAG &DAG) {
10290 SDValue Op0 = Op.getOperand(0);
10291 SDValue Op1 = Op.getOperand(1);
10292 SDValue CC = Op.getOperand(2);
10293 MVT VT = Op.getSimpleValueType();
10294 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10295 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10300 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10301 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10304 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10305 unsigned Opc = X86ISD::CMPP;
10306 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10307 assert(VT.getVectorNumElements() <= 16);
10308 Opc = X86ISD::CMPM;
10310 // In the two special cases we can't handle, emit two comparisons.
10313 unsigned CombineOpc;
10314 if (SetCCOpcode == ISD::SETUEQ) {
10315 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10317 assert(SetCCOpcode == ISD::SETONE);
10318 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10321 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10322 DAG.getConstant(CC0, MVT::i8));
10323 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10324 DAG.getConstant(CC1, MVT::i8));
10325 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10327 // Handle all other FP comparisons here.
10328 return DAG.getNode(Opc, dl, VT, Op0, Op1,
10329 DAG.getConstant(SSECC, MVT::i8));
10332 // Break 256-bit integer vector compare into smaller ones.
10333 if (VT.is256BitVector() && !Subtarget->hasInt256())
10334 return Lower256IntVSETCC(Op, DAG);
10336 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10337 EVT OpVT = Op1.getValueType();
10338 if (Subtarget->hasAVX512()) {
10339 if (Op1.getValueType().is512BitVector() ||
10340 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10341 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10343 // In AVX-512 architecture setcc returns mask with i1 elements,
10344 // But there is no compare instruction for i8 and i16 elements.
10345 // We are not talking about 512-bit operands in this case, these
10346 // types are illegal.
10348 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10349 OpVT.getVectorElementType().getSizeInBits() >= 8))
10350 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10351 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10354 // We are handling one of the integer comparisons here. Since SSE only has
10355 // GT and EQ comparisons for integer, swapping operands and multiple
10356 // operations may be required for some comparisons.
10358 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10359 bool Subus = false;
10361 switch (SetCCOpcode) {
10362 default: llvm_unreachable("Unexpected SETCC condition");
10363 case ISD::SETNE: Invert = true;
10364 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
10365 case ISD::SETLT: Swap = true;
10366 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
10367 case ISD::SETGE: Swap = true;
10368 case ISD::SETLE: Opc = X86ISD::PCMPGT;
10369 Invert = true; break;
10370 case ISD::SETULT: Swap = true;
10371 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10372 FlipSigns = true; break;
10373 case ISD::SETUGE: Swap = true;
10374 case ISD::SETULE: Opc = X86ISD::PCMPGT;
10375 FlipSigns = true; Invert = true; break;
10378 // Special case: Use min/max operations for SETULE/SETUGE
10379 MVT VET = VT.getVectorElementType();
10381 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10382 || (Subtarget->hasSSE2() && (VET == MVT::i8));
10385 switch (SetCCOpcode) {
10387 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10388 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10391 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10394 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10395 if (!MinMax && hasSubus) {
10396 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10398 // t = psubus Op0, Op1
10399 // pcmpeq t, <0..0>
10400 switch (SetCCOpcode) {
10402 case ISD::SETULT: {
10403 // If the comparison is against a constant we can turn this into a
10404 // setule. With psubus, setule does not require a swap. This is
10405 // beneficial because the constant in the register is no longer
10406 // destructed as the destination so it can be hoisted out of a loop.
10407 // Only do this pre-AVX since vpcmp* is no longer destructive.
10408 if (Subtarget->hasAVX())
10410 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10411 if (ULEOp1.getNode()) {
10413 Subus = true; Invert = false; Swap = false;
10417 // Psubus is better than flip-sign because it requires no inversion.
10418 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
10419 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10423 Opc = X86ISD::SUBUS;
10429 std::swap(Op0, Op1);
10431 // Check that the operation in question is available (most are plain SSE2,
10432 // but PCMPGTQ and PCMPEQQ have different requirements).
10433 if (VT == MVT::v2i64) {
10434 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10435 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10437 // First cast everything to the right type.
10438 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10439 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10441 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10442 // bits of the inputs before performing those operations. The lower
10443 // compare is always unsigned.
10446 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10448 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10449 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10450 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10451 Sign, Zero, Sign, Zero);
10453 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10454 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10456 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10457 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10458 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10460 // Create masks for only the low parts/high parts of the 64 bit integers.
10461 static const int MaskHi[] = { 1, 1, 3, 3 };
10462 static const int MaskLo[] = { 0, 0, 2, 2 };
10463 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10464 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10465 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10467 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10468 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10471 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10473 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10476 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10477 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10478 // pcmpeqd + pshufd + pand.
10479 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10481 // First cast everything to the right type.
10482 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10483 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10486 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10488 // Make sure the lower and upper halves are both all-ones.
10489 static const int Mask[] = { 1, 0, 3, 2 };
10490 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10491 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10494 Result = DAG.getNOT(dl, Result, MVT::v4i32);
10496 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10500 // Since SSE has no unsigned integer comparisons, we need to flip the sign
10501 // bits of the inputs before performing those operations.
10503 EVT EltVT = VT.getVectorElementType();
10504 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10505 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10506 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10509 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10511 // If the logical-not of the result is required, perform that now.
10513 Result = DAG.getNOT(dl, Result, VT);
10516 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10519 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10520 getZeroVector(VT, Subtarget, DAG, dl));
10525 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10527 MVT VT = Op.getSimpleValueType();
10529 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10531 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10532 && "SetCC type must be 8-bit or 1-bit integer");
10533 SDValue Op0 = Op.getOperand(0);
10534 SDValue Op1 = Op.getOperand(1);
10536 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10538 // Optimize to BT if possible.
10539 // Lower (X & (1 << N)) == 0 to BT(X, N).
10540 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10541 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10542 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10543 Op1.getOpcode() == ISD::Constant &&
10544 cast<ConstantSDNode>(Op1)->isNullValue() &&
10545 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10546 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10547 if (NewSetCC.getNode())
10551 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
10553 if (Op1.getOpcode() == ISD::Constant &&
10554 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10555 cast<ConstantSDNode>(Op1)->isNullValue()) &&
10556 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10558 // If the input is a setcc, then reuse the input setcc or use a new one with
10559 // the inverted condition.
10560 if (Op0.getOpcode() == X86ISD::SETCC) {
10561 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10562 bool Invert = (CC == ISD::SETNE) ^
10563 cast<ConstantSDNode>(Op1)->isNullValue();
10567 CCode = X86::GetOppositeBranchCondition(CCode);
10568 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10569 DAG.getConstant(CCode, MVT::i8),
10570 Op0.getOperand(1));
10572 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10576 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10577 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10578 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10580 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10581 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10584 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10585 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10586 if (X86CC == X86::COND_INVALID)
10589 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10590 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10591 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10592 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10594 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10598 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10599 static bool isX86LogicalCmp(SDValue Op) {
10600 unsigned Opc = Op.getNode()->getOpcode();
10601 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10602 Opc == X86ISD::SAHF)
10604 if (Op.getResNo() == 1 &&
10605 (Opc == X86ISD::ADD ||
10606 Opc == X86ISD::SUB ||
10607 Opc == X86ISD::ADC ||
10608 Opc == X86ISD::SBB ||
10609 Opc == X86ISD::SMUL ||
10610 Opc == X86ISD::UMUL ||
10611 Opc == X86ISD::INC ||
10612 Opc == X86ISD::DEC ||
10613 Opc == X86ISD::OR ||
10614 Opc == X86ISD::XOR ||
10615 Opc == X86ISD::AND))
10618 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10624 static bool isZero(SDValue V) {
10625 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10626 return C && C->isNullValue();
10629 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10630 if (V.getOpcode() != ISD::TRUNCATE)
10633 SDValue VOp0 = V.getOperand(0);
10634 unsigned InBits = VOp0.getValueSizeInBits();
10635 unsigned Bits = V.getValueSizeInBits();
10636 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10639 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10640 bool addTest = true;
10641 SDValue Cond = Op.getOperand(0);
10642 SDValue Op1 = Op.getOperand(1);
10643 SDValue Op2 = Op.getOperand(2);
10645 EVT VT = Op1.getValueType();
10648 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10649 // are available. Otherwise fp cmovs get lowered into a less efficient branch
10650 // sequence later on.
10651 if (Cond.getOpcode() == ISD::SETCC &&
10652 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10653 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10654 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10655 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10656 int SSECC = translateX86FSETCC(
10657 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10660 if (Subtarget->hasAVX512()) {
10661 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10662 DAG.getConstant(SSECC, MVT::i8));
10663 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10665 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10666 DAG.getConstant(SSECC, MVT::i8));
10667 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10668 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10669 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10673 if (Cond.getOpcode() == ISD::SETCC) {
10674 SDValue NewCond = LowerSETCC(Cond, DAG);
10675 if (NewCond.getNode())
10679 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10680 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10681 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10682 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10683 if (Cond.getOpcode() == X86ISD::SETCC &&
10684 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10685 isZero(Cond.getOperand(1).getOperand(1))) {
10686 SDValue Cmp = Cond.getOperand(1);
10688 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10690 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10691 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10692 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10694 SDValue CmpOp0 = Cmp.getOperand(0);
10695 // Apply further optimizations for special cases
10696 // (select (x != 0), -1, 0) -> neg & sbb
10697 // (select (x == 0), 0, -1) -> neg & sbb
10698 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10699 if (YC->isNullValue() &&
10700 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10701 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10702 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10703 DAG.getConstant(0, CmpOp0.getValueType()),
10705 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10706 DAG.getConstant(X86::COND_B, MVT::i8),
10707 SDValue(Neg.getNode(), 1));
10711 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10712 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10713 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10715 SDValue Res = // Res = 0 or -1.
10716 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10717 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10719 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10720 Res = DAG.getNOT(DL, Res, Res.getValueType());
10722 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10723 if (!N2C || !N2C->isNullValue())
10724 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10729 // Look past (and (setcc_carry (cmp ...)), 1).
10730 if (Cond.getOpcode() == ISD::AND &&
10731 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10732 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10733 if (C && C->getAPIntValue() == 1)
10734 Cond = Cond.getOperand(0);
10737 // If condition flag is set by a X86ISD::CMP, then use it as the condition
10738 // setting operand in place of the X86ISD::SETCC.
10739 unsigned CondOpcode = Cond.getOpcode();
10740 if (CondOpcode == X86ISD::SETCC ||
10741 CondOpcode == X86ISD::SETCC_CARRY) {
10742 CC = Cond.getOperand(0);
10744 SDValue Cmp = Cond.getOperand(1);
10745 unsigned Opc = Cmp.getOpcode();
10746 MVT VT = Op.getSimpleValueType();
10748 bool IllegalFPCMov = false;
10749 if (VT.isFloatingPoint() && !VT.isVector() &&
10750 !isScalarFPTypeInSSEReg(VT)) // FPStack?
10751 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10753 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10754 Opc == X86ISD::BT) { // FIXME
10758 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10759 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10760 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10761 Cond.getOperand(0).getValueType() != MVT::i8)) {
10762 SDValue LHS = Cond.getOperand(0);
10763 SDValue RHS = Cond.getOperand(1);
10764 unsigned X86Opcode;
10767 switch (CondOpcode) {
10768 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10769 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10770 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10771 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10772 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10773 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10774 default: llvm_unreachable("unexpected overflowing operator");
10776 if (CondOpcode == ISD::UMULO)
10777 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10780 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10782 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10784 if (CondOpcode == ISD::UMULO)
10785 Cond = X86Op.getValue(2);
10787 Cond = X86Op.getValue(1);
10789 CC = DAG.getConstant(X86Cond, MVT::i8);
10794 // Look pass the truncate if the high bits are known zero.
10795 if (isTruncWithZeroHighBitsInput(Cond, DAG))
10796 Cond = Cond.getOperand(0);
10798 // We know the result of AND is compared against zero. Try to match
10800 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10801 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10802 if (NewSetCC.getNode()) {
10803 CC = NewSetCC.getOperand(0);
10804 Cond = NewSetCC.getOperand(1);
10811 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10812 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10815 // a < b ? -1 : 0 -> RES = ~setcc_carry
10816 // a < b ? 0 : -1 -> RES = setcc_carry
10817 // a >= b ? -1 : 0 -> RES = setcc_carry
10818 // a >= b ? 0 : -1 -> RES = ~setcc_carry
10819 if (Cond.getOpcode() == X86ISD::SUB) {
10820 Cond = ConvertCmpIfNecessary(Cond, DAG);
10821 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10823 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10824 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10825 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10826 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10827 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10828 return DAG.getNOT(DL, Res, Res.getValueType());
10833 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10834 // widen the cmov and push the truncate through. This avoids introducing a new
10835 // branch during isel and doesn't add any extensions.
10836 if (Op.getValueType() == MVT::i8 &&
10837 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10838 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10839 if (T1.getValueType() == T2.getValueType() &&
10840 // Blacklist CopyFromReg to avoid partial register stalls.
10841 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10842 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10843 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10844 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10848 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10849 // condition is true.
10850 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10851 SDValue Ops[] = { Op2, Op1, CC, Cond };
10852 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10855 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10856 MVT VT = Op->getSimpleValueType(0);
10857 SDValue In = Op->getOperand(0);
10858 MVT InVT = In.getSimpleValueType();
10861 unsigned int NumElts = VT.getVectorNumElements();
10862 if (NumElts != 8 && NumElts != 16)
10865 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10866 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10868 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10869 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10871 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10872 Constant *C = ConstantInt::get(*DAG.getContext(),
10873 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10875 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10876 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10877 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10878 MachinePointerInfo::getConstantPool(),
10879 false, false, false, Alignment);
10880 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10881 if (VT.is512BitVector())
10883 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10886 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10887 SelectionDAG &DAG) {
10888 MVT VT = Op->getSimpleValueType(0);
10889 SDValue In = Op->getOperand(0);
10890 MVT InVT = In.getSimpleValueType();
10893 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10894 return LowerSIGN_EXTEND_AVX512(Op, DAG);
10896 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10897 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10898 (VT != MVT::v16i16 || InVT != MVT::v16i8))
10901 if (Subtarget->hasInt256())
10902 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10904 // Optimize vectors in AVX mode
10905 // Sign extend v8i16 to v8i32 and
10908 // Divide input vector into two parts
10909 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10910 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10911 // concat the vectors to original VT
10913 unsigned NumElems = InVT.getVectorNumElements();
10914 SDValue Undef = DAG.getUNDEF(InVT);
10916 SmallVector<int,8> ShufMask1(NumElems, -1);
10917 for (unsigned i = 0; i != NumElems/2; ++i)
10920 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10922 SmallVector<int,8> ShufMask2(NumElems, -1);
10923 for (unsigned i = 0; i != NumElems/2; ++i)
10924 ShufMask2[i] = i + NumElems/2;
10926 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10928 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10929 VT.getVectorNumElements()/2);
10931 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10932 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10934 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10937 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10938 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10939 // from the AND / OR.
10940 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10941 Opc = Op.getOpcode();
10942 if (Opc != ISD::OR && Opc != ISD::AND)
10944 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10945 Op.getOperand(0).hasOneUse() &&
10946 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10947 Op.getOperand(1).hasOneUse());
10950 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10951 // 1 and that the SETCC node has a single use.
10952 static bool isXor1OfSetCC(SDValue Op) {
10953 if (Op.getOpcode() != ISD::XOR)
10955 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10956 if (N1C && N1C->getAPIntValue() == 1) {
10957 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10958 Op.getOperand(0).hasOneUse();
10963 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10964 bool addTest = true;
10965 SDValue Chain = Op.getOperand(0);
10966 SDValue Cond = Op.getOperand(1);
10967 SDValue Dest = Op.getOperand(2);
10970 bool Inverted = false;
10972 if (Cond.getOpcode() == ISD::SETCC) {
10973 // Check for setcc([su]{add,sub,mul}o == 0).
10974 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10975 isa<ConstantSDNode>(Cond.getOperand(1)) &&
10976 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10977 Cond.getOperand(0).getResNo() == 1 &&
10978 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10979 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10980 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10981 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10982 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10983 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10985 Cond = Cond.getOperand(0);
10987 SDValue NewCond = LowerSETCC(Cond, DAG);
10988 if (NewCond.getNode())
10993 // FIXME: LowerXALUO doesn't handle these!!
10994 else if (Cond.getOpcode() == X86ISD::ADD ||
10995 Cond.getOpcode() == X86ISD::SUB ||
10996 Cond.getOpcode() == X86ISD::SMUL ||
10997 Cond.getOpcode() == X86ISD::UMUL)
10998 Cond = LowerXALUO(Cond, DAG);
11001 // Look pass (and (setcc_carry (cmp ...)), 1).
11002 if (Cond.getOpcode() == ISD::AND &&
11003 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11004 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11005 if (C && C->getAPIntValue() == 1)
11006 Cond = Cond.getOperand(0);
11009 // If condition flag is set by a X86ISD::CMP, then use it as the condition
11010 // setting operand in place of the X86ISD::SETCC.
11011 unsigned CondOpcode = Cond.getOpcode();
11012 if (CondOpcode == X86ISD::SETCC ||
11013 CondOpcode == X86ISD::SETCC_CARRY) {
11014 CC = Cond.getOperand(0);
11016 SDValue Cmp = Cond.getOperand(1);
11017 unsigned Opc = Cmp.getOpcode();
11018 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11019 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11023 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11027 // These can only come from an arithmetic instruction with overflow,
11028 // e.g. SADDO, UADDO.
11029 Cond = Cond.getNode()->getOperand(1);
11035 CondOpcode = Cond.getOpcode();
11036 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11037 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11038 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11039 Cond.getOperand(0).getValueType() != MVT::i8)) {
11040 SDValue LHS = Cond.getOperand(0);
11041 SDValue RHS = Cond.getOperand(1);
11042 unsigned X86Opcode;
11045 // Keep this in sync with LowerXALUO, otherwise we might create redundant
11046 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11048 switch (CondOpcode) {
11049 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11053 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11056 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11057 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11061 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11064 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11065 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11066 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11067 default: llvm_unreachable("unexpected overflowing operator");
11070 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11071 if (CondOpcode == ISD::UMULO)
11072 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11075 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11077 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11079 if (CondOpcode == ISD::UMULO)
11080 Cond = X86Op.getValue(2);
11082 Cond = X86Op.getValue(1);
11084 CC = DAG.getConstant(X86Cond, MVT::i8);
11088 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11089 SDValue Cmp = Cond.getOperand(0).getOperand(1);
11090 if (CondOpc == ISD::OR) {
11091 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11092 // two branches instead of an explicit OR instruction with a
11094 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11095 isX86LogicalCmp(Cmp)) {
11096 CC = Cond.getOperand(0).getOperand(0);
11097 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11098 Chain, Dest, CC, Cmp);
11099 CC = Cond.getOperand(1).getOperand(0);
11103 } else { // ISD::AND
11104 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11105 // two branches instead of an explicit AND instruction with a
11106 // separate test. However, we only do this if this block doesn't
11107 // have a fall-through edge, because this requires an explicit
11108 // jmp when the condition is false.
11109 if (Cmp == Cond.getOperand(1).getOperand(1) &&
11110 isX86LogicalCmp(Cmp) &&
11111 Op.getNode()->hasOneUse()) {
11112 X86::CondCode CCode =
11113 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11114 CCode = X86::GetOppositeBranchCondition(CCode);
11115 CC = DAG.getConstant(CCode, MVT::i8);
11116 SDNode *User = *Op.getNode()->use_begin();
11117 // Look for an unconditional branch following this conditional branch.
11118 // We need this because we need to reverse the successors in order
11119 // to implement FCMP_OEQ.
11120 if (User->getOpcode() == ISD::BR) {
11121 SDValue FalseBB = User->getOperand(1);
11123 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11124 assert(NewBR == User);
11128 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11129 Chain, Dest, CC, Cmp);
11130 X86::CondCode CCode =
11131 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11132 CCode = X86::GetOppositeBranchCondition(CCode);
11133 CC = DAG.getConstant(CCode, MVT::i8);
11139 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11140 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11141 // It should be transformed during dag combiner except when the condition
11142 // is set by a arithmetics with overflow node.
11143 X86::CondCode CCode =
11144 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11145 CCode = X86::GetOppositeBranchCondition(CCode);
11146 CC = DAG.getConstant(CCode, MVT::i8);
11147 Cond = Cond.getOperand(0).getOperand(1);
11149 } else if (Cond.getOpcode() == ISD::SETCC &&
11150 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11151 // For FCMP_OEQ, we can emit
11152 // two branches instead of an explicit AND instruction with a
11153 // separate test. However, we only do this if this block doesn't
11154 // have a fall-through edge, because this requires an explicit
11155 // jmp when the condition is false.
11156 if (Op.getNode()->hasOneUse()) {
11157 SDNode *User = *Op.getNode()->use_begin();
11158 // Look for an unconditional branch following this conditional branch.
11159 // We need this because we need to reverse the successors in order
11160 // to implement FCMP_OEQ.
11161 if (User->getOpcode() == ISD::BR) {
11162 SDValue FalseBB = User->getOperand(1);
11164 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11165 assert(NewBR == User);
11169 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11170 Cond.getOperand(0), Cond.getOperand(1));
11171 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11172 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11173 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11174 Chain, Dest, CC, Cmp);
11175 CC = DAG.getConstant(X86::COND_P, MVT::i8);
11180 } else if (Cond.getOpcode() == ISD::SETCC &&
11181 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11182 // For FCMP_UNE, we can emit
11183 // two branches instead of an explicit AND instruction with a
11184 // separate test. However, we only do this if this block doesn't
11185 // have a fall-through edge, because this requires an explicit
11186 // jmp when the condition is false.
11187 if (Op.getNode()->hasOneUse()) {
11188 SDNode *User = *Op.getNode()->use_begin();
11189 // Look for an unconditional branch following this conditional branch.
11190 // We need this because we need to reverse the successors in order
11191 // to implement FCMP_UNE.
11192 if (User->getOpcode() == ISD::BR) {
11193 SDValue FalseBB = User->getOperand(1);
11195 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11196 assert(NewBR == User);
11199 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11200 Cond.getOperand(0), Cond.getOperand(1));
11201 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11202 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11203 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11204 Chain, Dest, CC, Cmp);
11205 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11215 // Look pass the truncate if the high bits are known zero.
11216 if (isTruncWithZeroHighBitsInput(Cond, DAG))
11217 Cond = Cond.getOperand(0);
11219 // We know the result of AND is compared against zero. Try to match
11221 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11222 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11223 if (NewSetCC.getNode()) {
11224 CC = NewSetCC.getOperand(0);
11225 Cond = NewSetCC.getOperand(1);
11232 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11233 Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11235 Cond = ConvertCmpIfNecessary(Cond, DAG);
11236 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11237 Chain, Dest, CC, Cond);
11240 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11241 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11242 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11243 // that the guard pages used by the OS virtual memory manager are allocated in
11244 // correct sequence.
11246 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11247 SelectionDAG &DAG) const {
11248 MachineFunction &MF = DAG.getMachineFunction();
11249 bool SplitStack = MF.shouldSplitStack();
11250 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11255 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11256 SDNode* Node = Op.getNode();
11258 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11259 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11260 " not tell us which reg is the stack pointer!");
11261 EVT VT = Node->getValueType(0);
11262 SDValue Tmp1 = SDValue(Node, 0);
11263 SDValue Tmp2 = SDValue(Node, 1);
11264 SDValue Tmp3 = Node->getOperand(2);
11265 SDValue Chain = Tmp1.getOperand(0);
11267 // Chain the dynamic stack allocation so that it doesn't modify the stack
11268 // pointer when other instructions are using the stack.
11269 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11272 SDValue Size = Tmp2.getOperand(1);
11273 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11274 Chain = SP.getValue(1);
11275 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11276 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11277 unsigned StackAlign = TFI.getStackAlignment();
11278 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11279 if (Align > StackAlign)
11280 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11281 DAG.getConstant(-(uint64_t)Align, VT));
11282 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11284 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11285 DAG.getIntPtrConstant(0, true), SDValue(),
11288 SDValue Ops[2] = { Tmp1, Tmp2 };
11289 return DAG.getMergeValues(Ops, 2, dl);
11293 SDValue Chain = Op.getOperand(0);
11294 SDValue Size = Op.getOperand(1);
11295 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11296 EVT VT = Op.getNode()->getValueType(0);
11298 bool Is64Bit = Subtarget->is64Bit();
11299 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11302 MachineRegisterInfo &MRI = MF.getRegInfo();
11305 // The 64 bit implementation of segmented stacks needs to clobber both r10
11306 // r11. This makes it impossible to use it along with nested parameters.
11307 const Function *F = MF.getFunction();
11309 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11311 if (I->hasNestAttr())
11312 report_fatal_error("Cannot use segmented stacks with functions that "
11313 "have nested arguments.");
11316 const TargetRegisterClass *AddrRegClass =
11317 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11318 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11319 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11320 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11321 DAG.getRegister(Vreg, SPTy));
11322 SDValue Ops1[2] = { Value, Chain };
11323 return DAG.getMergeValues(Ops1, 2, dl);
11326 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11328 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11329 Flag = Chain.getValue(1);
11330 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11332 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11334 const X86RegisterInfo *RegInfo =
11335 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11336 unsigned SPReg = RegInfo->getStackRegister();
11337 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11338 Chain = SP.getValue(1);
11341 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11342 DAG.getConstant(-(uint64_t)Align, VT));
11343 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11346 SDValue Ops1[2] = { SP, Chain };
11347 return DAG.getMergeValues(Ops1, 2, dl);
11351 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11352 MachineFunction &MF = DAG.getMachineFunction();
11353 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11355 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11358 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11359 // vastart just stores the address of the VarArgsFrameIndex slot into the
11360 // memory location argument.
11361 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11363 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11364 MachinePointerInfo(SV), false, false, 0);
11368 // gp_offset (0 - 6 * 8)
11369 // fp_offset (48 - 48 + 8 * 16)
11370 // overflow_arg_area (point to parameters coming in memory).
11372 SmallVector<SDValue, 8> MemOps;
11373 SDValue FIN = Op.getOperand(1);
11375 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11376 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11378 FIN, MachinePointerInfo(SV), false, false, 0);
11379 MemOps.push_back(Store);
11382 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11383 FIN, DAG.getIntPtrConstant(4));
11384 Store = DAG.getStore(Op.getOperand(0), DL,
11385 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11387 FIN, MachinePointerInfo(SV, 4), false, false, 0);
11388 MemOps.push_back(Store);
11390 // Store ptr to overflow_arg_area
11391 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11392 FIN, DAG.getIntPtrConstant(4));
11393 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11395 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11396 MachinePointerInfo(SV, 8),
11398 MemOps.push_back(Store);
11400 // Store ptr to reg_save_area.
11401 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11402 FIN, DAG.getIntPtrConstant(8));
11403 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11405 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11406 MachinePointerInfo(SV, 16), false, false, 0);
11407 MemOps.push_back(Store);
11408 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11411 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11412 assert(Subtarget->is64Bit() &&
11413 "LowerVAARG only handles 64-bit va_arg!");
11414 assert((Subtarget->isTargetLinux() ||
11415 Subtarget->isTargetDarwin()) &&
11416 "Unhandled target in LowerVAARG");
11417 assert(Op.getNode()->getNumOperands() == 4);
11418 SDValue Chain = Op.getOperand(0);
11419 SDValue SrcPtr = Op.getOperand(1);
11420 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11421 unsigned Align = Op.getConstantOperandVal(3);
11424 EVT ArgVT = Op.getNode()->getValueType(0);
11425 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11426 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11429 // Decide which area this value should be read from.
11430 // TODO: Implement the AMD64 ABI in its entirety. This simple
11431 // selection mechanism works only for the basic types.
11432 if (ArgVT == MVT::f80) {
11433 llvm_unreachable("va_arg for f80 not yet implemented");
11434 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11435 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
11436 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11437 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
11439 llvm_unreachable("Unhandled argument type in LowerVAARG");
11442 if (ArgMode == 2) {
11443 // Sanity Check: Make sure using fp_offset makes sense.
11444 assert(!getTargetMachine().Options.UseSoftFloat &&
11445 !(DAG.getMachineFunction()
11446 .getFunction()->getAttributes()
11447 .hasAttribute(AttributeSet::FunctionIndex,
11448 Attribute::NoImplicitFloat)) &&
11449 Subtarget->hasSSE1());
11452 // Insert VAARG_64 node into the DAG
11453 // VAARG_64 returns two values: Variable Argument Address, Chain
11454 SmallVector<SDValue, 11> InstOps;
11455 InstOps.push_back(Chain);
11456 InstOps.push_back(SrcPtr);
11457 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11458 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11459 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11460 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11461 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11462 VTs, &InstOps[0], InstOps.size(),
11464 MachinePointerInfo(SV),
11466 /*Volatile=*/false,
11468 /*WriteMem=*/true);
11469 Chain = VAARG.getValue(1);
11471 // Load the next argument and return it
11472 return DAG.getLoad(ArgVT, dl,
11475 MachinePointerInfo(),
11476 false, false, false, 0);
11479 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11480 SelectionDAG &DAG) {
11481 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11482 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11483 SDValue Chain = Op.getOperand(0);
11484 SDValue DstPtr = Op.getOperand(1);
11485 SDValue SrcPtr = Op.getOperand(2);
11486 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11487 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11490 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11491 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11493 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11496 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11497 // amount is a constant. Takes immediate version of shift as input.
11498 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11499 SDValue SrcOp, uint64_t ShiftAmt,
11500 SelectionDAG &DAG) {
11501 MVT ElementType = VT.getVectorElementType();
11503 // Check for ShiftAmt >= element width
11504 if (ShiftAmt >= ElementType.getSizeInBits()) {
11505 if (Opc == X86ISD::VSRAI)
11506 ShiftAmt = ElementType.getSizeInBits() - 1;
11508 return DAG.getConstant(0, VT);
11511 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11512 && "Unknown target vector shift-by-constant node");
11514 // Fold this packed vector shift into a build vector if SrcOp is a
11515 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11516 if (VT == SrcOp.getSimpleValueType() &&
11517 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11518 SmallVector<SDValue, 8> Elts;
11519 unsigned NumElts = SrcOp->getNumOperands();
11520 ConstantSDNode *ND;
11523 default: llvm_unreachable(0);
11524 case X86ISD::VSHLI:
11525 for (unsigned i=0; i!=NumElts; ++i) {
11526 SDValue CurrentOp = SrcOp->getOperand(i);
11527 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11528 Elts.push_back(CurrentOp);
11531 ND = cast<ConstantSDNode>(CurrentOp);
11532 const APInt &C = ND->getAPIntValue();
11533 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11536 case X86ISD::VSRLI:
11537 for (unsigned i=0; i!=NumElts; ++i) {
11538 SDValue CurrentOp = SrcOp->getOperand(i);
11539 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11540 Elts.push_back(CurrentOp);
11543 ND = cast<ConstantSDNode>(CurrentOp);
11544 const APInt &C = ND->getAPIntValue();
11545 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11548 case X86ISD::VSRAI:
11549 for (unsigned i=0; i!=NumElts; ++i) {
11550 SDValue CurrentOp = SrcOp->getOperand(i);
11551 if (CurrentOp->getOpcode() == ISD::UNDEF) {
11552 Elts.push_back(CurrentOp);
11555 ND = cast<ConstantSDNode>(CurrentOp);
11556 const APInt &C = ND->getAPIntValue();
11557 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11562 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11565 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11568 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11569 // may or may not be a constant. Takes immediate version of shift as input.
11570 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11571 SDValue SrcOp, SDValue ShAmt,
11572 SelectionDAG &DAG) {
11573 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11575 // Catch shift-by-constant.
11576 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11577 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11578 CShAmt->getZExtValue(), DAG);
11580 // Change opcode to non-immediate version
11582 default: llvm_unreachable("Unknown target vector shift node");
11583 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11584 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11585 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11588 // Need to build a vector containing shift amount
11589 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11592 ShOps[1] = DAG.getConstant(0, MVT::i32);
11593 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11594 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11596 // The return type has to be a 128-bit type with the same element
11597 // type as the input type.
11598 MVT EltVT = VT.getVectorElementType();
11599 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11601 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11602 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11605 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11607 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11609 default: return SDValue(); // Don't custom lower most intrinsics.
11610 // Comparison intrinsics.
11611 case Intrinsic::x86_sse_comieq_ss:
11612 case Intrinsic::x86_sse_comilt_ss:
11613 case Intrinsic::x86_sse_comile_ss:
11614 case Intrinsic::x86_sse_comigt_ss:
11615 case Intrinsic::x86_sse_comige_ss:
11616 case Intrinsic::x86_sse_comineq_ss:
11617 case Intrinsic::x86_sse_ucomieq_ss:
11618 case Intrinsic::x86_sse_ucomilt_ss:
11619 case Intrinsic::x86_sse_ucomile_ss:
11620 case Intrinsic::x86_sse_ucomigt_ss:
11621 case Intrinsic::x86_sse_ucomige_ss:
11622 case Intrinsic::x86_sse_ucomineq_ss:
11623 case Intrinsic::x86_sse2_comieq_sd:
11624 case Intrinsic::x86_sse2_comilt_sd:
11625 case Intrinsic::x86_sse2_comile_sd:
11626 case Intrinsic::x86_sse2_comigt_sd:
11627 case Intrinsic::x86_sse2_comige_sd:
11628 case Intrinsic::x86_sse2_comineq_sd:
11629 case Intrinsic::x86_sse2_ucomieq_sd:
11630 case Intrinsic::x86_sse2_ucomilt_sd:
11631 case Intrinsic::x86_sse2_ucomile_sd:
11632 case Intrinsic::x86_sse2_ucomigt_sd:
11633 case Intrinsic::x86_sse2_ucomige_sd:
11634 case Intrinsic::x86_sse2_ucomineq_sd: {
11638 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11639 case Intrinsic::x86_sse_comieq_ss:
11640 case Intrinsic::x86_sse2_comieq_sd:
11641 Opc = X86ISD::COMI;
11644 case Intrinsic::x86_sse_comilt_ss:
11645 case Intrinsic::x86_sse2_comilt_sd:
11646 Opc = X86ISD::COMI;
11649 case Intrinsic::x86_sse_comile_ss:
11650 case Intrinsic::x86_sse2_comile_sd:
11651 Opc = X86ISD::COMI;
11654 case Intrinsic::x86_sse_comigt_ss:
11655 case Intrinsic::x86_sse2_comigt_sd:
11656 Opc = X86ISD::COMI;
11659 case Intrinsic::x86_sse_comige_ss:
11660 case Intrinsic::x86_sse2_comige_sd:
11661 Opc = X86ISD::COMI;
11664 case Intrinsic::x86_sse_comineq_ss:
11665 case Intrinsic::x86_sse2_comineq_sd:
11666 Opc = X86ISD::COMI;
11669 case Intrinsic::x86_sse_ucomieq_ss:
11670 case Intrinsic::x86_sse2_ucomieq_sd:
11671 Opc = X86ISD::UCOMI;
11674 case Intrinsic::x86_sse_ucomilt_ss:
11675 case Intrinsic::x86_sse2_ucomilt_sd:
11676 Opc = X86ISD::UCOMI;
11679 case Intrinsic::x86_sse_ucomile_ss:
11680 case Intrinsic::x86_sse2_ucomile_sd:
11681 Opc = X86ISD::UCOMI;
11684 case Intrinsic::x86_sse_ucomigt_ss:
11685 case Intrinsic::x86_sse2_ucomigt_sd:
11686 Opc = X86ISD::UCOMI;
11689 case Intrinsic::x86_sse_ucomige_ss:
11690 case Intrinsic::x86_sse2_ucomige_sd:
11691 Opc = X86ISD::UCOMI;
11694 case Intrinsic::x86_sse_ucomineq_ss:
11695 case Intrinsic::x86_sse2_ucomineq_sd:
11696 Opc = X86ISD::UCOMI;
11701 SDValue LHS = Op.getOperand(1);
11702 SDValue RHS = Op.getOperand(2);
11703 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11704 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11705 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11706 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11707 DAG.getConstant(X86CC, MVT::i8), Cond);
11708 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11711 // Arithmetic intrinsics.
11712 case Intrinsic::x86_sse2_pmulu_dq:
11713 case Intrinsic::x86_avx2_pmulu_dq:
11714 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11715 Op.getOperand(1), Op.getOperand(2));
11717 case Intrinsic::x86_sse41_pmuldq:
11718 case Intrinsic::x86_avx2_pmul_dq:
11719 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11720 Op.getOperand(1), Op.getOperand(2));
11722 case Intrinsic::x86_sse2_pmulhu_w:
11723 case Intrinsic::x86_avx2_pmulhu_w:
11724 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11725 Op.getOperand(1), Op.getOperand(2));
11727 case Intrinsic::x86_sse2_pmulh_w:
11728 case Intrinsic::x86_avx2_pmulh_w:
11729 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11730 Op.getOperand(1), Op.getOperand(2));
11732 // SSE2/AVX2 sub with unsigned saturation intrinsics
11733 case Intrinsic::x86_sse2_psubus_b:
11734 case Intrinsic::x86_sse2_psubus_w:
11735 case Intrinsic::x86_avx2_psubus_b:
11736 case Intrinsic::x86_avx2_psubus_w:
11737 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11738 Op.getOperand(1), Op.getOperand(2));
11740 // SSE3/AVX horizontal add/sub intrinsics
11741 case Intrinsic::x86_sse3_hadd_ps:
11742 case Intrinsic::x86_sse3_hadd_pd:
11743 case Intrinsic::x86_avx_hadd_ps_256:
11744 case Intrinsic::x86_avx_hadd_pd_256:
11745 case Intrinsic::x86_sse3_hsub_ps:
11746 case Intrinsic::x86_sse3_hsub_pd:
11747 case Intrinsic::x86_avx_hsub_ps_256:
11748 case Intrinsic::x86_avx_hsub_pd_256:
11749 case Intrinsic::x86_ssse3_phadd_w_128:
11750 case Intrinsic::x86_ssse3_phadd_d_128:
11751 case Intrinsic::x86_avx2_phadd_w:
11752 case Intrinsic::x86_avx2_phadd_d:
11753 case Intrinsic::x86_ssse3_phsub_w_128:
11754 case Intrinsic::x86_ssse3_phsub_d_128:
11755 case Intrinsic::x86_avx2_phsub_w:
11756 case Intrinsic::x86_avx2_phsub_d: {
11759 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11760 case Intrinsic::x86_sse3_hadd_ps:
11761 case Intrinsic::x86_sse3_hadd_pd:
11762 case Intrinsic::x86_avx_hadd_ps_256:
11763 case Intrinsic::x86_avx_hadd_pd_256:
11764 Opcode = X86ISD::FHADD;
11766 case Intrinsic::x86_sse3_hsub_ps:
11767 case Intrinsic::x86_sse3_hsub_pd:
11768 case Intrinsic::x86_avx_hsub_ps_256:
11769 case Intrinsic::x86_avx_hsub_pd_256:
11770 Opcode = X86ISD::FHSUB;
11772 case Intrinsic::x86_ssse3_phadd_w_128:
11773 case Intrinsic::x86_ssse3_phadd_d_128:
11774 case Intrinsic::x86_avx2_phadd_w:
11775 case Intrinsic::x86_avx2_phadd_d:
11776 Opcode = X86ISD::HADD;
11778 case Intrinsic::x86_ssse3_phsub_w_128:
11779 case Intrinsic::x86_ssse3_phsub_d_128:
11780 case Intrinsic::x86_avx2_phsub_w:
11781 case Intrinsic::x86_avx2_phsub_d:
11782 Opcode = X86ISD::HSUB;
11785 return DAG.getNode(Opcode, dl, Op.getValueType(),
11786 Op.getOperand(1), Op.getOperand(2));
11789 // SSE2/SSE41/AVX2 integer max/min intrinsics.
11790 case Intrinsic::x86_sse2_pmaxu_b:
11791 case Intrinsic::x86_sse41_pmaxuw:
11792 case Intrinsic::x86_sse41_pmaxud:
11793 case Intrinsic::x86_avx2_pmaxu_b:
11794 case Intrinsic::x86_avx2_pmaxu_w:
11795 case Intrinsic::x86_avx2_pmaxu_d:
11796 case Intrinsic::x86_sse2_pminu_b:
11797 case Intrinsic::x86_sse41_pminuw:
11798 case Intrinsic::x86_sse41_pminud:
11799 case Intrinsic::x86_avx2_pminu_b:
11800 case Intrinsic::x86_avx2_pminu_w:
11801 case Intrinsic::x86_avx2_pminu_d:
11802 case Intrinsic::x86_sse41_pmaxsb:
11803 case Intrinsic::x86_sse2_pmaxs_w:
11804 case Intrinsic::x86_sse41_pmaxsd:
11805 case Intrinsic::x86_avx2_pmaxs_b:
11806 case Intrinsic::x86_avx2_pmaxs_w:
11807 case Intrinsic::x86_avx2_pmaxs_d:
11808 case Intrinsic::x86_sse41_pminsb:
11809 case Intrinsic::x86_sse2_pmins_w:
11810 case Intrinsic::x86_sse41_pminsd:
11811 case Intrinsic::x86_avx2_pmins_b:
11812 case Intrinsic::x86_avx2_pmins_w:
11813 case Intrinsic::x86_avx2_pmins_d: {
11816 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11817 case Intrinsic::x86_sse2_pmaxu_b:
11818 case Intrinsic::x86_sse41_pmaxuw:
11819 case Intrinsic::x86_sse41_pmaxud:
11820 case Intrinsic::x86_avx2_pmaxu_b:
11821 case Intrinsic::x86_avx2_pmaxu_w:
11822 case Intrinsic::x86_avx2_pmaxu_d:
11823 Opcode = X86ISD::UMAX;
11825 case Intrinsic::x86_sse2_pminu_b:
11826 case Intrinsic::x86_sse41_pminuw:
11827 case Intrinsic::x86_sse41_pminud:
11828 case Intrinsic::x86_avx2_pminu_b:
11829 case Intrinsic::x86_avx2_pminu_w:
11830 case Intrinsic::x86_avx2_pminu_d:
11831 Opcode = X86ISD::UMIN;
11833 case Intrinsic::x86_sse41_pmaxsb:
11834 case Intrinsic::x86_sse2_pmaxs_w:
11835 case Intrinsic::x86_sse41_pmaxsd:
11836 case Intrinsic::x86_avx2_pmaxs_b:
11837 case Intrinsic::x86_avx2_pmaxs_w:
11838 case Intrinsic::x86_avx2_pmaxs_d:
11839 Opcode = X86ISD::SMAX;
11841 case Intrinsic::x86_sse41_pminsb:
11842 case Intrinsic::x86_sse2_pmins_w:
11843 case Intrinsic::x86_sse41_pminsd:
11844 case Intrinsic::x86_avx2_pmins_b:
11845 case Intrinsic::x86_avx2_pmins_w:
11846 case Intrinsic::x86_avx2_pmins_d:
11847 Opcode = X86ISD::SMIN;
11850 return DAG.getNode(Opcode, dl, Op.getValueType(),
11851 Op.getOperand(1), Op.getOperand(2));
11854 // SSE/SSE2/AVX floating point max/min intrinsics.
11855 case Intrinsic::x86_sse_max_ps:
11856 case Intrinsic::x86_sse2_max_pd:
11857 case Intrinsic::x86_avx_max_ps_256:
11858 case Intrinsic::x86_avx_max_pd_256:
11859 case Intrinsic::x86_sse_min_ps:
11860 case Intrinsic::x86_sse2_min_pd:
11861 case Intrinsic::x86_avx_min_ps_256:
11862 case Intrinsic::x86_avx_min_pd_256: {
11865 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11866 case Intrinsic::x86_sse_max_ps:
11867 case Intrinsic::x86_sse2_max_pd:
11868 case Intrinsic::x86_avx_max_ps_256:
11869 case Intrinsic::x86_avx_max_pd_256:
11870 Opcode = X86ISD::FMAX;
11872 case Intrinsic::x86_sse_min_ps:
11873 case Intrinsic::x86_sse2_min_pd:
11874 case Intrinsic::x86_avx_min_ps_256:
11875 case Intrinsic::x86_avx_min_pd_256:
11876 Opcode = X86ISD::FMIN;
11879 return DAG.getNode(Opcode, dl, Op.getValueType(),
11880 Op.getOperand(1), Op.getOperand(2));
11883 // AVX2 variable shift intrinsics
11884 case Intrinsic::x86_avx2_psllv_d:
11885 case Intrinsic::x86_avx2_psllv_q:
11886 case Intrinsic::x86_avx2_psllv_d_256:
11887 case Intrinsic::x86_avx2_psllv_q_256:
11888 case Intrinsic::x86_avx2_psrlv_d:
11889 case Intrinsic::x86_avx2_psrlv_q:
11890 case Intrinsic::x86_avx2_psrlv_d_256:
11891 case Intrinsic::x86_avx2_psrlv_q_256:
11892 case Intrinsic::x86_avx2_psrav_d:
11893 case Intrinsic::x86_avx2_psrav_d_256: {
11896 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
11897 case Intrinsic::x86_avx2_psllv_d:
11898 case Intrinsic::x86_avx2_psllv_q:
11899 case Intrinsic::x86_avx2_psllv_d_256:
11900 case Intrinsic::x86_avx2_psllv_q_256:
11903 case Intrinsic::x86_avx2_psrlv_d:
11904 case Intrinsic::x86_avx2_psrlv_q:
11905 case Intrinsic::x86_avx2_psrlv_d_256:
11906 case Intrinsic::x86_avx2_psrlv_q_256:
11909 case Intrinsic::x86_avx2_psrav_d:
11910 case Intrinsic::x86_avx2_psrav_d_256:
11914 return DAG.getNode(Opcode, dl, Op.getValueType(),
11915 Op.getOperand(1), Op.getOperand(2));
11918 case Intrinsic::x86_ssse3_pshuf_b_128:
11919 case Intrinsic::x86_avx2_pshuf_b:
11920 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11921 Op.getOperand(1), Op.getOperand(2));
11923 case Intrinsic::x86_ssse3_psign_b_128:
11924 case Intrinsic::x86_ssse3_psign_w_128:
11925 case Intrinsic::x86_ssse3_psign_d_128:
11926 case Intrinsic::x86_avx2_psign_b:
11927 case Intrinsic::x86_avx2_psign_w:
11928 case Intrinsic::x86_avx2_psign_d:
11929 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11930 Op.getOperand(1), Op.getOperand(2));
11932 case Intrinsic::x86_sse41_insertps:
11933 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11934 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11936 case Intrinsic::x86_avx_vperm2f128_ps_256:
11937 case Intrinsic::x86_avx_vperm2f128_pd_256:
11938 case Intrinsic::x86_avx_vperm2f128_si_256:
11939 case Intrinsic::x86_avx2_vperm2i128:
11940 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11941 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11943 case Intrinsic::x86_avx2_permd:
11944 case Intrinsic::x86_avx2_permps:
11945 // Operands intentionally swapped. Mask is last operand to intrinsic,
11946 // but second operand for node/instruction.
11947 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11948 Op.getOperand(2), Op.getOperand(1));
11950 case Intrinsic::x86_sse_sqrt_ps:
11951 case Intrinsic::x86_sse2_sqrt_pd:
11952 case Intrinsic::x86_avx_sqrt_ps_256:
11953 case Intrinsic::x86_avx_sqrt_pd_256:
11954 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11956 // ptest and testp intrinsics. The intrinsic these come from are designed to
11957 // return an integer value, not just an instruction so lower it to the ptest
11958 // or testp pattern and a setcc for the result.
11959 case Intrinsic::x86_sse41_ptestz:
11960 case Intrinsic::x86_sse41_ptestc:
11961 case Intrinsic::x86_sse41_ptestnzc:
11962 case Intrinsic::x86_avx_ptestz_256:
11963 case Intrinsic::x86_avx_ptestc_256:
11964 case Intrinsic::x86_avx_ptestnzc_256:
11965 case Intrinsic::x86_avx_vtestz_ps:
11966 case Intrinsic::x86_avx_vtestc_ps:
11967 case Intrinsic::x86_avx_vtestnzc_ps:
11968 case Intrinsic::x86_avx_vtestz_pd:
11969 case Intrinsic::x86_avx_vtestc_pd:
11970 case Intrinsic::x86_avx_vtestnzc_pd:
11971 case Intrinsic::x86_avx_vtestz_ps_256:
11972 case Intrinsic::x86_avx_vtestc_ps_256:
11973 case Intrinsic::x86_avx_vtestnzc_ps_256:
11974 case Intrinsic::x86_avx_vtestz_pd_256:
11975 case Intrinsic::x86_avx_vtestc_pd_256:
11976 case Intrinsic::x86_avx_vtestnzc_pd_256: {
11977 bool IsTestPacked = false;
11980 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11981 case Intrinsic::x86_avx_vtestz_ps:
11982 case Intrinsic::x86_avx_vtestz_pd:
11983 case Intrinsic::x86_avx_vtestz_ps_256:
11984 case Intrinsic::x86_avx_vtestz_pd_256:
11985 IsTestPacked = true; // Fallthrough
11986 case Intrinsic::x86_sse41_ptestz:
11987 case Intrinsic::x86_avx_ptestz_256:
11989 X86CC = X86::COND_E;
11991 case Intrinsic::x86_avx_vtestc_ps:
11992 case Intrinsic::x86_avx_vtestc_pd:
11993 case Intrinsic::x86_avx_vtestc_ps_256:
11994 case Intrinsic::x86_avx_vtestc_pd_256:
11995 IsTestPacked = true; // Fallthrough
11996 case Intrinsic::x86_sse41_ptestc:
11997 case Intrinsic::x86_avx_ptestc_256:
11999 X86CC = X86::COND_B;
12001 case Intrinsic::x86_avx_vtestnzc_ps:
12002 case Intrinsic::x86_avx_vtestnzc_pd:
12003 case Intrinsic::x86_avx_vtestnzc_ps_256:
12004 case Intrinsic::x86_avx_vtestnzc_pd_256:
12005 IsTestPacked = true; // Fallthrough
12006 case Intrinsic::x86_sse41_ptestnzc:
12007 case Intrinsic::x86_avx_ptestnzc_256:
12009 X86CC = X86::COND_A;
12013 SDValue LHS = Op.getOperand(1);
12014 SDValue RHS = Op.getOperand(2);
12015 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12016 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12017 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12018 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12019 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12021 case Intrinsic::x86_avx512_kortestz_w:
12022 case Intrinsic::x86_avx512_kortestc_w: {
12023 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12024 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12025 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12026 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12027 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12028 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12029 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12032 // SSE/AVX shift intrinsics
12033 case Intrinsic::x86_sse2_psll_w:
12034 case Intrinsic::x86_sse2_psll_d:
12035 case Intrinsic::x86_sse2_psll_q:
12036 case Intrinsic::x86_avx2_psll_w:
12037 case Intrinsic::x86_avx2_psll_d:
12038 case Intrinsic::x86_avx2_psll_q:
12039 case Intrinsic::x86_sse2_psrl_w:
12040 case Intrinsic::x86_sse2_psrl_d:
12041 case Intrinsic::x86_sse2_psrl_q:
12042 case Intrinsic::x86_avx2_psrl_w:
12043 case Intrinsic::x86_avx2_psrl_d:
12044 case Intrinsic::x86_avx2_psrl_q:
12045 case Intrinsic::x86_sse2_psra_w:
12046 case Intrinsic::x86_sse2_psra_d:
12047 case Intrinsic::x86_avx2_psra_w:
12048 case Intrinsic::x86_avx2_psra_d: {
12051 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12052 case Intrinsic::x86_sse2_psll_w:
12053 case Intrinsic::x86_sse2_psll_d:
12054 case Intrinsic::x86_sse2_psll_q:
12055 case Intrinsic::x86_avx2_psll_w:
12056 case Intrinsic::x86_avx2_psll_d:
12057 case Intrinsic::x86_avx2_psll_q:
12058 Opcode = X86ISD::VSHL;
12060 case Intrinsic::x86_sse2_psrl_w:
12061 case Intrinsic::x86_sse2_psrl_d:
12062 case Intrinsic::x86_sse2_psrl_q:
12063 case Intrinsic::x86_avx2_psrl_w:
12064 case Intrinsic::x86_avx2_psrl_d:
12065 case Intrinsic::x86_avx2_psrl_q:
12066 Opcode = X86ISD::VSRL;
12068 case Intrinsic::x86_sse2_psra_w:
12069 case Intrinsic::x86_sse2_psra_d:
12070 case Intrinsic::x86_avx2_psra_w:
12071 case Intrinsic::x86_avx2_psra_d:
12072 Opcode = X86ISD::VSRA;
12075 return DAG.getNode(Opcode, dl, Op.getValueType(),
12076 Op.getOperand(1), Op.getOperand(2));
12079 // SSE/AVX immediate shift intrinsics
12080 case Intrinsic::x86_sse2_pslli_w:
12081 case Intrinsic::x86_sse2_pslli_d:
12082 case Intrinsic::x86_sse2_pslli_q:
12083 case Intrinsic::x86_avx2_pslli_w:
12084 case Intrinsic::x86_avx2_pslli_d:
12085 case Intrinsic::x86_avx2_pslli_q:
12086 case Intrinsic::x86_sse2_psrli_w:
12087 case Intrinsic::x86_sse2_psrli_d:
12088 case Intrinsic::x86_sse2_psrli_q:
12089 case Intrinsic::x86_avx2_psrli_w:
12090 case Intrinsic::x86_avx2_psrli_d:
12091 case Intrinsic::x86_avx2_psrli_q:
12092 case Intrinsic::x86_sse2_psrai_w:
12093 case Intrinsic::x86_sse2_psrai_d:
12094 case Intrinsic::x86_avx2_psrai_w:
12095 case Intrinsic::x86_avx2_psrai_d: {
12098 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12099 case Intrinsic::x86_sse2_pslli_w:
12100 case Intrinsic::x86_sse2_pslli_d:
12101 case Intrinsic::x86_sse2_pslli_q:
12102 case Intrinsic::x86_avx2_pslli_w:
12103 case Intrinsic::x86_avx2_pslli_d:
12104 case Intrinsic::x86_avx2_pslli_q:
12105 Opcode = X86ISD::VSHLI;
12107 case Intrinsic::x86_sse2_psrli_w:
12108 case Intrinsic::x86_sse2_psrli_d:
12109 case Intrinsic::x86_sse2_psrli_q:
12110 case Intrinsic::x86_avx2_psrli_w:
12111 case Intrinsic::x86_avx2_psrli_d:
12112 case Intrinsic::x86_avx2_psrli_q:
12113 Opcode = X86ISD::VSRLI;
12115 case Intrinsic::x86_sse2_psrai_w:
12116 case Intrinsic::x86_sse2_psrai_d:
12117 case Intrinsic::x86_avx2_psrai_w:
12118 case Intrinsic::x86_avx2_psrai_d:
12119 Opcode = X86ISD::VSRAI;
12122 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12123 Op.getOperand(1), Op.getOperand(2), DAG);
12126 case Intrinsic::x86_sse42_pcmpistria128:
12127 case Intrinsic::x86_sse42_pcmpestria128:
12128 case Intrinsic::x86_sse42_pcmpistric128:
12129 case Intrinsic::x86_sse42_pcmpestric128:
12130 case Intrinsic::x86_sse42_pcmpistrio128:
12131 case Intrinsic::x86_sse42_pcmpestrio128:
12132 case Intrinsic::x86_sse42_pcmpistris128:
12133 case Intrinsic::x86_sse42_pcmpestris128:
12134 case Intrinsic::x86_sse42_pcmpistriz128:
12135 case Intrinsic::x86_sse42_pcmpestriz128: {
12139 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12140 case Intrinsic::x86_sse42_pcmpistria128:
12141 Opcode = X86ISD::PCMPISTRI;
12142 X86CC = X86::COND_A;
12144 case Intrinsic::x86_sse42_pcmpestria128:
12145 Opcode = X86ISD::PCMPESTRI;
12146 X86CC = X86::COND_A;
12148 case Intrinsic::x86_sse42_pcmpistric128:
12149 Opcode = X86ISD::PCMPISTRI;
12150 X86CC = X86::COND_B;
12152 case Intrinsic::x86_sse42_pcmpestric128:
12153 Opcode = X86ISD::PCMPESTRI;
12154 X86CC = X86::COND_B;
12156 case Intrinsic::x86_sse42_pcmpistrio128:
12157 Opcode = X86ISD::PCMPISTRI;
12158 X86CC = X86::COND_O;
12160 case Intrinsic::x86_sse42_pcmpestrio128:
12161 Opcode = X86ISD::PCMPESTRI;
12162 X86CC = X86::COND_O;
12164 case Intrinsic::x86_sse42_pcmpistris128:
12165 Opcode = X86ISD::PCMPISTRI;
12166 X86CC = X86::COND_S;
12168 case Intrinsic::x86_sse42_pcmpestris128:
12169 Opcode = X86ISD::PCMPESTRI;
12170 X86CC = X86::COND_S;
12172 case Intrinsic::x86_sse42_pcmpistriz128:
12173 Opcode = X86ISD::PCMPISTRI;
12174 X86CC = X86::COND_E;
12176 case Intrinsic::x86_sse42_pcmpestriz128:
12177 Opcode = X86ISD::PCMPESTRI;
12178 X86CC = X86::COND_E;
12181 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12182 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12183 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12184 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12185 DAG.getConstant(X86CC, MVT::i8),
12186 SDValue(PCMP.getNode(), 1));
12187 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12190 case Intrinsic::x86_sse42_pcmpistri128:
12191 case Intrinsic::x86_sse42_pcmpestri128: {
12193 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12194 Opcode = X86ISD::PCMPISTRI;
12196 Opcode = X86ISD::PCMPESTRI;
12198 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12199 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12200 return DAG.getNode(Opcode, dl, VTs, NewOps);
12202 case Intrinsic::x86_fma_vfmadd_ps:
12203 case Intrinsic::x86_fma_vfmadd_pd:
12204 case Intrinsic::x86_fma_vfmsub_ps:
12205 case Intrinsic::x86_fma_vfmsub_pd:
12206 case Intrinsic::x86_fma_vfnmadd_ps:
12207 case Intrinsic::x86_fma_vfnmadd_pd:
12208 case Intrinsic::x86_fma_vfnmsub_ps:
12209 case Intrinsic::x86_fma_vfnmsub_pd:
12210 case Intrinsic::x86_fma_vfmaddsub_ps:
12211 case Intrinsic::x86_fma_vfmaddsub_pd:
12212 case Intrinsic::x86_fma_vfmsubadd_ps:
12213 case Intrinsic::x86_fma_vfmsubadd_pd:
12214 case Intrinsic::x86_fma_vfmadd_ps_256:
12215 case Intrinsic::x86_fma_vfmadd_pd_256:
12216 case Intrinsic::x86_fma_vfmsub_ps_256:
12217 case Intrinsic::x86_fma_vfmsub_pd_256:
12218 case Intrinsic::x86_fma_vfnmadd_ps_256:
12219 case Intrinsic::x86_fma_vfnmadd_pd_256:
12220 case Intrinsic::x86_fma_vfnmsub_ps_256:
12221 case Intrinsic::x86_fma_vfnmsub_pd_256:
12222 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12223 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12224 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12225 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12226 case Intrinsic::x86_fma_vfmadd_ps_512:
12227 case Intrinsic::x86_fma_vfmadd_pd_512:
12228 case Intrinsic::x86_fma_vfmsub_ps_512:
12229 case Intrinsic::x86_fma_vfmsub_pd_512:
12230 case Intrinsic::x86_fma_vfnmadd_ps_512:
12231 case Intrinsic::x86_fma_vfnmadd_pd_512:
12232 case Intrinsic::x86_fma_vfnmsub_ps_512:
12233 case Intrinsic::x86_fma_vfnmsub_pd_512:
12234 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12235 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12236 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12237 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12240 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12241 case Intrinsic::x86_fma_vfmadd_ps:
12242 case Intrinsic::x86_fma_vfmadd_pd:
12243 case Intrinsic::x86_fma_vfmadd_ps_256:
12244 case Intrinsic::x86_fma_vfmadd_pd_256:
12245 case Intrinsic::x86_fma_vfmadd_ps_512:
12246 case Intrinsic::x86_fma_vfmadd_pd_512:
12247 Opc = X86ISD::FMADD;
12249 case Intrinsic::x86_fma_vfmsub_ps:
12250 case Intrinsic::x86_fma_vfmsub_pd:
12251 case Intrinsic::x86_fma_vfmsub_ps_256:
12252 case Intrinsic::x86_fma_vfmsub_pd_256:
12253 case Intrinsic::x86_fma_vfmsub_ps_512:
12254 case Intrinsic::x86_fma_vfmsub_pd_512:
12255 Opc = X86ISD::FMSUB;
12257 case Intrinsic::x86_fma_vfnmadd_ps:
12258 case Intrinsic::x86_fma_vfnmadd_pd:
12259 case Intrinsic::x86_fma_vfnmadd_ps_256:
12260 case Intrinsic::x86_fma_vfnmadd_pd_256:
12261 case Intrinsic::x86_fma_vfnmadd_ps_512:
12262 case Intrinsic::x86_fma_vfnmadd_pd_512:
12263 Opc = X86ISD::FNMADD;
12265 case Intrinsic::x86_fma_vfnmsub_ps:
12266 case Intrinsic::x86_fma_vfnmsub_pd:
12267 case Intrinsic::x86_fma_vfnmsub_ps_256:
12268 case Intrinsic::x86_fma_vfnmsub_pd_256:
12269 case Intrinsic::x86_fma_vfnmsub_ps_512:
12270 case Intrinsic::x86_fma_vfnmsub_pd_512:
12271 Opc = X86ISD::FNMSUB;
12273 case Intrinsic::x86_fma_vfmaddsub_ps:
12274 case Intrinsic::x86_fma_vfmaddsub_pd:
12275 case Intrinsic::x86_fma_vfmaddsub_ps_256:
12276 case Intrinsic::x86_fma_vfmaddsub_pd_256:
12277 case Intrinsic::x86_fma_vfmaddsub_ps_512:
12278 case Intrinsic::x86_fma_vfmaddsub_pd_512:
12279 Opc = X86ISD::FMADDSUB;
12281 case Intrinsic::x86_fma_vfmsubadd_ps:
12282 case Intrinsic::x86_fma_vfmsubadd_pd:
12283 case Intrinsic::x86_fma_vfmsubadd_ps_256:
12284 case Intrinsic::x86_fma_vfmsubadd_pd_256:
12285 case Intrinsic::x86_fma_vfmsubadd_ps_512:
12286 case Intrinsic::x86_fma_vfmsubadd_pd_512:
12287 Opc = X86ISD::FMSUBADD;
12291 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12292 Op.getOperand(2), Op.getOperand(3));
12297 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12298 SDValue Base, SDValue Index,
12299 SDValue ScaleOp, SDValue Chain,
12300 const X86Subtarget * Subtarget) {
12302 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12303 assert(C && "Invalid scale type");
12304 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12305 SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12306 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12307 Index.getSimpleValueType().getVectorNumElements());
12308 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12309 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12310 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12311 SDValue Segment = DAG.getRegister(0, MVT::i32);
12312 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12313 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12314 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12315 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12318 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12319 SDValue Src, SDValue Mask, SDValue Base,
12320 SDValue Index, SDValue ScaleOp, SDValue Chain,
12321 const X86Subtarget * Subtarget) {
12323 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12324 assert(C && "Invalid scale type");
12325 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12326 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12327 Index.getSimpleValueType().getVectorNumElements());
12328 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12329 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12330 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12331 SDValue Segment = DAG.getRegister(0, MVT::i32);
12332 if (Src.getOpcode() == ISD::UNDEF)
12333 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12334 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12335 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12336 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12337 return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12340 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12341 SDValue Src, SDValue Base, SDValue Index,
12342 SDValue ScaleOp, SDValue Chain) {
12344 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12345 assert(C && "Invalid scale type");
12346 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12347 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12348 SDValue Segment = DAG.getRegister(0, MVT::i32);
12349 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12350 Index.getSimpleValueType().getVectorNumElements());
12351 SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12352 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12353 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12354 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12355 return SDValue(Res, 1);
12358 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12359 SDValue Src, SDValue Mask, SDValue Base,
12360 SDValue Index, SDValue ScaleOp, SDValue Chain) {
12362 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12363 assert(C && "Invalid scale type");
12364 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12365 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12366 SDValue Segment = DAG.getRegister(0, MVT::i32);
12367 EVT MaskVT = MVT::getVectorVT(MVT::i1,
12368 Index.getSimpleValueType().getVectorNumElements());
12369 SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12370 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12371 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12372 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12373 return SDValue(Res, 1);
12376 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12377 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12378 // also used to custom lower READCYCLECOUNTER nodes.
12379 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12380 SelectionDAG &DAG, const X86Subtarget *Subtarget,
12381 SmallVectorImpl<SDValue> &Results) {
12382 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12383 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12386 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12387 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12388 // and the EAX register is loaded with the low-order 32 bits.
12389 if (Subtarget->is64Bit()) {
12390 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12391 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12394 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12395 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12398 SDValue Chain = HI.getValue(1);
12400 if (Opcode == X86ISD::RDTSCP_DAG) {
12401 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12403 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12404 // the ECX register. Add 'ecx' explicitly to the chain.
12405 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12407 // Explicitly store the content of ECX at the location passed in input
12408 // to the 'rdtscp' intrinsic.
12409 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12410 MachinePointerInfo(), false, false, 0);
12413 if (Subtarget->is64Bit()) {
12414 // The EDX register is loaded with the high-order 32 bits of the MSR, and
12415 // the EAX register is loaded with the low-order 32 bits.
12416 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12417 DAG.getConstant(32, MVT::i8));
12418 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12419 Results.push_back(Chain);
12423 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12424 SDValue Ops[] = { LO, HI };
12425 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12426 Results.push_back(Pair);
12427 Results.push_back(Chain);
12430 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12431 SelectionDAG &DAG) {
12432 SmallVector<SDValue, 2> Results;
12434 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12436 return DAG.getMergeValues(&Results[0], Results.size(), DL);
12439 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12440 SelectionDAG &DAG) {
12442 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12444 default: return SDValue(); // Don't custom lower most intrinsics.
12446 // RDRAND/RDSEED intrinsics.
12447 case Intrinsic::x86_rdrand_16:
12448 case Intrinsic::x86_rdrand_32:
12449 case Intrinsic::x86_rdrand_64:
12450 case Intrinsic::x86_rdseed_16:
12451 case Intrinsic::x86_rdseed_32:
12452 case Intrinsic::x86_rdseed_64: {
12453 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12454 IntNo == Intrinsic::x86_rdseed_32 ||
12455 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12457 // Emit the node with the right value type.
12458 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12459 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12461 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12462 // Otherwise return the value from Rand, which is always 0, casted to i32.
12463 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12464 DAG.getConstant(1, Op->getValueType(1)),
12465 DAG.getConstant(X86::COND_B, MVT::i32),
12466 SDValue(Result.getNode(), 1) };
12467 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12468 DAG.getVTList(Op->getValueType(1), MVT::Glue),
12471 // Return { result, isValid, chain }.
12472 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12473 SDValue(Result.getNode(), 2));
12475 //int_gather(index, base, scale);
12476 case Intrinsic::x86_avx512_gather_qpd_512:
12477 case Intrinsic::x86_avx512_gather_qps_512:
12478 case Intrinsic::x86_avx512_gather_dpd_512:
12479 case Intrinsic::x86_avx512_gather_qpi_512:
12480 case Intrinsic::x86_avx512_gather_qpq_512:
12481 case Intrinsic::x86_avx512_gather_dpq_512:
12482 case Intrinsic::x86_avx512_gather_dps_512:
12483 case Intrinsic::x86_avx512_gather_dpi_512: {
12486 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12487 case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12488 case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12489 case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12490 case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12491 case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12492 case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12493 case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12494 case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12496 SDValue Chain = Op.getOperand(0);
12497 SDValue Index = Op.getOperand(2);
12498 SDValue Base = Op.getOperand(3);
12499 SDValue Scale = Op.getOperand(4);
12500 return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12502 //int_gather_mask(v1, mask, index, base, scale);
12503 case Intrinsic::x86_avx512_gather_qps_mask_512:
12504 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12505 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12506 case Intrinsic::x86_avx512_gather_dps_mask_512:
12507 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12508 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12509 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12510 case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12513 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12514 case Intrinsic::x86_avx512_gather_qps_mask_512:
12515 Opc = X86::VGATHERQPSZrm; break;
12516 case Intrinsic::x86_avx512_gather_qpd_mask_512:
12517 Opc = X86::VGATHERQPDZrm; break;
12518 case Intrinsic::x86_avx512_gather_dpd_mask_512:
12519 Opc = X86::VGATHERDPDZrm; break;
12520 case Intrinsic::x86_avx512_gather_dps_mask_512:
12521 Opc = X86::VGATHERDPSZrm; break;
12522 case Intrinsic::x86_avx512_gather_qpi_mask_512:
12523 Opc = X86::VPGATHERQDZrm; break;
12524 case Intrinsic::x86_avx512_gather_qpq_mask_512:
12525 Opc = X86::VPGATHERQQZrm; break;
12526 case Intrinsic::x86_avx512_gather_dpi_mask_512:
12527 Opc = X86::VPGATHERDDZrm; break;
12528 case Intrinsic::x86_avx512_gather_dpq_mask_512:
12529 Opc = X86::VPGATHERDQZrm; break;
12531 SDValue Chain = Op.getOperand(0);
12532 SDValue Src = Op.getOperand(2);
12533 SDValue Mask = Op.getOperand(3);
12534 SDValue Index = Op.getOperand(4);
12535 SDValue Base = Op.getOperand(5);
12536 SDValue Scale = Op.getOperand(6);
12537 return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12540 //int_scatter(base, index, v1, scale);
12541 case Intrinsic::x86_avx512_scatter_qpd_512:
12542 case Intrinsic::x86_avx512_scatter_qps_512:
12543 case Intrinsic::x86_avx512_scatter_dpd_512:
12544 case Intrinsic::x86_avx512_scatter_qpi_512:
12545 case Intrinsic::x86_avx512_scatter_qpq_512:
12546 case Intrinsic::x86_avx512_scatter_dpq_512:
12547 case Intrinsic::x86_avx512_scatter_dps_512:
12548 case Intrinsic::x86_avx512_scatter_dpi_512: {
12551 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12552 case Intrinsic::x86_avx512_scatter_qpd_512:
12553 Opc = X86::VSCATTERQPDZmr; break;
12554 case Intrinsic::x86_avx512_scatter_qps_512:
12555 Opc = X86::VSCATTERQPSZmr; break;
12556 case Intrinsic::x86_avx512_scatter_dpd_512:
12557 Opc = X86::VSCATTERDPDZmr; break;
12558 case Intrinsic::x86_avx512_scatter_dps_512:
12559 Opc = X86::VSCATTERDPSZmr; break;
12560 case Intrinsic::x86_avx512_scatter_qpi_512:
12561 Opc = X86::VPSCATTERQDZmr; break;
12562 case Intrinsic::x86_avx512_scatter_qpq_512:
12563 Opc = X86::VPSCATTERQQZmr; break;
12564 case Intrinsic::x86_avx512_scatter_dpq_512:
12565 Opc = X86::VPSCATTERDQZmr; break;
12566 case Intrinsic::x86_avx512_scatter_dpi_512:
12567 Opc = X86::VPSCATTERDDZmr; break;
12569 SDValue Chain = Op.getOperand(0);
12570 SDValue Base = Op.getOperand(2);
12571 SDValue Index = Op.getOperand(3);
12572 SDValue Src = Op.getOperand(4);
12573 SDValue Scale = Op.getOperand(5);
12574 return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12576 //int_scatter_mask(base, mask, index, v1, scale);
12577 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12578 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12579 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12580 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12581 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12582 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12583 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12584 case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12587 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12588 case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12589 Opc = X86::VSCATTERQPDZmr; break;
12590 case Intrinsic::x86_avx512_scatter_qps_mask_512:
12591 Opc = X86::VSCATTERQPSZmr; break;
12592 case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12593 Opc = X86::VSCATTERDPDZmr; break;
12594 case Intrinsic::x86_avx512_scatter_dps_mask_512:
12595 Opc = X86::VSCATTERDPSZmr; break;
12596 case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12597 Opc = X86::VPSCATTERQDZmr; break;
12598 case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12599 Opc = X86::VPSCATTERQQZmr; break;
12600 case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12601 Opc = X86::VPSCATTERDQZmr; break;
12602 case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12603 Opc = X86::VPSCATTERDDZmr; break;
12605 SDValue Chain = Op.getOperand(0);
12606 SDValue Base = Op.getOperand(2);
12607 SDValue Mask = Op.getOperand(3);
12608 SDValue Index = Op.getOperand(4);
12609 SDValue Src = Op.getOperand(5);
12610 SDValue Scale = Op.getOperand(6);
12611 return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12613 // Read Time Stamp Counter (RDTSC).
12614 case Intrinsic::x86_rdtsc:
12615 // Read Time Stamp Counter and Processor ID (RDTSCP).
12616 case Intrinsic::x86_rdtscp: {
12619 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12620 case Intrinsic::x86_rdtsc:
12621 Opc = X86ISD::RDTSC_DAG; break;
12622 case Intrinsic::x86_rdtscp:
12623 Opc = X86ISD::RDTSCP_DAG; break;
12625 SmallVector<SDValue, 2> Results;
12626 getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12627 return DAG.getMergeValues(&Results[0], Results.size(), dl);
12629 // XTEST intrinsics.
12630 case Intrinsic::x86_xtest: {
12631 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12632 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12633 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12634 DAG.getConstant(X86::COND_NE, MVT::i8),
12636 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12637 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12638 Ret, SDValue(InTrans.getNode(), 1));
12643 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12644 SelectionDAG &DAG) const {
12645 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12646 MFI->setReturnAddressIsTaken(true);
12648 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12651 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12653 EVT PtrVT = getPointerTy();
12656 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12657 const X86RegisterInfo *RegInfo =
12658 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12659 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12660 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12661 DAG.getNode(ISD::ADD, dl, PtrVT,
12662 FrameAddr, Offset),
12663 MachinePointerInfo(), false, false, false, 0);
12666 // Just load the return address.
12667 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12668 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12669 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12672 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12673 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12674 MFI->setFrameAddressIsTaken(true);
12676 EVT VT = Op.getValueType();
12677 SDLoc dl(Op); // FIXME probably not meaningful
12678 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12679 const X86RegisterInfo *RegInfo =
12680 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12681 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12682 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12683 (FrameReg == X86::EBP && VT == MVT::i32)) &&
12684 "Invalid Frame Register!");
12685 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12687 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12688 MachinePointerInfo(),
12689 false, false, false, 0);
12693 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12694 SelectionDAG &DAG) const {
12695 const X86RegisterInfo *RegInfo =
12696 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12697 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12700 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12701 SDValue Chain = Op.getOperand(0);
12702 SDValue Offset = Op.getOperand(1);
12703 SDValue Handler = Op.getOperand(2);
12706 EVT PtrVT = getPointerTy();
12707 const X86RegisterInfo *RegInfo =
12708 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12709 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12710 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12711 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12712 "Invalid Frame Register!");
12713 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12714 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12716 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12717 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12718 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12719 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12721 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12723 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12724 DAG.getRegister(StoreAddrReg, PtrVT));
12727 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12728 SelectionDAG &DAG) const {
12730 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12731 DAG.getVTList(MVT::i32, MVT::Other),
12732 Op.getOperand(0), Op.getOperand(1));
12735 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12736 SelectionDAG &DAG) const {
12738 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12739 Op.getOperand(0), Op.getOperand(1));
12742 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12743 return Op.getOperand(0);
12746 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12747 SelectionDAG &DAG) const {
12748 SDValue Root = Op.getOperand(0);
12749 SDValue Trmp = Op.getOperand(1); // trampoline
12750 SDValue FPtr = Op.getOperand(2); // nested function
12751 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12754 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12755 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12757 if (Subtarget->is64Bit()) {
12758 SDValue OutChains[6];
12760 // Large code-model.
12761 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
12762 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12764 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12765 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12767 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12769 // Load the pointer to the nested function into R11.
12770 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12771 SDValue Addr = Trmp;
12772 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12773 Addr, MachinePointerInfo(TrmpAddr),
12776 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12777 DAG.getConstant(2, MVT::i64));
12778 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12779 MachinePointerInfo(TrmpAddr, 2),
12782 // Load the 'nest' parameter value into R10.
12783 // R10 is specified in X86CallingConv.td
12784 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12785 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12786 DAG.getConstant(10, MVT::i64));
12787 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12788 Addr, MachinePointerInfo(TrmpAddr, 10),
12791 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12792 DAG.getConstant(12, MVT::i64));
12793 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12794 MachinePointerInfo(TrmpAddr, 12),
12797 // Jump to the nested function.
12798 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12799 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12800 DAG.getConstant(20, MVT::i64));
12801 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12802 Addr, MachinePointerInfo(TrmpAddr, 20),
12805 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12806 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12807 DAG.getConstant(22, MVT::i64));
12808 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12809 MachinePointerInfo(TrmpAddr, 22),
12812 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12814 const Function *Func =
12815 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12816 CallingConv::ID CC = Func->getCallingConv();
12821 llvm_unreachable("Unsupported calling convention");
12822 case CallingConv::C:
12823 case CallingConv::X86_StdCall: {
12824 // Pass 'nest' parameter in ECX.
12825 // Must be kept in sync with X86CallingConv.td
12826 NestReg = X86::ECX;
12828 // Check that ECX wasn't needed by an 'inreg' parameter.
12829 FunctionType *FTy = Func->getFunctionType();
12830 const AttributeSet &Attrs = Func->getAttributes();
12832 if (!Attrs.isEmpty() && !Func->isVarArg()) {
12833 unsigned InRegCount = 0;
12836 for (FunctionType::param_iterator I = FTy->param_begin(),
12837 E = FTy->param_end(); I != E; ++I, ++Idx)
12838 if (Attrs.hasAttribute(Idx, Attribute::InReg))
12839 // FIXME: should only count parameters that are lowered to integers.
12840 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12842 if (InRegCount > 2) {
12843 report_fatal_error("Nest register in use - reduce number of inreg"
12849 case CallingConv::X86_FastCall:
12850 case CallingConv::X86_ThisCall:
12851 case CallingConv::Fast:
12852 // Pass 'nest' parameter in EAX.
12853 // Must be kept in sync with X86CallingConv.td
12854 NestReg = X86::EAX;
12858 SDValue OutChains[4];
12859 SDValue Addr, Disp;
12861 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12862 DAG.getConstant(10, MVT::i32));
12863 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12865 // This is storing the opcode for MOV32ri.
12866 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12867 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12868 OutChains[0] = DAG.getStore(Root, dl,
12869 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12870 Trmp, MachinePointerInfo(TrmpAddr),
12873 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12874 DAG.getConstant(1, MVT::i32));
12875 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12876 MachinePointerInfo(TrmpAddr, 1),
12879 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12880 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12881 DAG.getConstant(5, MVT::i32));
12882 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12883 MachinePointerInfo(TrmpAddr, 5),
12886 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12887 DAG.getConstant(6, MVT::i32));
12888 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12889 MachinePointerInfo(TrmpAddr, 6),
12892 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12896 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12897 SelectionDAG &DAG) const {
12899 The rounding mode is in bits 11:10 of FPSR, and has the following
12901 00 Round to nearest
12906 FLT_ROUNDS, on the other hand, expects the following:
12913 To perform the conversion, we do:
12914 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12917 MachineFunction &MF = DAG.getMachineFunction();
12918 const TargetMachine &TM = MF.getTarget();
12919 const TargetFrameLowering &TFI = *TM.getFrameLowering();
12920 unsigned StackAlignment = TFI.getStackAlignment();
12921 MVT VT = Op.getSimpleValueType();
12924 // Save FP Control Word to stack slot
12925 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12926 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12928 MachineMemOperand *MMO =
12929 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12930 MachineMemOperand::MOStore, 2, 2);
12932 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12933 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12934 DAG.getVTList(MVT::Other),
12935 Ops, array_lengthof(Ops), MVT::i16,
12938 // Load FP Control Word from stack slot
12939 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12940 MachinePointerInfo(), false, false, false, 0);
12942 // Transform as necessary
12944 DAG.getNode(ISD::SRL, DL, MVT::i16,
12945 DAG.getNode(ISD::AND, DL, MVT::i16,
12946 CWD, DAG.getConstant(0x800, MVT::i16)),
12947 DAG.getConstant(11, MVT::i8));
12949 DAG.getNode(ISD::SRL, DL, MVT::i16,
12950 DAG.getNode(ISD::AND, DL, MVT::i16,
12951 CWD, DAG.getConstant(0x400, MVT::i16)),
12952 DAG.getConstant(9, MVT::i8));
12955 DAG.getNode(ISD::AND, DL, MVT::i16,
12956 DAG.getNode(ISD::ADD, DL, MVT::i16,
12957 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12958 DAG.getConstant(1, MVT::i16)),
12959 DAG.getConstant(3, MVT::i16));
12961 return DAG.getNode((VT.getSizeInBits() < 16 ?
12962 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12965 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12966 MVT VT = Op.getSimpleValueType();
12968 unsigned NumBits = VT.getSizeInBits();
12971 Op = Op.getOperand(0);
12972 if (VT == MVT::i8) {
12973 // Zero extend to i32 since there is not an i8 bsr.
12975 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12978 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12979 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12980 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12982 // If src is zero (i.e. bsr sets ZF), returns NumBits.
12985 DAG.getConstant(NumBits+NumBits-1, OpVT),
12986 DAG.getConstant(X86::COND_E, MVT::i8),
12989 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
12991 // Finally xor with NumBits-1.
12992 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12995 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12999 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13000 MVT VT = Op.getSimpleValueType();
13002 unsigned NumBits = VT.getSizeInBits();
13005 Op = Op.getOperand(0);
13006 if (VT == MVT::i8) {
13007 // Zero extend to i32 since there is not an i8 bsr.
13009 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13012 // Issue a bsr (scan bits in reverse).
13013 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13014 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13016 // And xor with NumBits-1.
13017 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13020 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13024 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13025 MVT VT = Op.getSimpleValueType();
13026 unsigned NumBits = VT.getSizeInBits();
13028 Op = Op.getOperand(0);
13030 // Issue a bsf (scan bits forward) which also sets EFLAGS.
13031 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13032 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13034 // If src is zero (i.e. bsf sets ZF), returns NumBits.
13037 DAG.getConstant(NumBits, VT),
13038 DAG.getConstant(X86::COND_E, MVT::i8),
13041 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13044 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13045 // ones, and then concatenate the result back.
13046 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13047 MVT VT = Op.getSimpleValueType();
13049 assert(VT.is256BitVector() && VT.isInteger() &&
13050 "Unsupported value type for operation");
13052 unsigned NumElems = VT.getVectorNumElements();
13055 // Extract the LHS vectors
13056 SDValue LHS = Op.getOperand(0);
13057 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13058 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13060 // Extract the RHS vectors
13061 SDValue RHS = Op.getOperand(1);
13062 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13063 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13065 MVT EltVT = VT.getVectorElementType();
13066 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13068 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13069 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13070 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13073 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13074 assert(Op.getSimpleValueType().is256BitVector() &&
13075 Op.getSimpleValueType().isInteger() &&
13076 "Only handle AVX 256-bit vector integer operation");
13077 return Lower256IntArith(Op, DAG);
13080 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13081 assert(Op.getSimpleValueType().is256BitVector() &&
13082 Op.getSimpleValueType().isInteger() &&
13083 "Only handle AVX 256-bit vector integer operation");
13084 return Lower256IntArith(Op, DAG);
13087 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13088 SelectionDAG &DAG) {
13090 MVT VT = Op.getSimpleValueType();
13092 // Decompose 256-bit ops into smaller 128-bit ops.
13093 if (VT.is256BitVector() && !Subtarget->hasInt256())
13094 return Lower256IntArith(Op, DAG);
13096 SDValue A = Op.getOperand(0);
13097 SDValue B = Op.getOperand(1);
13099 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13100 if (VT == MVT::v4i32) {
13101 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13102 "Should not custom lower when pmuldq is available!");
13104 // Extract the odd parts.
13105 static const int UnpackMask[] = { 1, -1, 3, -1 };
13106 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13107 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13109 // Multiply the even parts.
13110 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13111 // Now multiply odd parts.
13112 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13114 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13115 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13117 // Merge the two vectors back together with a shuffle. This expands into 2
13119 static const int ShufMask[] = { 0, 4, 2, 6 };
13120 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13123 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13124 "Only know how to lower V2I64/V4I64/V8I64 multiply");
13126 // Ahi = psrlqi(a, 32);
13127 // Bhi = psrlqi(b, 32);
13129 // AloBlo = pmuludq(a, b);
13130 // AloBhi = pmuludq(a, Bhi);
13131 // AhiBlo = pmuludq(Ahi, b);
13133 // AloBhi = psllqi(AloBhi, 32);
13134 // AhiBlo = psllqi(AhiBlo, 32);
13135 // return AloBlo + AloBhi + AhiBlo;
13137 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13138 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13140 // Bit cast to 32-bit vectors for MULUDQ
13141 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13142 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13143 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13144 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13145 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13146 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13148 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13149 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13150 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13152 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13153 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13155 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13156 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13159 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13160 SelectionDAG &DAG) {
13161 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13162 EVT VT = Op0.getValueType();
13165 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13166 (VT == MVT::v8i32 && Subtarget->hasInt256()));
13168 // Get the high parts.
13169 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13170 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13171 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13173 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13175 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13177 Op->getOpcode() == ISD::UMUL_LOHI ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13178 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13179 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13180 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13181 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13183 // Shuffle it back into the right order.
13184 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13185 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13186 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13187 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13189 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13192 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13193 const X86Subtarget *Subtarget) {
13194 MVT VT = Op.getSimpleValueType();
13196 SDValue R = Op.getOperand(0);
13197 SDValue Amt = Op.getOperand(1);
13199 // Optimize shl/srl/sra with constant shift amount.
13200 if (isSplatVector(Amt.getNode())) {
13201 SDValue SclrAmt = Amt->getOperand(0);
13202 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13203 uint64_t ShiftAmt = C->getZExtValue();
13205 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13206 (Subtarget->hasInt256() &&
13207 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13208 (Subtarget->hasAVX512() &&
13209 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13210 if (Op.getOpcode() == ISD::SHL)
13211 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13213 if (Op.getOpcode() == ISD::SRL)
13214 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13216 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13217 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13221 if (VT == MVT::v16i8) {
13222 if (Op.getOpcode() == ISD::SHL) {
13223 // Make a large shift.
13224 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13225 MVT::v8i16, R, ShiftAmt,
13227 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13228 // Zero out the rightmost bits.
13229 SmallVector<SDValue, 16> V(16,
13230 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13232 return DAG.getNode(ISD::AND, dl, VT, SHL,
13233 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13235 if (Op.getOpcode() == ISD::SRL) {
13236 // Make a large shift.
13237 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13238 MVT::v8i16, R, ShiftAmt,
13240 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13241 // Zero out the leftmost bits.
13242 SmallVector<SDValue, 16> V(16,
13243 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13245 return DAG.getNode(ISD::AND, dl, VT, SRL,
13246 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13248 if (Op.getOpcode() == ISD::SRA) {
13249 if (ShiftAmt == 7) {
13250 // R s>> 7 === R s< 0
13251 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13252 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13255 // R s>> a === ((R u>> a) ^ m) - m
13256 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13257 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13259 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13260 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13261 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13264 llvm_unreachable("Unknown shift opcode.");
13267 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13268 if (Op.getOpcode() == ISD::SHL) {
13269 // Make a large shift.
13270 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13271 MVT::v16i16, R, ShiftAmt,
13273 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13274 // Zero out the rightmost bits.
13275 SmallVector<SDValue, 32> V(32,
13276 DAG.getConstant(uint8_t(-1U << ShiftAmt),
13278 return DAG.getNode(ISD::AND, dl, VT, SHL,
13279 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13281 if (Op.getOpcode() == ISD::SRL) {
13282 // Make a large shift.
13283 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13284 MVT::v16i16, R, ShiftAmt,
13286 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13287 // Zero out the leftmost bits.
13288 SmallVector<SDValue, 32> V(32,
13289 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13291 return DAG.getNode(ISD::AND, dl, VT, SRL,
13292 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13294 if (Op.getOpcode() == ISD::SRA) {
13295 if (ShiftAmt == 7) {
13296 // R s>> 7 === R s< 0
13297 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13298 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13301 // R s>> a === ((R u>> a) ^ m) - m
13302 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13303 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13305 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13306 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13307 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13310 llvm_unreachable("Unknown shift opcode.");
13315 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13316 if (!Subtarget->is64Bit() &&
13317 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13318 Amt.getOpcode() == ISD::BITCAST &&
13319 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13320 Amt = Amt.getOperand(0);
13321 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13322 VT.getVectorNumElements();
13323 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13324 uint64_t ShiftAmt = 0;
13325 for (unsigned i = 0; i != Ratio; ++i) {
13326 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13330 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13332 // Check remaining shift amounts.
13333 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13334 uint64_t ShAmt = 0;
13335 for (unsigned j = 0; j != Ratio; ++j) {
13336 ConstantSDNode *C =
13337 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13341 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13343 if (ShAmt != ShiftAmt)
13346 switch (Op.getOpcode()) {
13348 llvm_unreachable("Unknown shift opcode!");
13350 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13353 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13356 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13364 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13365 const X86Subtarget* Subtarget) {
13366 MVT VT = Op.getSimpleValueType();
13368 SDValue R = Op.getOperand(0);
13369 SDValue Amt = Op.getOperand(1);
13371 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13372 VT == MVT::v4i32 || VT == MVT::v8i16 ||
13373 (Subtarget->hasInt256() &&
13374 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13375 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13376 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13378 EVT EltVT = VT.getVectorElementType();
13380 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13381 unsigned NumElts = VT.getVectorNumElements();
13383 for (i = 0; i != NumElts; ++i) {
13384 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13388 for (j = i; j != NumElts; ++j) {
13389 SDValue Arg = Amt.getOperand(j);
13390 if (Arg.getOpcode() == ISD::UNDEF) continue;
13391 if (Arg != Amt.getOperand(i))
13394 if (i != NumElts && j == NumElts)
13395 BaseShAmt = Amt.getOperand(i);
13397 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13398 Amt = Amt.getOperand(0);
13399 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13400 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13401 SDValue InVec = Amt.getOperand(0);
13402 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13403 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13405 for (; i != NumElts; ++i) {
13406 SDValue Arg = InVec.getOperand(i);
13407 if (Arg.getOpcode() == ISD::UNDEF) continue;
13411 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13412 if (ConstantSDNode *C =
13413 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13414 unsigned SplatIdx =
13415 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13416 if (C->getZExtValue() == SplatIdx)
13417 BaseShAmt = InVec.getOperand(1);
13420 if (!BaseShAmt.getNode())
13421 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13422 DAG.getIntPtrConstant(0));
13426 if (BaseShAmt.getNode()) {
13427 if (EltVT.bitsGT(MVT::i32))
13428 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13429 else if (EltVT.bitsLT(MVT::i32))
13430 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13432 switch (Op.getOpcode()) {
13434 llvm_unreachable("Unknown shift opcode!");
13436 switch (VT.SimpleTy) {
13437 default: return SDValue();
13446 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13449 switch (VT.SimpleTy) {
13450 default: return SDValue();
13457 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13460 switch (VT.SimpleTy) {
13461 default: return SDValue();
13470 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13476 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13477 if (!Subtarget->is64Bit() &&
13478 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13479 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13480 Amt.getOpcode() == ISD::BITCAST &&
13481 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13482 Amt = Amt.getOperand(0);
13483 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13484 VT.getVectorNumElements();
13485 std::vector<SDValue> Vals(Ratio);
13486 for (unsigned i = 0; i != Ratio; ++i)
13487 Vals[i] = Amt.getOperand(i);
13488 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13489 for (unsigned j = 0; j != Ratio; ++j)
13490 if (Vals[j] != Amt.getOperand(i + j))
13493 switch (Op.getOpcode()) {
13495 llvm_unreachable("Unknown shift opcode!");
13497 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13499 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13501 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13508 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13509 SelectionDAG &DAG) {
13511 MVT VT = Op.getSimpleValueType();
13513 SDValue R = Op.getOperand(0);
13514 SDValue Amt = Op.getOperand(1);
13517 if (!Subtarget->hasSSE2())
13520 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13524 V = LowerScalarVariableShift(Op, DAG, Subtarget);
13528 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13530 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13531 if (Subtarget->hasInt256()) {
13532 if (Op.getOpcode() == ISD::SRL &&
13533 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13534 VT == MVT::v4i64 || VT == MVT::v8i32))
13536 if (Op.getOpcode() == ISD::SHL &&
13537 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13538 VT == MVT::v4i64 || VT == MVT::v8i32))
13540 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13544 // If possible, lower this packed shift into a vector multiply instead of
13545 // expanding it into a sequence of scalar shifts.
13546 // Do this only if the vector shift count is a constant build_vector.
13547 if (Op.getOpcode() == ISD::SHL &&
13548 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13549 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13550 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13551 SmallVector<SDValue, 8> Elts;
13552 EVT SVT = VT.getScalarType();
13553 unsigned SVTBits = SVT.getSizeInBits();
13554 const APInt &One = APInt(SVTBits, 1);
13555 unsigned NumElems = VT.getVectorNumElements();
13557 for (unsigned i=0; i !=NumElems; ++i) {
13558 SDValue Op = Amt->getOperand(i);
13559 if (Op->getOpcode() == ISD::UNDEF) {
13560 Elts.push_back(Op);
13564 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13565 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13566 uint64_t ShAmt = C.getZExtValue();
13567 if (ShAmt >= SVTBits) {
13568 Elts.push_back(DAG.getUNDEF(SVT));
13571 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13573 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13574 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13577 // Lower SHL with variable shift amount.
13578 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13579 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13581 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13582 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13583 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13584 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13587 // If possible, lower this shift as a sequence of two shifts by
13588 // constant plus a MOVSS/MOVSD instead of scalarizing it.
13590 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13592 // Could be rewritten as:
13593 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13595 // The advantage is that the two shifts from the example would be
13596 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13597 // the vector shift into four scalar shifts plus four pairs of vector
13599 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13600 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13601 unsigned TargetOpcode = X86ISD::MOVSS;
13602 bool CanBeSimplified;
13603 // The splat value for the first packed shift (the 'X' from the example).
13604 SDValue Amt1 = Amt->getOperand(0);
13605 // The splat value for the second packed shift (the 'Y' from the example).
13606 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13607 Amt->getOperand(2);
13609 // See if it is possible to replace this node with a sequence of
13610 // two shifts followed by a MOVSS/MOVSD
13611 if (VT == MVT::v4i32) {
13612 // Check if it is legal to use a MOVSS.
13613 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13614 Amt2 == Amt->getOperand(3);
13615 if (!CanBeSimplified) {
13616 // Otherwise, check if we can still simplify this node using a MOVSD.
13617 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13618 Amt->getOperand(2) == Amt->getOperand(3);
13619 TargetOpcode = X86ISD::MOVSD;
13620 Amt2 = Amt->getOperand(2);
13623 // Do similar checks for the case where the machine value type
13625 CanBeSimplified = Amt1 == Amt->getOperand(1);
13626 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13627 CanBeSimplified = Amt2 == Amt->getOperand(i);
13629 if (!CanBeSimplified) {
13630 TargetOpcode = X86ISD::MOVSD;
13631 CanBeSimplified = true;
13632 Amt2 = Amt->getOperand(4);
13633 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13634 CanBeSimplified = Amt1 == Amt->getOperand(i);
13635 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13636 CanBeSimplified = Amt2 == Amt->getOperand(j);
13640 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13641 isa<ConstantSDNode>(Amt2)) {
13642 // Replace this node with two shifts followed by a MOVSS/MOVSD.
13643 EVT CastVT = MVT::v4i32;
13645 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13646 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13648 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13649 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13650 if (TargetOpcode == X86ISD::MOVSD)
13651 CastVT = MVT::v2i64;
13652 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13653 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13654 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13656 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13660 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13661 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13664 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13665 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13667 // Turn 'a' into a mask suitable for VSELECT
13668 SDValue VSelM = DAG.getConstant(0x80, VT);
13669 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13670 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13672 SDValue CM1 = DAG.getConstant(0x0f, VT);
13673 SDValue CM2 = DAG.getConstant(0x3f, VT);
13675 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13676 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13677 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13678 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13679 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13682 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13683 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13684 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13686 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13687 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13688 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13689 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13690 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13693 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13694 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13695 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13697 // return VSELECT(r, r+r, a);
13698 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13699 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13703 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13704 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13705 // solution better.
13706 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13707 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13709 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13710 R = DAG.getNode(ExtOpc, dl, NewVT, R);
13711 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13712 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13713 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13716 // Decompose 256-bit shifts into smaller 128-bit shifts.
13717 if (VT.is256BitVector()) {
13718 unsigned NumElems = VT.getVectorNumElements();
13719 MVT EltVT = VT.getVectorElementType();
13720 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13722 // Extract the two vectors
13723 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13724 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13726 // Recreate the shift amount vectors
13727 SDValue Amt1, Amt2;
13728 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13729 // Constant shift amount
13730 SmallVector<SDValue, 4> Amt1Csts;
13731 SmallVector<SDValue, 4> Amt2Csts;
13732 for (unsigned i = 0; i != NumElems/2; ++i)
13733 Amt1Csts.push_back(Amt->getOperand(i));
13734 for (unsigned i = NumElems/2; i != NumElems; ++i)
13735 Amt2Csts.push_back(Amt->getOperand(i));
13737 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13738 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13740 // Variable shift amount
13741 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13742 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13745 // Issue new vector shifts for the smaller types
13746 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13747 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13749 // Concatenate the result back
13750 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13756 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13757 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13758 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13759 // looks for this combo and may remove the "setcc" instruction if the "setcc"
13760 // has only one use.
13761 SDNode *N = Op.getNode();
13762 SDValue LHS = N->getOperand(0);
13763 SDValue RHS = N->getOperand(1);
13764 unsigned BaseOp = 0;
13767 switch (Op.getOpcode()) {
13768 default: llvm_unreachable("Unknown ovf instruction!");
13770 // A subtract of one will be selected as a INC. Note that INC doesn't
13771 // set CF, so we can't do this for UADDO.
13772 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13774 BaseOp = X86ISD::INC;
13775 Cond = X86::COND_O;
13778 BaseOp = X86ISD::ADD;
13779 Cond = X86::COND_O;
13782 BaseOp = X86ISD::ADD;
13783 Cond = X86::COND_B;
13786 // A subtract of one will be selected as a DEC. Note that DEC doesn't
13787 // set CF, so we can't do this for USUBO.
13788 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13790 BaseOp = X86ISD::DEC;
13791 Cond = X86::COND_O;
13794 BaseOp = X86ISD::SUB;
13795 Cond = X86::COND_O;
13798 BaseOp = X86ISD::SUB;
13799 Cond = X86::COND_B;
13802 BaseOp = X86ISD::SMUL;
13803 Cond = X86::COND_O;
13805 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13806 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13808 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13811 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13812 DAG.getConstant(X86::COND_O, MVT::i32),
13813 SDValue(Sum.getNode(), 2));
13815 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13819 // Also sets EFLAGS.
13820 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13821 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13824 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13825 DAG.getConstant(Cond, MVT::i32),
13826 SDValue(Sum.getNode(), 1));
13828 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13831 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13832 SelectionDAG &DAG) const {
13834 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13835 MVT VT = Op.getSimpleValueType();
13837 if (!Subtarget->hasSSE2() || !VT.isVector())
13840 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13841 ExtraVT.getScalarType().getSizeInBits();
13843 switch (VT.SimpleTy) {
13844 default: return SDValue();
13847 if (!Subtarget->hasFp256())
13849 if (!Subtarget->hasInt256()) {
13850 // needs to be split
13851 unsigned NumElems = VT.getVectorNumElements();
13853 // Extract the LHS vectors
13854 SDValue LHS = Op.getOperand(0);
13855 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13856 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13858 MVT EltVT = VT.getVectorElementType();
13859 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13861 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13862 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13863 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13865 SDValue Extra = DAG.getValueType(ExtraVT);
13867 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13868 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13870 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13875 SDValue Op0 = Op.getOperand(0);
13876 SDValue Op00 = Op0.getOperand(0);
13878 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13879 if (Op0.getOpcode() == ISD::BITCAST &&
13880 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13881 // (sext (vzext x)) -> (vsext x)
13882 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13883 if (Tmp1.getNode()) {
13884 EVT ExtraEltVT = ExtraVT.getVectorElementType();
13885 // This folding is only valid when the in-reg type is a vector of i8,
13887 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13888 ExtraEltVT == MVT::i32) {
13889 SDValue Tmp1Op0 = Tmp1.getOperand(0);
13890 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13891 "This optimization is invalid without a VZEXT.");
13892 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13898 // If the above didn't work, then just use Shift-Left + Shift-Right.
13899 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13901 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13907 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13908 SelectionDAG &DAG) {
13910 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13911 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13912 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13913 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13915 // The only fence that needs an instruction is a sequentially-consistent
13916 // cross-thread fence.
13917 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13918 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13919 // no-sse2). There isn't any reason to disable it if the target processor
13921 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13922 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13924 SDValue Chain = Op.getOperand(0);
13925 SDValue Zero = DAG.getConstant(0, MVT::i32);
13927 DAG.getRegister(X86::ESP, MVT::i32), // Base
13928 DAG.getTargetConstant(1, MVT::i8), // Scale
13929 DAG.getRegister(0, MVT::i32), // Index
13930 DAG.getTargetConstant(0, MVT::i32), // Disp
13931 DAG.getRegister(0, MVT::i32), // Segment.
13935 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13936 return SDValue(Res, 0);
13939 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13940 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13943 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13944 SelectionDAG &DAG) {
13945 MVT T = Op.getSimpleValueType();
13949 switch(T.SimpleTy) {
13950 default: llvm_unreachable("Invalid value type!");
13951 case MVT::i8: Reg = X86::AL; size = 1; break;
13952 case MVT::i16: Reg = X86::AX; size = 2; break;
13953 case MVT::i32: Reg = X86::EAX; size = 4; break;
13955 assert(Subtarget->is64Bit() && "Node not type legal!");
13956 Reg = X86::RAX; size = 8;
13959 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13960 Op.getOperand(2), SDValue());
13961 SDValue Ops[] = { cpIn.getValue(0),
13964 DAG.getTargetConstant(size, MVT::i8),
13965 cpIn.getValue(1) };
13966 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13967 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13968 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13969 Ops, array_lengthof(Ops), T, MMO);
13971 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13975 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13976 SelectionDAG &DAG) {
13977 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13978 MVT DstVT = Op.getSimpleValueType();
13979 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13980 Subtarget->hasMMX() && "Unexpected custom BITCAST");
13981 assert((DstVT == MVT::i64 ||
13982 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13983 "Unexpected custom BITCAST");
13984 // i64 <=> MMX conversions are Legal.
13985 if (SrcVT==MVT::i64 && DstVT.isVector())
13987 if (DstVT==MVT::i64 && SrcVT.isVector())
13989 // MMX <=> MMX conversions are Legal.
13990 if (SrcVT.isVector() && DstVT.isVector())
13992 // All other conversions need to be expanded.
13996 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13997 SDNode *Node = Op.getNode();
13999 EVT T = Node->getValueType(0);
14000 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14001 DAG.getConstant(0, T), Node->getOperand(2));
14002 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14003 cast<AtomicSDNode>(Node)->getMemoryVT(),
14004 Node->getOperand(0),
14005 Node->getOperand(1), negOp,
14006 cast<AtomicSDNode>(Node)->getMemOperand(),
14007 cast<AtomicSDNode>(Node)->getOrdering(),
14008 cast<AtomicSDNode>(Node)->getSynchScope());
14011 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14012 SDNode *Node = Op.getNode();
14014 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14016 // Convert seq_cst store -> xchg
14017 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14018 // FIXME: On 32-bit, store -> fist or movq would be more efficient
14019 // (The only way to get a 16-byte store is cmpxchg16b)
14020 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14021 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14022 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14023 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14024 cast<AtomicSDNode>(Node)->getMemoryVT(),
14025 Node->getOperand(0),
14026 Node->getOperand(1), Node->getOperand(2),
14027 cast<AtomicSDNode>(Node)->getMemOperand(),
14028 cast<AtomicSDNode>(Node)->getOrdering(),
14029 cast<AtomicSDNode>(Node)->getSynchScope());
14030 return Swap.getValue(1);
14032 // Other atomic stores have a simple pattern.
14036 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14037 EVT VT = Op.getNode()->getSimpleValueType(0);
14039 // Let legalize expand this if it isn't a legal type yet.
14040 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14043 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14046 bool ExtraOp = false;
14047 switch (Op.getOpcode()) {
14048 default: llvm_unreachable("Invalid code");
14049 case ISD::ADDC: Opc = X86ISD::ADD; break;
14050 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14051 case ISD::SUBC: Opc = X86ISD::SUB; break;
14052 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14056 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14058 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14059 Op.getOperand(1), Op.getOperand(2));
14062 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14063 SelectionDAG &DAG) {
14064 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14066 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14067 // which returns the values as { float, float } (in XMM0) or
14068 // { double, double } (which is returned in XMM0, XMM1).
14070 SDValue Arg = Op.getOperand(0);
14071 EVT ArgVT = Arg.getValueType();
14072 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14074 TargetLowering::ArgListTy Args;
14075 TargetLowering::ArgListEntry Entry;
14079 Entry.isSExt = false;
14080 Entry.isZExt = false;
14081 Args.push_back(Entry);
14083 bool isF64 = ArgVT == MVT::f64;
14084 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14085 // the small struct {f32, f32} is returned in (eax, edx). For f64,
14086 // the results are returned via SRet in memory.
14087 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
14088 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14089 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14091 Type *RetTy = isF64
14092 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14093 : (Type*)VectorType::get(ArgTy, 4);
14095 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14096 false, false, false, false, 0,
14097 CallingConv::C, /*isTaillCall=*/false,
14098 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14099 Callee, Args, DAG, dl);
14100 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14103 // Returned in xmm0 and xmm1.
14104 return CallResult.first;
14106 // Returned in bits 0:31 and 32:64 xmm0.
14107 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14108 CallResult.first, DAG.getIntPtrConstant(0));
14109 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14110 CallResult.first, DAG.getIntPtrConstant(1));
14111 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14112 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14115 /// LowerOperation - Provide custom lowering hooks for some operations.
14117 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14118 switch (Op.getOpcode()) {
14119 default: llvm_unreachable("Should not custom lower this!");
14120 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
14121 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14122 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
14123 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
14124 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
14125 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
14126 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
14127 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
14128 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14129 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
14130 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14131 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14132 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
14133 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
14134 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
14135 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
14136 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
14137 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
14138 case ISD::SHL_PARTS:
14139 case ISD::SRA_PARTS:
14140 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
14141 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
14142 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
14143 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
14144 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
14145 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14146 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
14147 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
14148 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
14149 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
14150 case ISD::FABS: return LowerFABS(Op, DAG);
14151 case ISD::FNEG: return LowerFNEG(Op, DAG);
14152 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
14153 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
14154 case ISD::SETCC: return LowerSETCC(Op, DAG);
14155 case ISD::SELECT: return LowerSELECT(Op, DAG);
14156 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
14157 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
14158 case ISD::VASTART: return LowerVASTART(Op, DAG);
14159 case ISD::VAARG: return LowerVAARG(Op, DAG);
14160 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
14161 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14162 case ISD::INTRINSIC_VOID:
14163 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14164 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
14165 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
14166 case ISD::FRAME_TO_ARGS_OFFSET:
14167 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14168 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14169 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
14170 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
14171 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
14172 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
14173 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
14174 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
14175 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
14176 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14177 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
14178 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
14179 case ISD::UMUL_LOHI:
14180 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
14183 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
14189 case ISD::UMULO: return LowerXALUO(Op, DAG);
14190 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14191 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
14195 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14196 case ISD::ADD: return LowerADD(Op, DAG);
14197 case ISD::SUB: return LowerSUB(Op, DAG);
14198 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
14202 static void ReplaceATOMIC_LOAD(SDNode *Node,
14203 SmallVectorImpl<SDValue> &Results,
14204 SelectionDAG &DAG) {
14206 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14208 // Convert wide load -> cmpxchg8b/cmpxchg16b
14209 // FIXME: On 32-bit, load -> fild or movq would be more efficient
14210 // (The only way to get a 16-byte load is cmpxchg16b)
14211 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14212 SDValue Zero = DAG.getConstant(0, VT);
14213 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14214 Node->getOperand(0),
14215 Node->getOperand(1), Zero, Zero,
14216 cast<AtomicSDNode>(Node)->getMemOperand(),
14217 cast<AtomicSDNode>(Node)->getOrdering(),
14218 cast<AtomicSDNode>(Node)->getOrdering(),
14219 cast<AtomicSDNode>(Node)->getSynchScope());
14220 Results.push_back(Swap.getValue(0));
14221 Results.push_back(Swap.getValue(1));
14225 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14226 SelectionDAG &DAG, unsigned NewOp) {
14228 assert (Node->getValueType(0) == MVT::i64 &&
14229 "Only know how to expand i64 atomics");
14231 SDValue Chain = Node->getOperand(0);
14232 SDValue In1 = Node->getOperand(1);
14233 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14234 Node->getOperand(2), DAG.getIntPtrConstant(0));
14235 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14236 Node->getOperand(2), DAG.getIntPtrConstant(1));
14237 SDValue Ops[] = { Chain, In1, In2L, In2H };
14238 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14240 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14241 cast<MemSDNode>(Node)->getMemOperand());
14242 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14243 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14244 Results.push_back(Result.getValue(2));
14247 /// ReplaceNodeResults - Replace a node with an illegal result type
14248 /// with a new node built out of custom code.
14249 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14250 SmallVectorImpl<SDValue>&Results,
14251 SelectionDAG &DAG) const {
14253 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14254 switch (N->getOpcode()) {
14256 llvm_unreachable("Do not know how to custom type legalize this operation!");
14257 case ISD::SIGN_EXTEND_INREG:
14262 // We don't want to expand or promote these.
14264 case ISD::FP_TO_SINT:
14265 case ISD::FP_TO_UINT: {
14266 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14268 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14271 std::pair<SDValue,SDValue> Vals =
14272 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14273 SDValue FIST = Vals.first, StackSlot = Vals.second;
14274 if (FIST.getNode()) {
14275 EVT VT = N->getValueType(0);
14276 // Return a load from the stack slot.
14277 if (StackSlot.getNode())
14278 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14279 MachinePointerInfo(),
14280 false, false, false, 0));
14282 Results.push_back(FIST);
14286 case ISD::UINT_TO_FP: {
14287 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14288 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14289 N->getValueType(0) != MVT::v2f32)
14291 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14293 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14295 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14296 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14297 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14298 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14299 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14300 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14303 case ISD::FP_ROUND: {
14304 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14306 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14307 Results.push_back(V);
14310 case ISD::INTRINSIC_W_CHAIN: {
14311 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14313 default : llvm_unreachable("Do not know how to custom type "
14314 "legalize this intrinsic operation!");
14315 case Intrinsic::x86_rdtsc:
14316 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14318 case Intrinsic::x86_rdtscp:
14319 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14323 case ISD::READCYCLECOUNTER: {
14324 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14327 case ISD::ATOMIC_CMP_SWAP: {
14328 EVT T = N->getValueType(0);
14329 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14330 bool Regs64bit = T == MVT::i128;
14331 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14332 SDValue cpInL, cpInH;
14333 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14334 DAG.getConstant(0, HalfT));
14335 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14336 DAG.getConstant(1, HalfT));
14337 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14338 Regs64bit ? X86::RAX : X86::EAX,
14340 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14341 Regs64bit ? X86::RDX : X86::EDX,
14342 cpInH, cpInL.getValue(1));
14343 SDValue swapInL, swapInH;
14344 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14345 DAG.getConstant(0, HalfT));
14346 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14347 DAG.getConstant(1, HalfT));
14348 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14349 Regs64bit ? X86::RBX : X86::EBX,
14350 swapInL, cpInH.getValue(1));
14351 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14352 Regs64bit ? X86::RCX : X86::ECX,
14353 swapInH, swapInL.getValue(1));
14354 SDValue Ops[] = { swapInH.getValue(0),
14356 swapInH.getValue(1) };
14357 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14358 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14359 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14360 X86ISD::LCMPXCHG8_DAG;
14361 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14362 Ops, array_lengthof(Ops), T, MMO);
14363 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14364 Regs64bit ? X86::RAX : X86::EAX,
14365 HalfT, Result.getValue(1));
14366 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14367 Regs64bit ? X86::RDX : X86::EDX,
14368 HalfT, cpOutL.getValue(2));
14369 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14370 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14371 Results.push_back(cpOutH.getValue(1));
14374 case ISD::ATOMIC_LOAD_ADD:
14375 case ISD::ATOMIC_LOAD_AND:
14376 case ISD::ATOMIC_LOAD_NAND:
14377 case ISD::ATOMIC_LOAD_OR:
14378 case ISD::ATOMIC_LOAD_SUB:
14379 case ISD::ATOMIC_LOAD_XOR:
14380 case ISD::ATOMIC_LOAD_MAX:
14381 case ISD::ATOMIC_LOAD_MIN:
14382 case ISD::ATOMIC_LOAD_UMAX:
14383 case ISD::ATOMIC_LOAD_UMIN:
14384 case ISD::ATOMIC_SWAP: {
14386 switch (N->getOpcode()) {
14387 default: llvm_unreachable("Unexpected opcode");
14388 case ISD::ATOMIC_LOAD_ADD:
14389 Opc = X86ISD::ATOMADD64_DAG;
14391 case ISD::ATOMIC_LOAD_AND:
14392 Opc = X86ISD::ATOMAND64_DAG;
14394 case ISD::ATOMIC_LOAD_NAND:
14395 Opc = X86ISD::ATOMNAND64_DAG;
14397 case ISD::ATOMIC_LOAD_OR:
14398 Opc = X86ISD::ATOMOR64_DAG;
14400 case ISD::ATOMIC_LOAD_SUB:
14401 Opc = X86ISD::ATOMSUB64_DAG;
14403 case ISD::ATOMIC_LOAD_XOR:
14404 Opc = X86ISD::ATOMXOR64_DAG;
14406 case ISD::ATOMIC_LOAD_MAX:
14407 Opc = X86ISD::ATOMMAX64_DAG;
14409 case ISD::ATOMIC_LOAD_MIN:
14410 Opc = X86ISD::ATOMMIN64_DAG;
14412 case ISD::ATOMIC_LOAD_UMAX:
14413 Opc = X86ISD::ATOMUMAX64_DAG;
14415 case ISD::ATOMIC_LOAD_UMIN:
14416 Opc = X86ISD::ATOMUMIN64_DAG;
14418 case ISD::ATOMIC_SWAP:
14419 Opc = X86ISD::ATOMSWAP64_DAG;
14422 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14425 case ISD::ATOMIC_LOAD:
14426 ReplaceATOMIC_LOAD(N, Results, DAG);
14430 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14432 default: return nullptr;
14433 case X86ISD::BSF: return "X86ISD::BSF";
14434 case X86ISD::BSR: return "X86ISD::BSR";
14435 case X86ISD::SHLD: return "X86ISD::SHLD";
14436 case X86ISD::SHRD: return "X86ISD::SHRD";
14437 case X86ISD::FAND: return "X86ISD::FAND";
14438 case X86ISD::FANDN: return "X86ISD::FANDN";
14439 case X86ISD::FOR: return "X86ISD::FOR";
14440 case X86ISD::FXOR: return "X86ISD::FXOR";
14441 case X86ISD::FSRL: return "X86ISD::FSRL";
14442 case X86ISD::FILD: return "X86ISD::FILD";
14443 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
14444 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14445 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14446 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14447 case X86ISD::FLD: return "X86ISD::FLD";
14448 case X86ISD::FST: return "X86ISD::FST";
14449 case X86ISD::CALL: return "X86ISD::CALL";
14450 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
14451 case X86ISD::BT: return "X86ISD::BT";
14452 case X86ISD::CMP: return "X86ISD::CMP";
14453 case X86ISD::COMI: return "X86ISD::COMI";
14454 case X86ISD::UCOMI: return "X86ISD::UCOMI";
14455 case X86ISD::CMPM: return "X86ISD::CMPM";
14456 case X86ISD::CMPMU: return "X86ISD::CMPMU";
14457 case X86ISD::SETCC: return "X86ISD::SETCC";
14458 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
14459 case X86ISD::FSETCC: return "X86ISD::FSETCC";
14460 case X86ISD::CMOV: return "X86ISD::CMOV";
14461 case X86ISD::BRCOND: return "X86ISD::BRCOND";
14462 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
14463 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
14464 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
14465 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
14466 case X86ISD::Wrapper: return "X86ISD::Wrapper";
14467 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
14468 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
14469 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
14470 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
14471 case X86ISD::PINSRB: return "X86ISD::PINSRB";
14472 case X86ISD::PINSRW: return "X86ISD::PINSRW";
14473 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
14474 case X86ISD::ANDNP: return "X86ISD::ANDNP";
14475 case X86ISD::PSIGN: return "X86ISD::PSIGN";
14476 case X86ISD::BLENDV: return "X86ISD::BLENDV";
14477 case X86ISD::BLENDI: return "X86ISD::BLENDI";
14478 case X86ISD::SUBUS: return "X86ISD::SUBUS";
14479 case X86ISD::HADD: return "X86ISD::HADD";
14480 case X86ISD::HSUB: return "X86ISD::HSUB";
14481 case X86ISD::FHADD: return "X86ISD::FHADD";
14482 case X86ISD::FHSUB: return "X86ISD::FHSUB";
14483 case X86ISD::UMAX: return "X86ISD::UMAX";
14484 case X86ISD::UMIN: return "X86ISD::UMIN";
14485 case X86ISD::SMAX: return "X86ISD::SMAX";
14486 case X86ISD::SMIN: return "X86ISD::SMIN";
14487 case X86ISD::FMAX: return "X86ISD::FMAX";
14488 case X86ISD::FMIN: return "X86ISD::FMIN";
14489 case X86ISD::FMAXC: return "X86ISD::FMAXC";
14490 case X86ISD::FMINC: return "X86ISD::FMINC";
14491 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
14492 case X86ISD::FRCP: return "X86ISD::FRCP";
14493 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
14494 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
14495 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
14496 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
14497 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
14498 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
14499 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
14500 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
14501 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
14502 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
14503 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
14504 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
14505 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
14506 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
14507 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
14508 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
14509 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
14510 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
14511 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
14512 case X86ISD::VZEXT: return "X86ISD::VZEXT";
14513 case X86ISD::VSEXT: return "X86ISD::VSEXT";
14514 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
14515 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
14516 case X86ISD::VINSERT: return "X86ISD::VINSERT";
14517 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
14518 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
14519 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
14520 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
14521 case X86ISD::VSHL: return "X86ISD::VSHL";
14522 case X86ISD::VSRL: return "X86ISD::VSRL";
14523 case X86ISD::VSRA: return "X86ISD::VSRA";
14524 case X86ISD::VSHLI: return "X86ISD::VSHLI";
14525 case X86ISD::VSRLI: return "X86ISD::VSRLI";
14526 case X86ISD::VSRAI: return "X86ISD::VSRAI";
14527 case X86ISD::CMPP: return "X86ISD::CMPP";
14528 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
14529 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
14530 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
14531 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
14532 case X86ISD::ADD: return "X86ISD::ADD";
14533 case X86ISD::SUB: return "X86ISD::SUB";
14534 case X86ISD::ADC: return "X86ISD::ADC";
14535 case X86ISD::SBB: return "X86ISD::SBB";
14536 case X86ISD::SMUL: return "X86ISD::SMUL";
14537 case X86ISD::UMUL: return "X86ISD::UMUL";
14538 case X86ISD::INC: return "X86ISD::INC";
14539 case X86ISD::DEC: return "X86ISD::DEC";
14540 case X86ISD::OR: return "X86ISD::OR";
14541 case X86ISD::XOR: return "X86ISD::XOR";
14542 case X86ISD::AND: return "X86ISD::AND";
14543 case X86ISD::BEXTR: return "X86ISD::BEXTR";
14544 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
14545 case X86ISD::PTEST: return "X86ISD::PTEST";
14546 case X86ISD::TESTP: return "X86ISD::TESTP";
14547 case X86ISD::TESTM: return "X86ISD::TESTM";
14548 case X86ISD::TESTNM: return "X86ISD::TESTNM";
14549 case X86ISD::KORTEST: return "X86ISD::KORTEST";
14550 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
14551 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
14552 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
14553 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
14554 case X86ISD::SHUFP: return "X86ISD::SHUFP";
14555 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
14556 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
14557 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
14558 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
14559 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
14560 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
14561 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
14562 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
14563 case X86ISD::MOVSD: return "X86ISD::MOVSD";
14564 case X86ISD::MOVSS: return "X86ISD::MOVSS";
14565 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
14566 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
14567 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
14568 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
14569 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
14570 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
14571 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
14572 case X86ISD::VPERMV: return "X86ISD::VPERMV";
14573 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
14574 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
14575 case X86ISD::VPERMI: return "X86ISD::VPERMI";
14576 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
14577 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
14578 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14579 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
14580 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
14581 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
14582 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
14583 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
14584 case X86ISD::SAHF: return "X86ISD::SAHF";
14585 case X86ISD::RDRAND: return "X86ISD::RDRAND";
14586 case X86ISD::RDSEED: return "X86ISD::RDSEED";
14587 case X86ISD::FMADD: return "X86ISD::FMADD";
14588 case X86ISD::FMSUB: return "X86ISD::FMSUB";
14589 case X86ISD::FNMADD: return "X86ISD::FNMADD";
14590 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
14591 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
14592 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
14593 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
14594 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
14595 case X86ISD::XTEST: return "X86ISD::XTEST";
14599 // isLegalAddressingMode - Return true if the addressing mode represented
14600 // by AM is legal for this target, for a load/store of the specified type.
14601 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14603 // X86 supports extremely general addressing modes.
14604 CodeModel::Model M = getTargetMachine().getCodeModel();
14605 Reloc::Model R = getTargetMachine().getRelocationModel();
14607 // X86 allows a sign-extended 32-bit immediate field as a displacement.
14608 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14613 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14615 // If a reference to this global requires an extra load, we can't fold it.
14616 if (isGlobalStubReference(GVFlags))
14619 // If BaseGV requires a register for the PIC base, we cannot also have a
14620 // BaseReg specified.
14621 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14624 // If lower 4G is not available, then we must use rip-relative addressing.
14625 if ((M != CodeModel::Small || R != Reloc::Static) &&
14626 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14630 switch (AM.Scale) {
14636 // These scales always work.
14641 // These scales are formed with basereg+scalereg. Only accept if there is
14646 default: // Other stuff never works.
14653 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14654 unsigned Bits = Ty->getScalarSizeInBits();
14656 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14657 // particularly cheaper than those without.
14661 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14662 // variable shifts just as cheap as scalar ones.
14663 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14666 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14667 // fully general vector.
14671 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14672 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14674 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14675 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14676 return NumBits1 > NumBits2;
14679 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14680 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14683 if (!isTypeLegal(EVT::getEVT(Ty1)))
14686 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14688 // Assuming the caller doesn't have a zeroext or signext return parameter,
14689 // truncation all the way down to i1 is valid.
14693 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14694 return isInt<32>(Imm);
14697 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14698 // Can also use sub to handle negated immediates.
14699 return isInt<32>(Imm);
14702 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14703 if (!VT1.isInteger() || !VT2.isInteger())
14705 unsigned NumBits1 = VT1.getSizeInBits();
14706 unsigned NumBits2 = VT2.getSizeInBits();
14707 return NumBits1 > NumBits2;
14710 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14711 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14712 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14715 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14716 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14717 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14720 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14721 EVT VT1 = Val.getValueType();
14722 if (isZExtFree(VT1, VT2))
14725 if (Val.getOpcode() != ISD::LOAD)
14728 if (!VT1.isSimple() || !VT1.isInteger() ||
14729 !VT2.isSimple() || !VT2.isInteger())
14732 switch (VT1.getSimpleVT().SimpleTy) {
14737 // X86 has 8, 16, and 32-bit zero-extending loads.
14745 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14746 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14749 VT = VT.getScalarType();
14751 if (!VT.isSimple())
14754 switch (VT.getSimpleVT().SimpleTy) {
14765 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14766 // i16 instructions are longer (0x66 prefix) and potentially slower.
14767 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14770 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14771 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14772 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14773 /// are assumed to be legal.
14775 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14777 if (!VT.isSimple())
14780 MVT SVT = VT.getSimpleVT();
14782 // Very little shuffling can be done for 64-bit vectors right now.
14783 if (VT.getSizeInBits() == 64)
14786 // FIXME: pshufb, blends, shifts.
14787 return (SVT.getVectorNumElements() == 2 ||
14788 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14789 isMOVLMask(M, SVT) ||
14790 isSHUFPMask(M, SVT) ||
14791 isPSHUFDMask(M, SVT) ||
14792 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14793 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14794 isPALIGNRMask(M, SVT, Subtarget) ||
14795 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14796 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14797 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14798 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14802 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14804 if (!VT.isSimple())
14807 MVT SVT = VT.getSimpleVT();
14808 unsigned NumElts = SVT.getVectorNumElements();
14809 // FIXME: This collection of masks seems suspect.
14812 if (NumElts == 4 && SVT.is128BitVector()) {
14813 return (isMOVLMask(Mask, SVT) ||
14814 isCommutedMOVLMask(Mask, SVT, true) ||
14815 isSHUFPMask(Mask, SVT) ||
14816 isSHUFPMask(Mask, SVT, /* Commuted */ true));
14821 //===----------------------------------------------------------------------===//
14822 // X86 Scheduler Hooks
14823 //===----------------------------------------------------------------------===//
14825 /// Utility function to emit xbegin specifying the start of an RTM region.
14826 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14827 const TargetInstrInfo *TII) {
14828 DebugLoc DL = MI->getDebugLoc();
14830 const BasicBlock *BB = MBB->getBasicBlock();
14831 MachineFunction::iterator I = MBB;
14834 // For the v = xbegin(), we generate
14845 MachineBasicBlock *thisMBB = MBB;
14846 MachineFunction *MF = MBB->getParent();
14847 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14848 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14849 MF->insert(I, mainMBB);
14850 MF->insert(I, sinkMBB);
14852 // Transfer the remainder of BB and its successor edges to sinkMBB.
14853 sinkMBB->splice(sinkMBB->begin(), MBB,
14854 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14855 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14859 // # fallthrough to mainMBB
14860 // # abortion to sinkMBB
14861 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14862 thisMBB->addSuccessor(mainMBB);
14863 thisMBB->addSuccessor(sinkMBB);
14867 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14868 mainMBB->addSuccessor(sinkMBB);
14871 // EAX is live into the sinkMBB
14872 sinkMBB->addLiveIn(X86::EAX);
14873 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14874 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14877 MI->eraseFromParent();
14881 // Get CMPXCHG opcode for the specified data type.
14882 static unsigned getCmpXChgOpcode(EVT VT) {
14883 switch (VT.getSimpleVT().SimpleTy) {
14884 case MVT::i8: return X86::LCMPXCHG8;
14885 case MVT::i16: return X86::LCMPXCHG16;
14886 case MVT::i32: return X86::LCMPXCHG32;
14887 case MVT::i64: return X86::LCMPXCHG64;
14891 llvm_unreachable("Invalid operand size!");
14894 // Get LOAD opcode for the specified data type.
14895 static unsigned getLoadOpcode(EVT VT) {
14896 switch (VT.getSimpleVT().SimpleTy) {
14897 case MVT::i8: return X86::MOV8rm;
14898 case MVT::i16: return X86::MOV16rm;
14899 case MVT::i32: return X86::MOV32rm;
14900 case MVT::i64: return X86::MOV64rm;
14904 llvm_unreachable("Invalid operand size!");
14907 // Get opcode of the non-atomic one from the specified atomic instruction.
14908 static unsigned getNonAtomicOpcode(unsigned Opc) {
14910 case X86::ATOMAND8: return X86::AND8rr;
14911 case X86::ATOMAND16: return X86::AND16rr;
14912 case X86::ATOMAND32: return X86::AND32rr;
14913 case X86::ATOMAND64: return X86::AND64rr;
14914 case X86::ATOMOR8: return X86::OR8rr;
14915 case X86::ATOMOR16: return X86::OR16rr;
14916 case X86::ATOMOR32: return X86::OR32rr;
14917 case X86::ATOMOR64: return X86::OR64rr;
14918 case X86::ATOMXOR8: return X86::XOR8rr;
14919 case X86::ATOMXOR16: return X86::XOR16rr;
14920 case X86::ATOMXOR32: return X86::XOR32rr;
14921 case X86::ATOMXOR64: return X86::XOR64rr;
14923 llvm_unreachable("Unhandled atomic-load-op opcode!");
14926 // Get opcode of the non-atomic one from the specified atomic instruction with
14928 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14929 unsigned &ExtraOpc) {
14931 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
14932 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
14933 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
14934 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
14935 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
14936 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14937 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14938 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14939 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
14940 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14941 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14942 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14943 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
14944 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14945 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14946 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14947 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
14948 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14949 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14950 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14952 llvm_unreachable("Unhandled atomic-load-op opcode!");
14955 // Get opcode of the non-atomic one from the specified atomic instruction for
14956 // 64-bit data type on 32-bit target.
14957 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14959 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
14960 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
14961 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
14962 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
14963 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
14964 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14965 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
14966 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
14967 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
14968 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
14970 llvm_unreachable("Unhandled atomic-load-op opcode!");
14973 // Get opcode of the non-atomic one from the specified atomic instruction for
14974 // 64-bit data type on 32-bit target with extra opcode.
14975 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14977 unsigned &ExtraOpc) {
14979 case X86::ATOMNAND6432:
14980 ExtraOpc = X86::NOT32r;
14981 HiOpc = X86::AND32rr;
14982 return X86::AND32rr;
14984 llvm_unreachable("Unhandled atomic-load-op opcode!");
14987 // Get pseudo CMOV opcode from the specified data type.
14988 static unsigned getPseudoCMOVOpc(EVT VT) {
14989 switch (VT.getSimpleVT().SimpleTy) {
14990 case MVT::i8: return X86::CMOV_GR8;
14991 case MVT::i16: return X86::CMOV_GR16;
14992 case MVT::i32: return X86::CMOV_GR32;
14996 llvm_unreachable("Unknown CMOV opcode!");
14999 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15000 // They will be translated into a spin-loop or compare-exchange loop from
15003 // dst = atomic-fetch-op MI.addr, MI.val
15009 // t1 = LOAD MI.addr
15011 // t4 = phi(t1, t3 / loop)
15012 // t2 = OP MI.val, t4
15014 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15020 MachineBasicBlock *
15021 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15022 MachineBasicBlock *MBB) const {
15023 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15024 DebugLoc DL = MI->getDebugLoc();
15026 MachineFunction *MF = MBB->getParent();
15027 MachineRegisterInfo &MRI = MF->getRegInfo();
15029 const BasicBlock *BB = MBB->getBasicBlock();
15030 MachineFunction::iterator I = MBB;
15033 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15034 "Unexpected number of operands");
15036 assert(MI->hasOneMemOperand() &&
15037 "Expected atomic-load-op to have one memoperand");
15039 // Memory Reference
15040 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15041 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15043 unsigned DstReg, SrcReg;
15044 unsigned MemOpndSlot;
15046 unsigned CurOp = 0;
15048 DstReg = MI->getOperand(CurOp++).getReg();
15049 MemOpndSlot = CurOp;
15050 CurOp += X86::AddrNumOperands;
15051 SrcReg = MI->getOperand(CurOp++).getReg();
15053 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15054 MVT::SimpleValueType VT = *RC->vt_begin();
15055 unsigned t1 = MRI.createVirtualRegister(RC);
15056 unsigned t2 = MRI.createVirtualRegister(RC);
15057 unsigned t3 = MRI.createVirtualRegister(RC);
15058 unsigned t4 = MRI.createVirtualRegister(RC);
15059 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15061 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15062 unsigned LOADOpc = getLoadOpcode(VT);
15064 // For the atomic load-arith operator, we generate
15067 // t1 = LOAD [MI.addr]
15069 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
15070 // t1 = OP MI.val, EAX
15072 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15078 MachineBasicBlock *thisMBB = MBB;
15079 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15080 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15081 MF->insert(I, mainMBB);
15082 MF->insert(I, sinkMBB);
15084 MachineInstrBuilder MIB;
15086 // Transfer the remainder of BB and its successor edges to sinkMBB.
15087 sinkMBB->splice(sinkMBB->begin(), MBB,
15088 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15089 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15092 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15093 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15094 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15096 NewMO.setIsKill(false);
15097 MIB.addOperand(NewMO);
15099 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15100 unsigned flags = (*MMOI)->getFlags();
15101 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15102 MachineMemOperand *MMO =
15103 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15104 (*MMOI)->getSize(),
15105 (*MMOI)->getBaseAlignment(),
15106 (*MMOI)->getTBAAInfo(),
15107 (*MMOI)->getRanges());
15108 MIB.addMemOperand(MMO);
15111 thisMBB->addSuccessor(mainMBB);
15114 MachineBasicBlock *origMainMBB = mainMBB;
15117 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15118 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15120 unsigned Opc = MI->getOpcode();
15123 llvm_unreachable("Unhandled atomic-load-op opcode!");
15124 case X86::ATOMAND8:
15125 case X86::ATOMAND16:
15126 case X86::ATOMAND32:
15127 case X86::ATOMAND64:
15129 case X86::ATOMOR16:
15130 case X86::ATOMOR32:
15131 case X86::ATOMOR64:
15132 case X86::ATOMXOR8:
15133 case X86::ATOMXOR16:
15134 case X86::ATOMXOR32:
15135 case X86::ATOMXOR64: {
15136 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15137 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15141 case X86::ATOMNAND8:
15142 case X86::ATOMNAND16:
15143 case X86::ATOMNAND32:
15144 case X86::ATOMNAND64: {
15145 unsigned Tmp = MRI.createVirtualRegister(RC);
15147 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15148 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15150 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15153 case X86::ATOMMAX8:
15154 case X86::ATOMMAX16:
15155 case X86::ATOMMAX32:
15156 case X86::ATOMMAX64:
15157 case X86::ATOMMIN8:
15158 case X86::ATOMMIN16:
15159 case X86::ATOMMIN32:
15160 case X86::ATOMMIN64:
15161 case X86::ATOMUMAX8:
15162 case X86::ATOMUMAX16:
15163 case X86::ATOMUMAX32:
15164 case X86::ATOMUMAX64:
15165 case X86::ATOMUMIN8:
15166 case X86::ATOMUMIN16:
15167 case X86::ATOMUMIN32:
15168 case X86::ATOMUMIN64: {
15170 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15172 BuildMI(mainMBB, DL, TII->get(CMPOpc))
15176 if (Subtarget->hasCMov()) {
15177 if (VT != MVT::i8) {
15179 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15183 // Promote i8 to i32 to use CMOV32
15184 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15185 const TargetRegisterClass *RC32 =
15186 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15187 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15188 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15189 unsigned Tmp = MRI.createVirtualRegister(RC32);
15191 unsigned Undef = MRI.createVirtualRegister(RC32);
15192 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15194 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15197 .addImm(X86::sub_8bit);
15198 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15201 .addImm(X86::sub_8bit);
15203 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15207 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15208 .addReg(Tmp, 0, X86::sub_8bit);
15211 // Use pseudo select and lower them.
15212 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15213 "Invalid atomic-load-op transformation!");
15214 unsigned SelOpc = getPseudoCMOVOpc(VT);
15215 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15216 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15217 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15218 .addReg(SrcReg).addReg(t4)
15220 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15221 // Replace the original PHI node as mainMBB is changed after CMOV
15223 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15224 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15225 Phi->eraseFromParent();
15231 // Copy PhyReg back from virtual register.
15232 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15235 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15236 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15237 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15239 NewMO.setIsKill(false);
15240 MIB.addOperand(NewMO);
15243 MIB.setMemRefs(MMOBegin, MMOEnd);
15245 // Copy PhyReg back to virtual register.
15246 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15249 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15251 mainMBB->addSuccessor(origMainMBB);
15252 mainMBB->addSuccessor(sinkMBB);
15255 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15256 TII->get(TargetOpcode::COPY), DstReg)
15259 MI->eraseFromParent();
15263 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15264 // instructions. They will be translated into a spin-loop or compare-exchange
15268 // dst = atomic-fetch-op MI.addr, MI.val
15274 // t1L = LOAD [MI.addr + 0]
15275 // t1H = LOAD [MI.addr + 4]
15277 // t4L = phi(t1L, t3L / loop)
15278 // t4H = phi(t1H, t3H / loop)
15279 // t2L = OP MI.val.lo, t4L
15280 // t2H = OP MI.val.hi, t4H
15285 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15293 MachineBasicBlock *
15294 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15295 MachineBasicBlock *MBB) const {
15296 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15297 DebugLoc DL = MI->getDebugLoc();
15299 MachineFunction *MF = MBB->getParent();
15300 MachineRegisterInfo &MRI = MF->getRegInfo();
15302 const BasicBlock *BB = MBB->getBasicBlock();
15303 MachineFunction::iterator I = MBB;
15306 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15307 "Unexpected number of operands");
15309 assert(MI->hasOneMemOperand() &&
15310 "Expected atomic-load-op32 to have one memoperand");
15312 // Memory Reference
15313 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15314 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15316 unsigned DstLoReg, DstHiReg;
15317 unsigned SrcLoReg, SrcHiReg;
15318 unsigned MemOpndSlot;
15320 unsigned CurOp = 0;
15322 DstLoReg = MI->getOperand(CurOp++).getReg();
15323 DstHiReg = MI->getOperand(CurOp++).getReg();
15324 MemOpndSlot = CurOp;
15325 CurOp += X86::AddrNumOperands;
15326 SrcLoReg = MI->getOperand(CurOp++).getReg();
15327 SrcHiReg = MI->getOperand(CurOp++).getReg();
15329 const TargetRegisterClass *RC = &X86::GR32RegClass;
15330 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15332 unsigned t1L = MRI.createVirtualRegister(RC);
15333 unsigned t1H = MRI.createVirtualRegister(RC);
15334 unsigned t2L = MRI.createVirtualRegister(RC);
15335 unsigned t2H = MRI.createVirtualRegister(RC);
15336 unsigned t3L = MRI.createVirtualRegister(RC);
15337 unsigned t3H = MRI.createVirtualRegister(RC);
15338 unsigned t4L = MRI.createVirtualRegister(RC);
15339 unsigned t4H = MRI.createVirtualRegister(RC);
15341 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15342 unsigned LOADOpc = X86::MOV32rm;
15344 // For the atomic load-arith operator, we generate
15347 // t1L = LOAD [MI.addr + 0]
15348 // t1H = LOAD [MI.addr + 4]
15350 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
15351 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
15352 // t2L = OP MI.val.lo, t4L
15353 // t2H = OP MI.val.hi, t4H
15356 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15364 MachineBasicBlock *thisMBB = MBB;
15365 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15366 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15367 MF->insert(I, mainMBB);
15368 MF->insert(I, sinkMBB);
15370 MachineInstrBuilder MIB;
15372 // Transfer the remainder of BB and its successor edges to sinkMBB.
15373 sinkMBB->splice(sinkMBB->begin(), MBB,
15374 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15375 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15379 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15380 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15381 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15383 NewMO.setIsKill(false);
15384 MIB.addOperand(NewMO);
15386 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15387 unsigned flags = (*MMOI)->getFlags();
15388 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15389 MachineMemOperand *MMO =
15390 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15391 (*MMOI)->getSize(),
15392 (*MMOI)->getBaseAlignment(),
15393 (*MMOI)->getTBAAInfo(),
15394 (*MMOI)->getRanges());
15395 MIB.addMemOperand(MMO);
15397 MachineInstr *LowMI = MIB;
15400 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15401 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15402 if (i == X86::AddrDisp) {
15403 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15405 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15407 NewMO.setIsKill(false);
15408 MIB.addOperand(NewMO);
15411 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15413 thisMBB->addSuccessor(mainMBB);
15416 MachineBasicBlock *origMainMBB = mainMBB;
15419 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15420 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15421 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15422 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15424 unsigned Opc = MI->getOpcode();
15427 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15428 case X86::ATOMAND6432:
15429 case X86::ATOMOR6432:
15430 case X86::ATOMXOR6432:
15431 case X86::ATOMADD6432:
15432 case X86::ATOMSUB6432: {
15434 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15435 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15437 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15441 case X86::ATOMNAND6432: {
15442 unsigned HiOpc, NOTOpc;
15443 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15444 unsigned TmpL = MRI.createVirtualRegister(RC);
15445 unsigned TmpH = MRI.createVirtualRegister(RC);
15446 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15448 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15450 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15451 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15454 case X86::ATOMMAX6432:
15455 case X86::ATOMMIN6432:
15456 case X86::ATOMUMAX6432:
15457 case X86::ATOMUMIN6432: {
15459 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15460 unsigned cL = MRI.createVirtualRegister(RC8);
15461 unsigned cH = MRI.createVirtualRegister(RC8);
15462 unsigned cL32 = MRI.createVirtualRegister(RC);
15463 unsigned cH32 = MRI.createVirtualRegister(RC);
15464 unsigned cc = MRI.createVirtualRegister(RC);
15465 // cl := cmp src_lo, lo
15466 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15467 .addReg(SrcLoReg).addReg(t4L);
15468 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15469 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15470 // ch := cmp src_hi, hi
15471 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15472 .addReg(SrcHiReg).addReg(t4H);
15473 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15474 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15475 // cc := if (src_hi == hi) ? cl : ch;
15476 if (Subtarget->hasCMov()) {
15477 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15478 .addReg(cH32).addReg(cL32);
15480 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15481 .addReg(cH32).addReg(cL32)
15482 .addImm(X86::COND_E);
15483 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15485 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15486 if (Subtarget->hasCMov()) {
15487 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15488 .addReg(SrcLoReg).addReg(t4L);
15489 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15490 .addReg(SrcHiReg).addReg(t4H);
15492 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15493 .addReg(SrcLoReg).addReg(t4L)
15494 .addImm(X86::COND_NE);
15495 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15496 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15497 // 2nd CMOV lowering.
15498 mainMBB->addLiveIn(X86::EFLAGS);
15499 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15500 .addReg(SrcHiReg).addReg(t4H)
15501 .addImm(X86::COND_NE);
15502 mainMBB = EmitLoweredSelect(MIB, mainMBB);
15503 // Replace the original PHI node as mainMBB is changed after CMOV
15505 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15506 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15507 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15508 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15509 PhiL->eraseFromParent();
15510 PhiH->eraseFromParent();
15514 case X86::ATOMSWAP6432: {
15516 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15517 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15518 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15523 // Copy EDX:EAX back from HiReg:LoReg
15524 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15525 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15526 // Copy ECX:EBX from t1H:t1L
15527 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15528 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15530 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15531 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15532 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15534 NewMO.setIsKill(false);
15535 MIB.addOperand(NewMO);
15537 MIB.setMemRefs(MMOBegin, MMOEnd);
15539 // Copy EDX:EAX back to t3H:t3L
15540 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15541 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15543 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15545 mainMBB->addSuccessor(origMainMBB);
15546 mainMBB->addSuccessor(sinkMBB);
15549 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15550 TII->get(TargetOpcode::COPY), DstLoReg)
15552 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15553 TII->get(TargetOpcode::COPY), DstHiReg)
15556 MI->eraseFromParent();
15560 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15561 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15562 // in the .td file.
15563 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15564 const TargetInstrInfo *TII) {
15566 switch (MI->getOpcode()) {
15567 default: llvm_unreachable("illegal opcode!");
15568 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
15569 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15570 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
15571 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15572 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
15573 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15574 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
15575 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15578 DebugLoc dl = MI->getDebugLoc();
15579 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15581 unsigned NumArgs = MI->getNumOperands();
15582 for (unsigned i = 1; i < NumArgs; ++i) {
15583 MachineOperand &Op = MI->getOperand(i);
15584 if (!(Op.isReg() && Op.isImplicit()))
15585 MIB.addOperand(Op);
15587 if (MI->hasOneMemOperand())
15588 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15590 BuildMI(*BB, MI, dl,
15591 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15592 .addReg(X86::XMM0);
15594 MI->eraseFromParent();
15598 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15599 // defs in an instruction pattern
15600 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15601 const TargetInstrInfo *TII) {
15603 switch (MI->getOpcode()) {
15604 default: llvm_unreachable("illegal opcode!");
15605 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
15606 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15607 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
15608 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15609 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
15610 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15611 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
15612 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15615 DebugLoc dl = MI->getDebugLoc();
15616 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15618 unsigned NumArgs = MI->getNumOperands(); // remove the results
15619 for (unsigned i = 1; i < NumArgs; ++i) {
15620 MachineOperand &Op = MI->getOperand(i);
15621 if (!(Op.isReg() && Op.isImplicit()))
15622 MIB.addOperand(Op);
15624 if (MI->hasOneMemOperand())
15625 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15627 BuildMI(*BB, MI, dl,
15628 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15631 MI->eraseFromParent();
15635 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15636 const TargetInstrInfo *TII,
15637 const X86Subtarget* Subtarget) {
15638 DebugLoc dl = MI->getDebugLoc();
15640 // Address into RAX/EAX, other two args into ECX, EDX.
15641 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15642 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15643 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15644 for (int i = 0; i < X86::AddrNumOperands; ++i)
15645 MIB.addOperand(MI->getOperand(i));
15647 unsigned ValOps = X86::AddrNumOperands;
15648 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15649 .addReg(MI->getOperand(ValOps).getReg());
15650 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15651 .addReg(MI->getOperand(ValOps+1).getReg());
15653 // The instruction doesn't actually take any operands though.
15654 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15656 MI->eraseFromParent(); // The pseudo is gone now.
15660 MachineBasicBlock *
15661 X86TargetLowering::EmitVAARG64WithCustomInserter(
15663 MachineBasicBlock *MBB) const {
15664 // Emit va_arg instruction on X86-64.
15666 // Operands to this pseudo-instruction:
15667 // 0 ) Output : destination address (reg)
15668 // 1-5) Input : va_list address (addr, i64mem)
15669 // 6 ) ArgSize : Size (in bytes) of vararg type
15670 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15671 // 8 ) Align : Alignment of type
15672 // 9 ) EFLAGS (implicit-def)
15674 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15675 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15677 unsigned DestReg = MI->getOperand(0).getReg();
15678 MachineOperand &Base = MI->getOperand(1);
15679 MachineOperand &Scale = MI->getOperand(2);
15680 MachineOperand &Index = MI->getOperand(3);
15681 MachineOperand &Disp = MI->getOperand(4);
15682 MachineOperand &Segment = MI->getOperand(5);
15683 unsigned ArgSize = MI->getOperand(6).getImm();
15684 unsigned ArgMode = MI->getOperand(7).getImm();
15685 unsigned Align = MI->getOperand(8).getImm();
15687 // Memory Reference
15688 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15689 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15690 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15692 // Machine Information
15693 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15694 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15695 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15696 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15697 DebugLoc DL = MI->getDebugLoc();
15699 // struct va_list {
15702 // i64 overflow_area (address)
15703 // i64 reg_save_area (address)
15705 // sizeof(va_list) = 24
15706 // alignment(va_list) = 8
15708 unsigned TotalNumIntRegs = 6;
15709 unsigned TotalNumXMMRegs = 8;
15710 bool UseGPOffset = (ArgMode == 1);
15711 bool UseFPOffset = (ArgMode == 2);
15712 unsigned MaxOffset = TotalNumIntRegs * 8 +
15713 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15715 /* Align ArgSize to a multiple of 8 */
15716 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15717 bool NeedsAlign = (Align > 8);
15719 MachineBasicBlock *thisMBB = MBB;
15720 MachineBasicBlock *overflowMBB;
15721 MachineBasicBlock *offsetMBB;
15722 MachineBasicBlock *endMBB;
15724 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
15725 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
15726 unsigned OffsetReg = 0;
15728 if (!UseGPOffset && !UseFPOffset) {
15729 // If we only pull from the overflow region, we don't create a branch.
15730 // We don't need to alter control flow.
15731 OffsetDestReg = 0; // unused
15732 OverflowDestReg = DestReg;
15734 offsetMBB = nullptr;
15735 overflowMBB = thisMBB;
15738 // First emit code to check if gp_offset (or fp_offset) is below the bound.
15739 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15740 // If not, pull from overflow_area. (branch to overflowMBB)
15745 // offsetMBB overflowMBB
15750 // Registers for the PHI in endMBB
15751 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15752 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15754 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15755 MachineFunction *MF = MBB->getParent();
15756 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15757 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15758 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15760 MachineFunction::iterator MBBIter = MBB;
15763 // Insert the new basic blocks
15764 MF->insert(MBBIter, offsetMBB);
15765 MF->insert(MBBIter, overflowMBB);
15766 MF->insert(MBBIter, endMBB);
15768 // Transfer the remainder of MBB and its successor edges to endMBB.
15769 endMBB->splice(endMBB->begin(), thisMBB,
15770 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15771 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15773 // Make offsetMBB and overflowMBB successors of thisMBB
15774 thisMBB->addSuccessor(offsetMBB);
15775 thisMBB->addSuccessor(overflowMBB);
15777 // endMBB is a successor of both offsetMBB and overflowMBB
15778 offsetMBB->addSuccessor(endMBB);
15779 overflowMBB->addSuccessor(endMBB);
15781 // Load the offset value into a register
15782 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15783 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15787 .addDisp(Disp, UseFPOffset ? 4 : 0)
15788 .addOperand(Segment)
15789 .setMemRefs(MMOBegin, MMOEnd);
15791 // Check if there is enough room left to pull this argument.
15792 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15794 .addImm(MaxOffset + 8 - ArgSizeA8);
15796 // Branch to "overflowMBB" if offset >= max
15797 // Fall through to "offsetMBB" otherwise
15798 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15799 .addMBB(overflowMBB);
15802 // In offsetMBB, emit code to use the reg_save_area.
15804 assert(OffsetReg != 0);
15806 // Read the reg_save_area address.
15807 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15808 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15813 .addOperand(Segment)
15814 .setMemRefs(MMOBegin, MMOEnd);
15816 // Zero-extend the offset
15817 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15818 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15821 .addImm(X86::sub_32bit);
15823 // Add the offset to the reg_save_area to get the final address.
15824 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15825 .addReg(OffsetReg64)
15826 .addReg(RegSaveReg);
15828 // Compute the offset for the next argument
15829 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15830 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15832 .addImm(UseFPOffset ? 16 : 8);
15834 // Store it back into the va_list.
15835 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15839 .addDisp(Disp, UseFPOffset ? 4 : 0)
15840 .addOperand(Segment)
15841 .addReg(NextOffsetReg)
15842 .setMemRefs(MMOBegin, MMOEnd);
15845 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15850 // Emit code to use overflow area
15853 // Load the overflow_area address into a register.
15854 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15855 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15860 .addOperand(Segment)
15861 .setMemRefs(MMOBegin, MMOEnd);
15863 // If we need to align it, do so. Otherwise, just copy the address
15864 // to OverflowDestReg.
15866 // Align the overflow address
15867 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15868 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15870 // aligned_addr = (addr + (align-1)) & ~(align-1)
15871 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15872 .addReg(OverflowAddrReg)
15875 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15877 .addImm(~(uint64_t)(Align-1));
15879 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15880 .addReg(OverflowAddrReg);
15883 // Compute the next overflow address after this argument.
15884 // (the overflow address should be kept 8-byte aligned)
15885 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15886 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15887 .addReg(OverflowDestReg)
15888 .addImm(ArgSizeA8);
15890 // Store the new overflow address.
15891 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15896 .addOperand(Segment)
15897 .addReg(NextAddrReg)
15898 .setMemRefs(MMOBegin, MMOEnd);
15900 // If we branched, emit the PHI to the front of endMBB.
15902 BuildMI(*endMBB, endMBB->begin(), DL,
15903 TII->get(X86::PHI), DestReg)
15904 .addReg(OffsetDestReg).addMBB(offsetMBB)
15905 .addReg(OverflowDestReg).addMBB(overflowMBB);
15908 // Erase the pseudo instruction
15909 MI->eraseFromParent();
15914 MachineBasicBlock *
15915 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15917 MachineBasicBlock *MBB) const {
15918 // Emit code to save XMM registers to the stack. The ABI says that the
15919 // number of registers to save is given in %al, so it's theoretically
15920 // possible to do an indirect jump trick to avoid saving all of them,
15921 // however this code takes a simpler approach and just executes all
15922 // of the stores if %al is non-zero. It's less code, and it's probably
15923 // easier on the hardware branch predictor, and stores aren't all that
15924 // expensive anyway.
15926 // Create the new basic blocks. One block contains all the XMM stores,
15927 // and one block is the final destination regardless of whether any
15928 // stores were performed.
15929 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15930 MachineFunction *F = MBB->getParent();
15931 MachineFunction::iterator MBBIter = MBB;
15933 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15934 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15935 F->insert(MBBIter, XMMSaveMBB);
15936 F->insert(MBBIter, EndMBB);
15938 // Transfer the remainder of MBB and its successor edges to EndMBB.
15939 EndMBB->splice(EndMBB->begin(), MBB,
15940 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15941 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15943 // The original block will now fall through to the XMM save block.
15944 MBB->addSuccessor(XMMSaveMBB);
15945 // The XMMSaveMBB will fall through to the end block.
15946 XMMSaveMBB->addSuccessor(EndMBB);
15948 // Now add the instructions.
15949 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15950 DebugLoc DL = MI->getDebugLoc();
15952 unsigned CountReg = MI->getOperand(0).getReg();
15953 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15954 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15956 if (!Subtarget->isTargetWin64()) {
15957 // If %al is 0, branch around the XMM save block.
15958 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15959 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15960 MBB->addSuccessor(EndMBB);
15963 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15964 // that was just emitted, but clearly shouldn't be "saved".
15965 assert((MI->getNumOperands() <= 3 ||
15966 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15967 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15968 && "Expected last argument to be EFLAGS");
15969 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15970 // In the XMM save block, save all the XMM argument registers.
15971 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15972 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15973 MachineMemOperand *MMO =
15974 F->getMachineMemOperand(
15975 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15976 MachineMemOperand::MOStore,
15977 /*Size=*/16, /*Align=*/16);
15978 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15979 .addFrameIndex(RegSaveFrameIndex)
15980 .addImm(/*Scale=*/1)
15981 .addReg(/*IndexReg=*/0)
15982 .addImm(/*Disp=*/Offset)
15983 .addReg(/*Segment=*/0)
15984 .addReg(MI->getOperand(i).getReg())
15985 .addMemOperand(MMO);
15988 MI->eraseFromParent(); // The pseudo instruction is gone now.
15993 // The EFLAGS operand of SelectItr might be missing a kill marker
15994 // because there were multiple uses of EFLAGS, and ISel didn't know
15995 // which to mark. Figure out whether SelectItr should have had a
15996 // kill marker, and set it if it should. Returns the correct kill
15998 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15999 MachineBasicBlock* BB,
16000 const TargetRegisterInfo* TRI) {
16001 // Scan forward through BB for a use/def of EFLAGS.
16002 MachineBasicBlock::iterator miI(std::next(SelectItr));
16003 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16004 const MachineInstr& mi = *miI;
16005 if (mi.readsRegister(X86::EFLAGS))
16007 if (mi.definesRegister(X86::EFLAGS))
16008 break; // Should have kill-flag - update below.
16011 // If we hit the end of the block, check whether EFLAGS is live into a
16013 if (miI == BB->end()) {
16014 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16015 sEnd = BB->succ_end();
16016 sItr != sEnd; ++sItr) {
16017 MachineBasicBlock* succ = *sItr;
16018 if (succ->isLiveIn(X86::EFLAGS))
16023 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16024 // out. SelectMI should have a kill flag on EFLAGS.
16025 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16029 MachineBasicBlock *
16030 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16031 MachineBasicBlock *BB) const {
16032 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16033 DebugLoc DL = MI->getDebugLoc();
16035 // To "insert" a SELECT_CC instruction, we actually have to insert the
16036 // diamond control-flow pattern. The incoming instruction knows the
16037 // destination vreg to set, the condition code register to branch on, the
16038 // true/false values to select between, and a branch opcode to use.
16039 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16040 MachineFunction::iterator It = BB;
16046 // cmpTY ccX, r1, r2
16048 // fallthrough --> copy0MBB
16049 MachineBasicBlock *thisMBB = BB;
16050 MachineFunction *F = BB->getParent();
16051 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16052 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16053 F->insert(It, copy0MBB);
16054 F->insert(It, sinkMBB);
16056 // If the EFLAGS register isn't dead in the terminator, then claim that it's
16057 // live into the sink and copy blocks.
16058 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16059 if (!MI->killsRegister(X86::EFLAGS) &&
16060 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16061 copy0MBB->addLiveIn(X86::EFLAGS);
16062 sinkMBB->addLiveIn(X86::EFLAGS);
16065 // Transfer the remainder of BB and its successor edges to sinkMBB.
16066 sinkMBB->splice(sinkMBB->begin(), BB,
16067 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16068 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16070 // Add the true and fallthrough blocks as its successors.
16071 BB->addSuccessor(copy0MBB);
16072 BB->addSuccessor(sinkMBB);
16074 // Create the conditional branch instruction.
16076 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16077 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16080 // %FalseValue = ...
16081 // # fallthrough to sinkMBB
16082 copy0MBB->addSuccessor(sinkMBB);
16085 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16087 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16088 TII->get(X86::PHI), MI->getOperand(0).getReg())
16089 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16090 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16092 MI->eraseFromParent(); // The pseudo instruction is gone now.
16096 MachineBasicBlock *
16097 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16098 bool Is64Bit) const {
16099 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16100 DebugLoc DL = MI->getDebugLoc();
16101 MachineFunction *MF = BB->getParent();
16102 const BasicBlock *LLVM_BB = BB->getBasicBlock();
16104 assert(MF->shouldSplitStack());
16106 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16107 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16110 // ... [Till the alloca]
16111 // If stacklet is not large enough, jump to mallocMBB
16114 // Allocate by subtracting from RSP
16115 // Jump to continueMBB
16118 // Allocate by call to runtime
16122 // [rest of original BB]
16125 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16126 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16127 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16129 MachineRegisterInfo &MRI = MF->getRegInfo();
16130 const TargetRegisterClass *AddrRegClass =
16131 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16133 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16134 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16135 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16136 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16137 sizeVReg = MI->getOperand(1).getReg(),
16138 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16140 MachineFunction::iterator MBBIter = BB;
16143 MF->insert(MBBIter, bumpMBB);
16144 MF->insert(MBBIter, mallocMBB);
16145 MF->insert(MBBIter, continueMBB);
16147 continueMBB->splice(continueMBB->begin(), BB,
16148 std::next(MachineBasicBlock::iterator(MI)), BB->end());
16149 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16151 // Add code to the main basic block to check if the stack limit has been hit,
16152 // and if so, jump to mallocMBB otherwise to bumpMBB.
16153 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16154 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16155 .addReg(tmpSPVReg).addReg(sizeVReg);
16156 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16157 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16158 .addReg(SPLimitVReg);
16159 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16161 // bumpMBB simply decreases the stack pointer, since we know the current
16162 // stacklet has enough space.
16163 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16164 .addReg(SPLimitVReg);
16165 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16166 .addReg(SPLimitVReg);
16167 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16169 // Calls into a routine in libgcc to allocate more space from the heap.
16170 const uint32_t *RegMask =
16171 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16173 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16175 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16176 .addExternalSymbol("__morestack_allocate_stack_space")
16177 .addRegMask(RegMask)
16178 .addReg(X86::RDI, RegState::Implicit)
16179 .addReg(X86::RAX, RegState::ImplicitDefine);
16181 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16183 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16184 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16185 .addExternalSymbol("__morestack_allocate_stack_space")
16186 .addRegMask(RegMask)
16187 .addReg(X86::EAX, RegState::ImplicitDefine);
16191 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16194 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16195 .addReg(Is64Bit ? X86::RAX : X86::EAX);
16196 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16198 // Set up the CFG correctly.
16199 BB->addSuccessor(bumpMBB);
16200 BB->addSuccessor(mallocMBB);
16201 mallocMBB->addSuccessor(continueMBB);
16202 bumpMBB->addSuccessor(continueMBB);
16204 // Take care of the PHI nodes.
16205 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16206 MI->getOperand(0).getReg())
16207 .addReg(mallocPtrVReg).addMBB(mallocMBB)
16208 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16210 // Delete the original pseudo instruction.
16211 MI->eraseFromParent();
16214 return continueMBB;
16217 MachineBasicBlock *
16218 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16219 MachineBasicBlock *BB) const {
16220 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16221 DebugLoc DL = MI->getDebugLoc();
16223 assert(!Subtarget->isTargetMacho());
16225 // The lowering is pretty easy: we're just emitting the call to _alloca. The
16226 // non-trivial part is impdef of ESP.
16228 if (Subtarget->isTargetWin64()) {
16229 if (Subtarget->isTargetCygMing()) {
16230 // ___chkstk(Mingw64):
16231 // Clobbers R10, R11, RAX and EFLAGS.
16233 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16234 .addExternalSymbol("___chkstk")
16235 .addReg(X86::RAX, RegState::Implicit)
16236 .addReg(X86::RSP, RegState::Implicit)
16237 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16238 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16239 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16241 // __chkstk(MSVCRT): does not update stack pointer.
16242 // Clobbers R10, R11 and EFLAGS.
16243 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16244 .addExternalSymbol("__chkstk")
16245 .addReg(X86::RAX, RegState::Implicit)
16246 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16247 // RAX has the offset to be subtracted from RSP.
16248 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16253 const char *StackProbeSymbol =
16254 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16256 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16257 .addExternalSymbol(StackProbeSymbol)
16258 .addReg(X86::EAX, RegState::Implicit)
16259 .addReg(X86::ESP, RegState::Implicit)
16260 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16261 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16262 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16265 MI->eraseFromParent(); // The pseudo instruction is gone now.
16269 MachineBasicBlock *
16270 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16271 MachineBasicBlock *BB) const {
16272 // This is pretty easy. We're taking the value that we received from
16273 // our load from the relocation, sticking it in either RDI (x86-64)
16274 // or EAX and doing an indirect call. The return value will then
16275 // be in the normal return register.
16276 const X86InstrInfo *TII
16277 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16278 DebugLoc DL = MI->getDebugLoc();
16279 MachineFunction *F = BB->getParent();
16281 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16282 assert(MI->getOperand(3).isGlobal() && "This should be a global");
16284 // Get a register mask for the lowered call.
16285 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16286 // proper register mask.
16287 const uint32_t *RegMask =
16288 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16289 if (Subtarget->is64Bit()) {
16290 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16291 TII->get(X86::MOV64rm), X86::RDI)
16293 .addImm(0).addReg(0)
16294 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16295 MI->getOperand(3).getTargetFlags())
16297 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16298 addDirectMem(MIB, X86::RDI);
16299 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16300 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16301 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16302 TII->get(X86::MOV32rm), X86::EAX)
16304 .addImm(0).addReg(0)
16305 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16306 MI->getOperand(3).getTargetFlags())
16308 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16309 addDirectMem(MIB, X86::EAX);
16310 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16312 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16313 TII->get(X86::MOV32rm), X86::EAX)
16314 .addReg(TII->getGlobalBaseReg(F))
16315 .addImm(0).addReg(0)
16316 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16317 MI->getOperand(3).getTargetFlags())
16319 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16320 addDirectMem(MIB, X86::EAX);
16321 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16324 MI->eraseFromParent(); // The pseudo instruction is gone now.
16328 MachineBasicBlock *
16329 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16330 MachineBasicBlock *MBB) const {
16331 DebugLoc DL = MI->getDebugLoc();
16332 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16334 MachineFunction *MF = MBB->getParent();
16335 MachineRegisterInfo &MRI = MF->getRegInfo();
16337 const BasicBlock *BB = MBB->getBasicBlock();
16338 MachineFunction::iterator I = MBB;
16341 // Memory Reference
16342 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16343 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16346 unsigned MemOpndSlot = 0;
16348 unsigned CurOp = 0;
16350 DstReg = MI->getOperand(CurOp++).getReg();
16351 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16352 assert(RC->hasType(MVT::i32) && "Invalid destination!");
16353 unsigned mainDstReg = MRI.createVirtualRegister(RC);
16354 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16356 MemOpndSlot = CurOp;
16358 MVT PVT = getPointerTy();
16359 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16360 "Invalid Pointer Size!");
16362 // For v = setjmp(buf), we generate
16365 // buf[LabelOffset] = restoreMBB
16366 // SjLjSetup restoreMBB
16372 // v = phi(main, restore)
16377 MachineBasicBlock *thisMBB = MBB;
16378 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16379 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16380 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16381 MF->insert(I, mainMBB);
16382 MF->insert(I, sinkMBB);
16383 MF->push_back(restoreMBB);
16385 MachineInstrBuilder MIB;
16387 // Transfer the remainder of BB and its successor edges to sinkMBB.
16388 sinkMBB->splice(sinkMBB->begin(), MBB,
16389 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16390 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16393 unsigned PtrStoreOpc = 0;
16394 unsigned LabelReg = 0;
16395 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16396 Reloc::Model RM = getTargetMachine().getRelocationModel();
16397 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16398 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16400 // Prepare IP either in reg or imm.
16401 if (!UseImmLabel) {
16402 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16403 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16404 LabelReg = MRI.createVirtualRegister(PtrRC);
16405 if (Subtarget->is64Bit()) {
16406 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16410 .addMBB(restoreMBB)
16413 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16414 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16415 .addReg(XII->getGlobalBaseReg(MF))
16418 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16422 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16424 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16425 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16426 if (i == X86::AddrDisp)
16427 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16429 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16432 MIB.addReg(LabelReg);
16434 MIB.addMBB(restoreMBB);
16435 MIB.setMemRefs(MMOBegin, MMOEnd);
16437 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16438 .addMBB(restoreMBB);
16440 const X86RegisterInfo *RegInfo =
16441 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16442 MIB.addRegMask(RegInfo->getNoPreservedMask());
16443 thisMBB->addSuccessor(mainMBB);
16444 thisMBB->addSuccessor(restoreMBB);
16448 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16449 mainMBB->addSuccessor(sinkMBB);
16452 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16453 TII->get(X86::PHI), DstReg)
16454 .addReg(mainDstReg).addMBB(mainMBB)
16455 .addReg(restoreDstReg).addMBB(restoreMBB);
16458 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16459 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16460 restoreMBB->addSuccessor(sinkMBB);
16462 MI->eraseFromParent();
16466 MachineBasicBlock *
16467 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16468 MachineBasicBlock *MBB) const {
16469 DebugLoc DL = MI->getDebugLoc();
16470 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16472 MachineFunction *MF = MBB->getParent();
16473 MachineRegisterInfo &MRI = MF->getRegInfo();
16475 // Memory Reference
16476 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16477 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16479 MVT PVT = getPointerTy();
16480 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16481 "Invalid Pointer Size!");
16483 const TargetRegisterClass *RC =
16484 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16485 unsigned Tmp = MRI.createVirtualRegister(RC);
16486 // Since FP is only updated here but NOT referenced, it's treated as GPR.
16487 const X86RegisterInfo *RegInfo =
16488 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16489 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16490 unsigned SP = RegInfo->getStackRegister();
16492 MachineInstrBuilder MIB;
16494 const int64_t LabelOffset = 1 * PVT.getStoreSize();
16495 const int64_t SPOffset = 2 * PVT.getStoreSize();
16497 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16498 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16501 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16502 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16503 MIB.addOperand(MI->getOperand(i));
16504 MIB.setMemRefs(MMOBegin, MMOEnd);
16506 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16507 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16508 if (i == X86::AddrDisp)
16509 MIB.addDisp(MI->getOperand(i), LabelOffset);
16511 MIB.addOperand(MI->getOperand(i));
16513 MIB.setMemRefs(MMOBegin, MMOEnd);
16515 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16516 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16517 if (i == X86::AddrDisp)
16518 MIB.addDisp(MI->getOperand(i), SPOffset);
16520 MIB.addOperand(MI->getOperand(i));
16522 MIB.setMemRefs(MMOBegin, MMOEnd);
16524 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16526 MI->eraseFromParent();
16530 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16531 // accumulator loops. Writing back to the accumulator allows the coalescer
16532 // to remove extra copies in the loop.
16533 MachineBasicBlock *
16534 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16535 MachineBasicBlock *MBB) const {
16536 MachineOperand &AddendOp = MI->getOperand(3);
16538 // Bail out early if the addend isn't a register - we can't switch these.
16539 if (!AddendOp.isReg())
16542 MachineFunction &MF = *MBB->getParent();
16543 MachineRegisterInfo &MRI = MF.getRegInfo();
16545 // Check whether the addend is defined by a PHI:
16546 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16547 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16548 if (!AddendDef.isPHI())
16551 // Look for the following pattern:
16553 // %addend = phi [%entry, 0], [%loop, %result]
16555 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16559 // %addend = phi [%entry, 0], [%loop, %result]
16561 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16563 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16564 assert(AddendDef.getOperand(i).isReg());
16565 MachineOperand PHISrcOp = AddendDef.getOperand(i);
16566 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16567 if (&PHISrcInst == MI) {
16568 // Found a matching instruction.
16569 unsigned NewFMAOpc = 0;
16570 switch (MI->getOpcode()) {
16571 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16572 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16573 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16574 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16575 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16576 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16577 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16578 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16579 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16580 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16581 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16582 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16583 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16584 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16585 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16586 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16587 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16588 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16589 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16590 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16591 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16592 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16593 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16594 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16595 default: llvm_unreachable("Unrecognized FMA variant.");
16598 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16599 MachineInstrBuilder MIB =
16600 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16601 .addOperand(MI->getOperand(0))
16602 .addOperand(MI->getOperand(3))
16603 .addOperand(MI->getOperand(2))
16604 .addOperand(MI->getOperand(1));
16605 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16606 MI->eraseFromParent();
16613 MachineBasicBlock *
16614 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16615 MachineBasicBlock *BB) const {
16616 switch (MI->getOpcode()) {
16617 default: llvm_unreachable("Unexpected instr type to insert");
16618 case X86::TAILJMPd64:
16619 case X86::TAILJMPr64:
16620 case X86::TAILJMPm64:
16621 llvm_unreachable("TAILJMP64 would not be touched here.");
16622 case X86::TCRETURNdi64:
16623 case X86::TCRETURNri64:
16624 case X86::TCRETURNmi64:
16626 case X86::WIN_ALLOCA:
16627 return EmitLoweredWinAlloca(MI, BB);
16628 case X86::SEG_ALLOCA_32:
16629 return EmitLoweredSegAlloca(MI, BB, false);
16630 case X86::SEG_ALLOCA_64:
16631 return EmitLoweredSegAlloca(MI, BB, true);
16632 case X86::TLSCall_32:
16633 case X86::TLSCall_64:
16634 return EmitLoweredTLSCall(MI, BB);
16635 case X86::CMOV_GR8:
16636 case X86::CMOV_FR32:
16637 case X86::CMOV_FR64:
16638 case X86::CMOV_V4F32:
16639 case X86::CMOV_V2F64:
16640 case X86::CMOV_V2I64:
16641 case X86::CMOV_V8F32:
16642 case X86::CMOV_V4F64:
16643 case X86::CMOV_V4I64:
16644 case X86::CMOV_V16F32:
16645 case X86::CMOV_V8F64:
16646 case X86::CMOV_V8I64:
16647 case X86::CMOV_GR16:
16648 case X86::CMOV_GR32:
16649 case X86::CMOV_RFP32:
16650 case X86::CMOV_RFP64:
16651 case X86::CMOV_RFP80:
16652 return EmitLoweredSelect(MI, BB);
16654 case X86::FP32_TO_INT16_IN_MEM:
16655 case X86::FP32_TO_INT32_IN_MEM:
16656 case X86::FP32_TO_INT64_IN_MEM:
16657 case X86::FP64_TO_INT16_IN_MEM:
16658 case X86::FP64_TO_INT32_IN_MEM:
16659 case X86::FP64_TO_INT64_IN_MEM:
16660 case X86::FP80_TO_INT16_IN_MEM:
16661 case X86::FP80_TO_INT32_IN_MEM:
16662 case X86::FP80_TO_INT64_IN_MEM: {
16663 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16664 DebugLoc DL = MI->getDebugLoc();
16666 // Change the floating point control register to use "round towards zero"
16667 // mode when truncating to an integer value.
16668 MachineFunction *F = BB->getParent();
16669 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16670 addFrameReference(BuildMI(*BB, MI, DL,
16671 TII->get(X86::FNSTCW16m)), CWFrameIdx);
16673 // Load the old value of the high byte of the control word...
16675 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16676 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16679 // Set the high part to be round to zero...
16680 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16683 // Reload the modified control word now...
16684 addFrameReference(BuildMI(*BB, MI, DL,
16685 TII->get(X86::FLDCW16m)), CWFrameIdx);
16687 // Restore the memory image of control word to original value
16688 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16691 // Get the X86 opcode to use.
16693 switch (MI->getOpcode()) {
16694 default: llvm_unreachable("illegal opcode!");
16695 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16696 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16697 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16698 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16699 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16700 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16701 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16702 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16703 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16707 MachineOperand &Op = MI->getOperand(0);
16709 AM.BaseType = X86AddressMode::RegBase;
16710 AM.Base.Reg = Op.getReg();
16712 AM.BaseType = X86AddressMode::FrameIndexBase;
16713 AM.Base.FrameIndex = Op.getIndex();
16715 Op = MI->getOperand(1);
16717 AM.Scale = Op.getImm();
16718 Op = MI->getOperand(2);
16720 AM.IndexReg = Op.getImm();
16721 Op = MI->getOperand(3);
16722 if (Op.isGlobal()) {
16723 AM.GV = Op.getGlobal();
16725 AM.Disp = Op.getImm();
16727 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16728 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16730 // Reload the original control word now.
16731 addFrameReference(BuildMI(*BB, MI, DL,
16732 TII->get(X86::FLDCW16m)), CWFrameIdx);
16734 MI->eraseFromParent(); // The pseudo instruction is gone now.
16737 // String/text processing lowering.
16738 case X86::PCMPISTRM128REG:
16739 case X86::VPCMPISTRM128REG:
16740 case X86::PCMPISTRM128MEM:
16741 case X86::VPCMPISTRM128MEM:
16742 case X86::PCMPESTRM128REG:
16743 case X86::VPCMPESTRM128REG:
16744 case X86::PCMPESTRM128MEM:
16745 case X86::VPCMPESTRM128MEM:
16746 assert(Subtarget->hasSSE42() &&
16747 "Target must have SSE4.2 or AVX features enabled");
16748 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16750 // String/text processing lowering.
16751 case X86::PCMPISTRIREG:
16752 case X86::VPCMPISTRIREG:
16753 case X86::PCMPISTRIMEM:
16754 case X86::VPCMPISTRIMEM:
16755 case X86::PCMPESTRIREG:
16756 case X86::VPCMPESTRIREG:
16757 case X86::PCMPESTRIMEM:
16758 case X86::VPCMPESTRIMEM:
16759 assert(Subtarget->hasSSE42() &&
16760 "Target must have SSE4.2 or AVX features enabled");
16761 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16763 // Thread synchronization.
16765 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16769 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16771 // Atomic Lowering.
16772 case X86::ATOMAND8:
16773 case X86::ATOMAND16:
16774 case X86::ATOMAND32:
16775 case X86::ATOMAND64:
16778 case X86::ATOMOR16:
16779 case X86::ATOMOR32:
16780 case X86::ATOMOR64:
16782 case X86::ATOMXOR16:
16783 case X86::ATOMXOR8:
16784 case X86::ATOMXOR32:
16785 case X86::ATOMXOR64:
16787 case X86::ATOMNAND8:
16788 case X86::ATOMNAND16:
16789 case X86::ATOMNAND32:
16790 case X86::ATOMNAND64:
16792 case X86::ATOMMAX8:
16793 case X86::ATOMMAX16:
16794 case X86::ATOMMAX32:
16795 case X86::ATOMMAX64:
16797 case X86::ATOMMIN8:
16798 case X86::ATOMMIN16:
16799 case X86::ATOMMIN32:
16800 case X86::ATOMMIN64:
16802 case X86::ATOMUMAX8:
16803 case X86::ATOMUMAX16:
16804 case X86::ATOMUMAX32:
16805 case X86::ATOMUMAX64:
16807 case X86::ATOMUMIN8:
16808 case X86::ATOMUMIN16:
16809 case X86::ATOMUMIN32:
16810 case X86::ATOMUMIN64:
16811 return EmitAtomicLoadArith(MI, BB);
16813 // This group does 64-bit operations on a 32-bit host.
16814 case X86::ATOMAND6432:
16815 case X86::ATOMOR6432:
16816 case X86::ATOMXOR6432:
16817 case X86::ATOMNAND6432:
16818 case X86::ATOMADD6432:
16819 case X86::ATOMSUB6432:
16820 case X86::ATOMMAX6432:
16821 case X86::ATOMMIN6432:
16822 case X86::ATOMUMAX6432:
16823 case X86::ATOMUMIN6432:
16824 case X86::ATOMSWAP6432:
16825 return EmitAtomicLoadArith6432(MI, BB);
16827 case X86::VASTART_SAVE_XMM_REGS:
16828 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16830 case X86::VAARG_64:
16831 return EmitVAARG64WithCustomInserter(MI, BB);
16833 case X86::EH_SjLj_SetJmp32:
16834 case X86::EH_SjLj_SetJmp64:
16835 return emitEHSjLjSetJmp(MI, BB);
16837 case X86::EH_SjLj_LongJmp32:
16838 case X86::EH_SjLj_LongJmp64:
16839 return emitEHSjLjLongJmp(MI, BB);
16841 case TargetOpcode::STACKMAP:
16842 case TargetOpcode::PATCHPOINT:
16843 return emitPatchPoint(MI, BB);
16845 case X86::VFMADDPDr213r:
16846 case X86::VFMADDPSr213r:
16847 case X86::VFMADDSDr213r:
16848 case X86::VFMADDSSr213r:
16849 case X86::VFMSUBPDr213r:
16850 case X86::VFMSUBPSr213r:
16851 case X86::VFMSUBSDr213r:
16852 case X86::VFMSUBSSr213r:
16853 case X86::VFNMADDPDr213r:
16854 case X86::VFNMADDPSr213r:
16855 case X86::VFNMADDSDr213r:
16856 case X86::VFNMADDSSr213r:
16857 case X86::VFNMSUBPDr213r:
16858 case X86::VFNMSUBPSr213r:
16859 case X86::VFNMSUBSDr213r:
16860 case X86::VFNMSUBSSr213r:
16861 case X86::VFMADDPDr213rY:
16862 case X86::VFMADDPSr213rY:
16863 case X86::VFMSUBPDr213rY:
16864 case X86::VFMSUBPSr213rY:
16865 case X86::VFNMADDPDr213rY:
16866 case X86::VFNMADDPSr213rY:
16867 case X86::VFNMSUBPDr213rY:
16868 case X86::VFNMSUBPSr213rY:
16869 return emitFMA3Instr(MI, BB);
16873 //===----------------------------------------------------------------------===//
16874 // X86 Optimization Hooks
16875 //===----------------------------------------------------------------------===//
16877 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16880 const SelectionDAG &DAG,
16881 unsigned Depth) const {
16882 unsigned BitWidth = KnownZero.getBitWidth();
16883 unsigned Opc = Op.getOpcode();
16884 assert((Opc >= ISD::BUILTIN_OP_END ||
16885 Opc == ISD::INTRINSIC_WO_CHAIN ||
16886 Opc == ISD::INTRINSIC_W_CHAIN ||
16887 Opc == ISD::INTRINSIC_VOID) &&
16888 "Should use MaskedValueIsZero if you don't know whether Op"
16889 " is a target node!");
16891 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
16905 // These nodes' second result is a boolean.
16906 if (Op.getResNo() == 0)
16909 case X86ISD::SETCC:
16910 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16912 case ISD::INTRINSIC_WO_CHAIN: {
16913 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16914 unsigned NumLoBits = 0;
16917 case Intrinsic::x86_sse_movmsk_ps:
16918 case Intrinsic::x86_avx_movmsk_ps_256:
16919 case Intrinsic::x86_sse2_movmsk_pd:
16920 case Intrinsic::x86_avx_movmsk_pd_256:
16921 case Intrinsic::x86_mmx_pmovmskb:
16922 case Intrinsic::x86_sse2_pmovmskb_128:
16923 case Intrinsic::x86_avx2_pmovmskb: {
16924 // High bits of movmskp{s|d}, pmovmskb are known zero.
16926 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16927 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
16928 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
16929 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
16930 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
16931 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
16932 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
16933 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
16935 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16944 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16946 const SelectionDAG &,
16947 unsigned Depth) const {
16948 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16949 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16950 return Op.getValueType().getScalarType().getSizeInBits();
16956 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16957 /// node is a GlobalAddress + offset.
16958 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16959 const GlobalValue* &GA,
16960 int64_t &Offset) const {
16961 if (N->getOpcode() == X86ISD::Wrapper) {
16962 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16963 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16964 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16968 return TargetLowering::isGAPlusOffset(N, GA, Offset);
16971 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16972 /// same as extracting the high 128-bit part of 256-bit vector and then
16973 /// inserting the result into the low part of a new 256-bit vector
16974 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16975 EVT VT = SVOp->getValueType(0);
16976 unsigned NumElems = VT.getVectorNumElements();
16978 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16979 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16980 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16981 SVOp->getMaskElt(j) >= 0)
16987 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16988 /// same as extracting the low 128-bit part of 256-bit vector and then
16989 /// inserting the result into the high part of a new 256-bit vector
16990 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16991 EVT VT = SVOp->getValueType(0);
16992 unsigned NumElems = VT.getVectorNumElements();
16994 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16995 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16996 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16997 SVOp->getMaskElt(j) >= 0)
17003 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17004 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17005 TargetLowering::DAGCombinerInfo &DCI,
17006 const X86Subtarget* Subtarget) {
17008 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17009 SDValue V1 = SVOp->getOperand(0);
17010 SDValue V2 = SVOp->getOperand(1);
17011 EVT VT = SVOp->getValueType(0);
17012 unsigned NumElems = VT.getVectorNumElements();
17014 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17015 V2.getOpcode() == ISD::CONCAT_VECTORS) {
17019 // V UNDEF BUILD_VECTOR UNDEF
17021 // CONCAT_VECTOR CONCAT_VECTOR
17024 // RESULT: V + zero extended
17026 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17027 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17028 V1.getOperand(1).getOpcode() != ISD::UNDEF)
17031 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17034 // To match the shuffle mask, the first half of the mask should
17035 // be exactly the first vector, and all the rest a splat with the
17036 // first element of the second one.
17037 for (unsigned i = 0; i != NumElems/2; ++i)
17038 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17039 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17042 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17043 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17044 if (Ld->hasNUsesOfValue(1, 0)) {
17045 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17046 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17048 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17049 array_lengthof(Ops),
17051 Ld->getPointerInfo(),
17052 Ld->getAlignment(),
17053 false/*isVolatile*/, true/*ReadMem*/,
17054 false/*WriteMem*/);
17056 // Make sure the newly-created LOAD is in the same position as Ld in
17057 // terms of dependency. We create a TokenFactor for Ld and ResNode,
17058 // and update uses of Ld's output chain to use the TokenFactor.
17059 if (Ld->hasAnyUseOfValue(1)) {
17060 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17061 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17062 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17063 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17064 SDValue(ResNode.getNode(), 1));
17067 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17071 // Emit a zeroed vector and insert the desired subvector on its
17073 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17074 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17075 return DCI.CombineTo(N, InsV);
17078 //===--------------------------------------------------------------------===//
17079 // Combine some shuffles into subvector extracts and inserts:
17082 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17083 if (isShuffleHigh128VectorInsertLow(SVOp)) {
17084 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17085 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17086 return DCI.CombineTo(N, InsV);
17089 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17090 if (isShuffleLow128VectorInsertHigh(SVOp)) {
17091 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17092 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17093 return DCI.CombineTo(N, InsV);
17099 /// PerformShuffleCombine - Performs several different shuffle combines.
17100 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17101 TargetLowering::DAGCombinerInfo &DCI,
17102 const X86Subtarget *Subtarget) {
17104 EVT VT = N->getValueType(0);
17106 // Don't create instructions with illegal types after legalize types has run.
17107 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17108 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17111 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17112 if (Subtarget->hasFp256() && VT.is256BitVector() &&
17113 N->getOpcode() == ISD::VECTOR_SHUFFLE)
17114 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17116 // Only handle 128 wide vector from here on.
17117 if (!VT.is128BitVector())
17120 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17121 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17122 // consecutive, non-overlapping, and in the right order.
17123 SmallVector<SDValue, 16> Elts;
17124 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17125 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17127 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17130 /// PerformTruncateCombine - Converts truncate operation to
17131 /// a sequence of vector shuffle operations.
17132 /// It is possible when we truncate 256-bit vector to 128-bit vector
17133 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17134 TargetLowering::DAGCombinerInfo &DCI,
17135 const X86Subtarget *Subtarget) {
17139 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17140 /// specific shuffle of a load can be folded into a single element load.
17141 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17142 /// shuffles have been customed lowered so we need to handle those here.
17143 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17144 TargetLowering::DAGCombinerInfo &DCI) {
17145 if (DCI.isBeforeLegalizeOps())
17148 SDValue InVec = N->getOperand(0);
17149 SDValue EltNo = N->getOperand(1);
17151 if (!isa<ConstantSDNode>(EltNo))
17154 EVT VT = InVec.getValueType();
17156 bool HasShuffleIntoBitcast = false;
17157 if (InVec.getOpcode() == ISD::BITCAST) {
17158 // Don't duplicate a load with other uses.
17159 if (!InVec.hasOneUse())
17161 EVT BCVT = InVec.getOperand(0).getValueType();
17162 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17164 InVec = InVec.getOperand(0);
17165 HasShuffleIntoBitcast = true;
17168 if (!isTargetShuffle(InVec.getOpcode()))
17171 // Don't duplicate a load with other uses.
17172 if (!InVec.hasOneUse())
17175 SmallVector<int, 16> ShuffleMask;
17177 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17181 // Select the input vector, guarding against out of range extract vector.
17182 unsigned NumElems = VT.getVectorNumElements();
17183 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17184 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17185 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17186 : InVec.getOperand(1);
17188 // If inputs to shuffle are the same for both ops, then allow 2 uses
17189 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17191 if (LdNode.getOpcode() == ISD::BITCAST) {
17192 // Don't duplicate a load with other uses.
17193 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17196 AllowedUses = 1; // only allow 1 load use if we have a bitcast
17197 LdNode = LdNode.getOperand(0);
17200 if (!ISD::isNormalLoad(LdNode.getNode()))
17203 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17205 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17208 if (HasShuffleIntoBitcast) {
17209 // If there's a bitcast before the shuffle, check if the load type and
17210 // alignment is valid.
17211 unsigned Align = LN0->getAlignment();
17212 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17213 unsigned NewAlign = TLI.getDataLayout()->
17214 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17216 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17220 // All checks match so transform back to vector_shuffle so that DAG combiner
17221 // can finish the job
17224 // Create shuffle node taking into account the case that its a unary shuffle
17225 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17226 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17227 InVec.getOperand(0), Shuffle,
17229 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17230 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17234 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17235 /// generation and convert it from being a bunch of shuffles and extracts
17236 /// to a simple store and scalar loads to extract the elements.
17237 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17238 TargetLowering::DAGCombinerInfo &DCI) {
17239 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17240 if (NewOp.getNode())
17243 SDValue InputVector = N->getOperand(0);
17245 // Detect whether we are trying to convert from mmx to i32 and the bitcast
17246 // from mmx to v2i32 has a single usage.
17247 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17248 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17249 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17250 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17251 N->getValueType(0),
17252 InputVector.getNode()->getOperand(0));
17254 // Only operate on vectors of 4 elements, where the alternative shuffling
17255 // gets to be more expensive.
17256 if (InputVector.getValueType() != MVT::v4i32)
17259 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17260 // single use which is a sign-extend or zero-extend, and all elements are
17262 SmallVector<SDNode *, 4> Uses;
17263 unsigned ExtractedElements = 0;
17264 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17265 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17266 if (UI.getUse().getResNo() != InputVector.getResNo())
17269 SDNode *Extract = *UI;
17270 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17273 if (Extract->getValueType(0) != MVT::i32)
17275 if (!Extract->hasOneUse())
17277 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17278 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17280 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17283 // Record which element was extracted.
17284 ExtractedElements |=
17285 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17287 Uses.push_back(Extract);
17290 // If not all the elements were used, this may not be worthwhile.
17291 if (ExtractedElements != 15)
17294 // Ok, we've now decided to do the transformation.
17295 SDLoc dl(InputVector);
17297 // Store the value to a temporary stack slot.
17298 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17299 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17300 MachinePointerInfo(), false, false, 0);
17302 // Replace each use (extract) with a load of the appropriate element.
17303 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17304 UE = Uses.end(); UI != UE; ++UI) {
17305 SDNode *Extract = *UI;
17307 // cOMpute the element's address.
17308 SDValue Idx = Extract->getOperand(1);
17310 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17311 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17312 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17313 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17315 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17316 StackPtr, OffsetVal);
17318 // Load the scalar.
17319 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17320 ScalarAddr, MachinePointerInfo(),
17321 false, false, false, 0);
17323 // Replace the exact with the load.
17324 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17327 // The replacement was made in place; don't return anything.
17331 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17332 static std::pair<unsigned, bool>
17333 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17334 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17335 if (!VT.isVector())
17336 return std::make_pair(0, false);
17338 bool NeedSplit = false;
17339 switch (VT.getSimpleVT().SimpleTy) {
17340 default: return std::make_pair(0, false);
17344 if (!Subtarget->hasAVX2())
17346 if (!Subtarget->hasAVX())
17347 return std::make_pair(0, false);
17352 if (!Subtarget->hasSSE2())
17353 return std::make_pair(0, false);
17356 // SSE2 has only a small subset of the operations.
17357 bool hasUnsigned = Subtarget->hasSSE41() ||
17358 (Subtarget->hasSSE2() && VT == MVT::v16i8);
17359 bool hasSigned = Subtarget->hasSSE41() ||
17360 (Subtarget->hasSSE2() && VT == MVT::v8i16);
17362 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17365 // Check for x CC y ? x : y.
17366 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17367 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17372 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17375 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17378 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17381 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17383 // Check for x CC y ? y : x -- a min/max with reversed arms.
17384 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17385 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17390 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17393 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17396 Opc = hasSigned ? X86ISD::SMAX : 0; break;
17399 Opc = hasSigned ? X86ISD::SMIN : 0; break;
17403 return std::make_pair(Opc, NeedSplit);
17406 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17408 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17409 TargetLowering::DAGCombinerInfo &DCI,
17410 const X86Subtarget *Subtarget) {
17412 SDValue Cond = N->getOperand(0);
17413 // Get the LHS/RHS of the select.
17414 SDValue LHS = N->getOperand(1);
17415 SDValue RHS = N->getOperand(2);
17416 EVT VT = LHS.getValueType();
17417 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17419 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17420 // instructions match the semantics of the common C idiom x<y?x:y but not
17421 // x<=y?x:y, because of how they handle negative zero (which can be
17422 // ignored in unsafe-math mode).
17423 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17424 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17425 (Subtarget->hasSSE2() ||
17426 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17427 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17429 unsigned Opcode = 0;
17430 // Check for x CC y ? x : y.
17431 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17432 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17436 // Converting this to a min would handle NaNs incorrectly, and swapping
17437 // the operands would cause it to handle comparisons between positive
17438 // and negative zero incorrectly.
17439 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17440 if (!DAG.getTarget().Options.UnsafeFPMath &&
17441 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17443 std::swap(LHS, RHS);
17445 Opcode = X86ISD::FMIN;
17448 // Converting this to a min would handle comparisons between positive
17449 // and negative zero incorrectly.
17450 if (!DAG.getTarget().Options.UnsafeFPMath &&
17451 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17453 Opcode = X86ISD::FMIN;
17456 // Converting this to a min would handle both negative zeros and NaNs
17457 // incorrectly, but we can swap the operands to fix both.
17458 std::swap(LHS, RHS);
17462 Opcode = X86ISD::FMIN;
17466 // Converting this to a max would handle comparisons between positive
17467 // and negative zero incorrectly.
17468 if (!DAG.getTarget().Options.UnsafeFPMath &&
17469 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17471 Opcode = X86ISD::FMAX;
17474 // Converting this to a max would handle NaNs incorrectly, and swapping
17475 // the operands would cause it to handle comparisons between positive
17476 // and negative zero incorrectly.
17477 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17478 if (!DAG.getTarget().Options.UnsafeFPMath &&
17479 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17481 std::swap(LHS, RHS);
17483 Opcode = X86ISD::FMAX;
17486 // Converting this to a max would handle both negative zeros and NaNs
17487 // incorrectly, but we can swap the operands to fix both.
17488 std::swap(LHS, RHS);
17492 Opcode = X86ISD::FMAX;
17495 // Check for x CC y ? y : x -- a min/max with reversed arms.
17496 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17497 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17501 // Converting this to a min would handle comparisons between positive
17502 // and negative zero incorrectly, and swapping the operands would
17503 // cause it to handle NaNs incorrectly.
17504 if (!DAG.getTarget().Options.UnsafeFPMath &&
17505 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17506 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17508 std::swap(LHS, RHS);
17510 Opcode = X86ISD::FMIN;
17513 // Converting this to a min would handle NaNs incorrectly.
17514 if (!DAG.getTarget().Options.UnsafeFPMath &&
17515 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17517 Opcode = X86ISD::FMIN;
17520 // Converting this to a min would handle both negative zeros and NaNs
17521 // incorrectly, but we can swap the operands to fix both.
17522 std::swap(LHS, RHS);
17526 Opcode = X86ISD::FMIN;
17530 // Converting this to a max would handle NaNs incorrectly.
17531 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17533 Opcode = X86ISD::FMAX;
17536 // Converting this to a max would handle comparisons between positive
17537 // and negative zero incorrectly, and swapping the operands would
17538 // cause it to handle NaNs incorrectly.
17539 if (!DAG.getTarget().Options.UnsafeFPMath &&
17540 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17541 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17543 std::swap(LHS, RHS);
17545 Opcode = X86ISD::FMAX;
17548 // Converting this to a max would handle both negative zeros and NaNs
17549 // incorrectly, but we can swap the operands to fix both.
17550 std::swap(LHS, RHS);
17554 Opcode = X86ISD::FMAX;
17560 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17563 EVT CondVT = Cond.getValueType();
17564 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17565 CondVT.getVectorElementType() == MVT::i1) {
17566 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17567 // lowering on AVX-512. In this case we convert it to
17568 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17569 // The same situation for all 128 and 256-bit vectors of i8 and i16
17570 EVT OpVT = LHS.getValueType();
17571 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17572 (OpVT.getVectorElementType() == MVT::i8 ||
17573 OpVT.getVectorElementType() == MVT::i16)) {
17574 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17575 DCI.AddToWorklist(Cond.getNode());
17576 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17579 // If this is a select between two integer constants, try to do some
17581 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17582 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17583 // Don't do this for crazy integer types.
17584 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17585 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17586 // so that TrueC (the true value) is larger than FalseC.
17587 bool NeedsCondInvert = false;
17589 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17590 // Efficiently invertible.
17591 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
17592 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
17593 isa<ConstantSDNode>(Cond.getOperand(1))))) {
17594 NeedsCondInvert = true;
17595 std::swap(TrueC, FalseC);
17598 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
17599 if (FalseC->getAPIntValue() == 0 &&
17600 TrueC->getAPIntValue().isPowerOf2()) {
17601 if (NeedsCondInvert) // Invert the condition if needed.
17602 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17603 DAG.getConstant(1, Cond.getValueType()));
17605 // Zero extend the condition if needed.
17606 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17608 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17609 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17610 DAG.getConstant(ShAmt, MVT::i8));
17613 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17614 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17615 if (NeedsCondInvert) // Invert the condition if needed.
17616 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17617 DAG.getConstant(1, Cond.getValueType()));
17619 // Zero extend the condition if needed.
17620 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17621 FalseC->getValueType(0), Cond);
17622 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17623 SDValue(FalseC, 0));
17626 // Optimize cases that will turn into an LEA instruction. This requires
17627 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17628 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17629 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17630 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17632 bool isFastMultiplier = false;
17634 switch ((unsigned char)Diff) {
17636 case 1: // result = add base, cond
17637 case 2: // result = lea base( , cond*2)
17638 case 3: // result = lea base(cond, cond*2)
17639 case 4: // result = lea base( , cond*4)
17640 case 5: // result = lea base(cond, cond*4)
17641 case 8: // result = lea base( , cond*8)
17642 case 9: // result = lea base(cond, cond*8)
17643 isFastMultiplier = true;
17648 if (isFastMultiplier) {
17649 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17650 if (NeedsCondInvert) // Invert the condition if needed.
17651 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17652 DAG.getConstant(1, Cond.getValueType()));
17654 // Zero extend the condition if needed.
17655 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17657 // Scale the condition by the difference.
17659 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17660 DAG.getConstant(Diff, Cond.getValueType()));
17662 // Add the base if non-zero.
17663 if (FalseC->getAPIntValue() != 0)
17664 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17665 SDValue(FalseC, 0));
17672 // Canonicalize max and min:
17673 // (x > y) ? x : y -> (x >= y) ? x : y
17674 // (x < y) ? x : y -> (x <= y) ? x : y
17675 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17676 // the need for an extra compare
17677 // against zero. e.g.
17678 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17680 // testl %edi, %edi
17682 // cmovgl %edi, %eax
17686 // cmovsl %eax, %edi
17687 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17688 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17689 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17690 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17695 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17696 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17697 Cond.getOperand(0), Cond.getOperand(1), NewCC);
17698 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17703 // Early exit check
17704 if (!TLI.isTypeLegal(VT))
17707 // Match VSELECTs into subs with unsigned saturation.
17708 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17709 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17710 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17711 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17712 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17714 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17715 // left side invert the predicate to simplify logic below.
17717 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17719 CC = ISD::getSetCCInverse(CC, true);
17720 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17724 if (Other.getNode() && Other->getNumOperands() == 2 &&
17725 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17726 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17727 SDValue CondRHS = Cond->getOperand(1);
17729 // Look for a general sub with unsigned saturation first.
17730 // x >= y ? x-y : 0 --> subus x, y
17731 // x > y ? x-y : 0 --> subus x, y
17732 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17733 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17734 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17736 // If the RHS is a constant we have to reverse the const canonicalization.
17737 // x > C-1 ? x+-C : 0 --> subus x, C
17738 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17739 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17740 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17741 if (CondRHS.getConstantOperandVal(0) == -A-1)
17742 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17743 DAG.getConstant(-A, VT));
17746 // Another special case: If C was a sign bit, the sub has been
17747 // canonicalized into a xor.
17748 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17749 // it's safe to decanonicalize the xor?
17750 // x s< 0 ? x^C : 0 --> subus x, C
17751 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17752 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17753 isSplatVector(OpRHS.getNode())) {
17754 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17756 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17761 // Try to match a min/max vector operation.
17762 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17763 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17764 unsigned Opc = ret.first;
17765 bool NeedSplit = ret.second;
17767 if (Opc && NeedSplit) {
17768 unsigned NumElems = VT.getVectorNumElements();
17769 // Extract the LHS vectors
17770 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17771 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17773 // Extract the RHS vectors
17774 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17775 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17777 // Create min/max for each subvector
17778 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17779 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17781 // Merge the result
17782 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17784 return DAG.getNode(Opc, DL, VT, LHS, RHS);
17787 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17788 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17789 // Check if SETCC has already been promoted
17790 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17791 // Check that condition value type matches vselect operand type
17794 assert(Cond.getValueType().isVector() &&
17795 "vector select expects a vector selector!");
17797 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17798 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17800 if (!TValIsAllOnes && !FValIsAllZeros) {
17801 // Try invert the condition if true value is not all 1s and false value
17803 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17804 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17806 if (TValIsAllZeros || FValIsAllOnes) {
17807 SDValue CC = Cond.getOperand(2);
17808 ISD::CondCode NewCC =
17809 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17810 Cond.getOperand(0).getValueType().isInteger());
17811 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17812 std::swap(LHS, RHS);
17813 TValIsAllOnes = FValIsAllOnes;
17814 FValIsAllZeros = TValIsAllZeros;
17818 if (TValIsAllOnes || FValIsAllZeros) {
17821 if (TValIsAllOnes && FValIsAllZeros)
17823 else if (TValIsAllOnes)
17824 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17825 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17826 else if (FValIsAllZeros)
17827 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17828 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17830 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17834 // Try to fold this VSELECT into a MOVSS/MOVSD
17835 if (N->getOpcode() == ISD::VSELECT &&
17836 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17837 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17838 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17839 bool CanFold = false;
17840 unsigned NumElems = Cond.getNumOperands();
17844 if (isZero(Cond.getOperand(0))) {
17847 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17848 // fold (vselect <0,-1> -> (movsd A, B)
17849 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17850 CanFold = isAllOnes(Cond.getOperand(i));
17851 } else if (isAllOnes(Cond.getOperand(0))) {
17855 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17856 // fold (vselect <-1,0> -> (movsd B, A)
17857 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17858 CanFold = isZero(Cond.getOperand(i));
17862 if (VT == MVT::v4i32 || VT == MVT::v4f32)
17863 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17864 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17867 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17868 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17869 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17870 // (v2i64 (bitcast B)))))
17872 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17873 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17874 // (v2f64 (bitcast B)))))
17876 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17877 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17878 // (v2i64 (bitcast A)))))
17880 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17881 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17882 // (v2f64 (bitcast A)))))
17884 CanFold = (isZero(Cond.getOperand(0)) &&
17885 isZero(Cond.getOperand(1)) &&
17886 isAllOnes(Cond.getOperand(2)) &&
17887 isAllOnes(Cond.getOperand(3)));
17889 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17890 isAllOnes(Cond.getOperand(1)) &&
17891 isZero(Cond.getOperand(2)) &&
17892 isZero(Cond.getOperand(3))) {
17894 std::swap(LHS, RHS);
17898 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17899 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17900 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17901 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17903 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17909 // If we know that this node is legal then we know that it is going to be
17910 // matched by one of the SSE/AVX BLEND instructions. These instructions only
17911 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17912 // to simplify previous instructions.
17913 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17914 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17915 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17917 // Don't optimize vector selects that map to mask-registers.
17921 // Check all uses of that condition operand to check whether it will be
17922 // consumed by non-BLEND instructions, which may depend on all bits are set
17924 for (SDNode::use_iterator I = Cond->use_begin(),
17925 E = Cond->use_end(); I != E; ++I)
17926 if (I->getOpcode() != ISD::VSELECT)
17927 // TODO: Add other opcodes eventually lowered into BLEND.
17930 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17931 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17933 APInt KnownZero, KnownOne;
17934 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17935 DCI.isBeforeLegalizeOps());
17936 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17937 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17938 DCI.CommitTargetLoweringOpt(TLO);
17944 // Check whether a boolean test is testing a boolean value generated by
17945 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17948 // Simplify the following patterns:
17949 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17950 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17951 // to (Op EFLAGS Cond)
17953 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17954 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17955 // to (Op EFLAGS !Cond)
17957 // where Op could be BRCOND or CMOV.
17959 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17960 // Quit if not CMP and SUB with its value result used.
17961 if (Cmp.getOpcode() != X86ISD::CMP &&
17962 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17965 // Quit if not used as a boolean value.
17966 if (CC != X86::COND_E && CC != X86::COND_NE)
17969 // Check CMP operands. One of them should be 0 or 1 and the other should be
17970 // an SetCC or extended from it.
17971 SDValue Op1 = Cmp.getOperand(0);
17972 SDValue Op2 = Cmp.getOperand(1);
17975 const ConstantSDNode* C = nullptr;
17976 bool needOppositeCond = (CC == X86::COND_E);
17977 bool checkAgainstTrue = false; // Is it a comparison against 1?
17979 if ((C = dyn_cast<ConstantSDNode>(Op1)))
17981 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17983 else // Quit if all operands are not constants.
17986 if (C->getZExtValue() == 1) {
17987 needOppositeCond = !needOppositeCond;
17988 checkAgainstTrue = true;
17989 } else if (C->getZExtValue() != 0)
17990 // Quit if the constant is neither 0 or 1.
17993 bool truncatedToBoolWithAnd = false;
17994 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17995 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17996 SetCC.getOpcode() == ISD::TRUNCATE ||
17997 SetCC.getOpcode() == ISD::AND) {
17998 if (SetCC.getOpcode() == ISD::AND) {
18000 ConstantSDNode *CS;
18001 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18002 CS->getZExtValue() == 1)
18004 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18005 CS->getZExtValue() == 1)
18009 SetCC = SetCC.getOperand(OpIdx);
18010 truncatedToBoolWithAnd = true;
18012 SetCC = SetCC.getOperand(0);
18015 switch (SetCC.getOpcode()) {
18016 case X86ISD::SETCC_CARRY:
18017 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18018 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18019 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18020 // truncated to i1 using 'and'.
18021 if (checkAgainstTrue && !truncatedToBoolWithAnd)
18023 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18024 "Invalid use of SETCC_CARRY!");
18026 case X86ISD::SETCC:
18027 // Set the condition code or opposite one if necessary.
18028 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18029 if (needOppositeCond)
18030 CC = X86::GetOppositeBranchCondition(CC);
18031 return SetCC.getOperand(1);
18032 case X86ISD::CMOV: {
18033 // Check whether false/true value has canonical one, i.e. 0 or 1.
18034 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18035 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18036 // Quit if true value is not a constant.
18039 // Quit if false value is not a constant.
18041 SDValue Op = SetCC.getOperand(0);
18042 // Skip 'zext' or 'trunc' node.
18043 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18044 Op.getOpcode() == ISD::TRUNCATE)
18045 Op = Op.getOperand(0);
18046 // A special case for rdrand/rdseed, where 0 is set if false cond is
18048 if ((Op.getOpcode() != X86ISD::RDRAND &&
18049 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18052 // Quit if false value is not the constant 0 or 1.
18053 bool FValIsFalse = true;
18054 if (FVal && FVal->getZExtValue() != 0) {
18055 if (FVal->getZExtValue() != 1)
18057 // If FVal is 1, opposite cond is needed.
18058 needOppositeCond = !needOppositeCond;
18059 FValIsFalse = false;
18061 // Quit if TVal is not the constant opposite of FVal.
18062 if (FValIsFalse && TVal->getZExtValue() != 1)
18064 if (!FValIsFalse && TVal->getZExtValue() != 0)
18066 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18067 if (needOppositeCond)
18068 CC = X86::GetOppositeBranchCondition(CC);
18069 return SetCC.getOperand(3);
18076 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18077 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18078 TargetLowering::DAGCombinerInfo &DCI,
18079 const X86Subtarget *Subtarget) {
18082 // If the flag operand isn't dead, don't touch this CMOV.
18083 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18086 SDValue FalseOp = N->getOperand(0);
18087 SDValue TrueOp = N->getOperand(1);
18088 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18089 SDValue Cond = N->getOperand(3);
18091 if (CC == X86::COND_E || CC == X86::COND_NE) {
18092 switch (Cond.getOpcode()) {
18096 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18097 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18098 return (CC == X86::COND_E) ? FalseOp : TrueOp;
18104 Flags = checkBoolTestSetCCCombine(Cond, CC);
18105 if (Flags.getNode() &&
18106 // Extra check as FCMOV only supports a subset of X86 cond.
18107 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18108 SDValue Ops[] = { FalseOp, TrueOp,
18109 DAG.getConstant(CC, MVT::i8), Flags };
18110 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18113 // If this is a select between two integer constants, try to do some
18114 // optimizations. Note that the operands are ordered the opposite of SELECT
18116 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18117 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18118 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18119 // larger than FalseC (the false value).
18120 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18121 CC = X86::GetOppositeBranchCondition(CC);
18122 std::swap(TrueC, FalseC);
18123 std::swap(TrueOp, FalseOp);
18126 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
18127 // This is efficient for any integer data type (including i8/i16) and
18129 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18130 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18131 DAG.getConstant(CC, MVT::i8), Cond);
18133 // Zero extend the condition if needed.
18134 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18136 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18137 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18138 DAG.getConstant(ShAmt, MVT::i8));
18139 if (N->getNumValues() == 2) // Dead flag value?
18140 return DCI.CombineTo(N, Cond, SDValue());
18144 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
18145 // for any integer data type, including i8/i16.
18146 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18147 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18148 DAG.getConstant(CC, MVT::i8), Cond);
18150 // Zero extend the condition if needed.
18151 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18152 FalseC->getValueType(0), Cond);
18153 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18154 SDValue(FalseC, 0));
18156 if (N->getNumValues() == 2) // Dead flag value?
18157 return DCI.CombineTo(N, Cond, SDValue());
18161 // Optimize cases that will turn into an LEA instruction. This requires
18162 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18163 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18164 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18165 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18167 bool isFastMultiplier = false;
18169 switch ((unsigned char)Diff) {
18171 case 1: // result = add base, cond
18172 case 2: // result = lea base( , cond*2)
18173 case 3: // result = lea base(cond, cond*2)
18174 case 4: // result = lea base( , cond*4)
18175 case 5: // result = lea base(cond, cond*4)
18176 case 8: // result = lea base( , cond*8)
18177 case 9: // result = lea base(cond, cond*8)
18178 isFastMultiplier = true;
18183 if (isFastMultiplier) {
18184 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18185 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18186 DAG.getConstant(CC, MVT::i8), Cond);
18187 // Zero extend the condition if needed.
18188 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18190 // Scale the condition by the difference.
18192 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18193 DAG.getConstant(Diff, Cond.getValueType()));
18195 // Add the base if non-zero.
18196 if (FalseC->getAPIntValue() != 0)
18197 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18198 SDValue(FalseC, 0));
18199 if (N->getNumValues() == 2) // Dead flag value?
18200 return DCI.CombineTo(N, Cond, SDValue());
18207 // Handle these cases:
18208 // (select (x != c), e, c) -> select (x != c), e, x),
18209 // (select (x == c), c, e) -> select (x == c), x, e)
18210 // where the c is an integer constant, and the "select" is the combination
18211 // of CMOV and CMP.
18213 // The rationale for this change is that the conditional-move from a constant
18214 // needs two instructions, however, conditional-move from a register needs
18215 // only one instruction.
18217 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18218 // some instruction-combining opportunities. This opt needs to be
18219 // postponed as late as possible.
18221 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18222 // the DCI.xxxx conditions are provided to postpone the optimization as
18223 // late as possible.
18225 ConstantSDNode *CmpAgainst = nullptr;
18226 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18227 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18228 !isa<ConstantSDNode>(Cond.getOperand(0))) {
18230 if (CC == X86::COND_NE &&
18231 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18232 CC = X86::GetOppositeBranchCondition(CC);
18233 std::swap(TrueOp, FalseOp);
18236 if (CC == X86::COND_E &&
18237 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18238 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18239 DAG.getConstant(CC, MVT::i8), Cond };
18240 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18248 /// PerformMulCombine - Optimize a single multiply with constant into two
18249 /// in order to implement it with two cheaper instructions, e.g.
18250 /// LEA + SHL, LEA + LEA.
18251 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18252 TargetLowering::DAGCombinerInfo &DCI) {
18253 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18256 EVT VT = N->getValueType(0);
18257 if (VT != MVT::i64)
18260 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18263 uint64_t MulAmt = C->getZExtValue();
18264 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18267 uint64_t MulAmt1 = 0;
18268 uint64_t MulAmt2 = 0;
18269 if ((MulAmt % 9) == 0) {
18271 MulAmt2 = MulAmt / 9;
18272 } else if ((MulAmt % 5) == 0) {
18274 MulAmt2 = MulAmt / 5;
18275 } else if ((MulAmt % 3) == 0) {
18277 MulAmt2 = MulAmt / 3;
18280 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18283 if (isPowerOf2_64(MulAmt2) &&
18284 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18285 // If second multiplifer is pow2, issue it first. We want the multiply by
18286 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18288 std::swap(MulAmt1, MulAmt2);
18291 if (isPowerOf2_64(MulAmt1))
18292 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18293 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18295 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18296 DAG.getConstant(MulAmt1, VT));
18298 if (isPowerOf2_64(MulAmt2))
18299 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18300 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18302 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18303 DAG.getConstant(MulAmt2, VT));
18305 // Do not add new nodes to DAG combiner worklist.
18306 DCI.CombineTo(N, NewMul, false);
18311 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18312 SDValue N0 = N->getOperand(0);
18313 SDValue N1 = N->getOperand(1);
18314 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18315 EVT VT = N0.getValueType();
18317 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18318 // since the result of setcc_c is all zero's or all ones.
18319 if (VT.isInteger() && !VT.isVector() &&
18320 N1C && N0.getOpcode() == ISD::AND &&
18321 N0.getOperand(1).getOpcode() == ISD::Constant) {
18322 SDValue N00 = N0.getOperand(0);
18323 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18324 ((N00.getOpcode() == ISD::ANY_EXTEND ||
18325 N00.getOpcode() == ISD::ZERO_EXTEND) &&
18326 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18327 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18328 APInt ShAmt = N1C->getAPIntValue();
18329 Mask = Mask.shl(ShAmt);
18331 return DAG.getNode(ISD::AND, SDLoc(N), VT,
18332 N00, DAG.getConstant(Mask, VT));
18336 // Hardware support for vector shifts is sparse which makes us scalarize the
18337 // vector operations in many cases. Also, on sandybridge ADD is faster than
18339 // (shl V, 1) -> add V,V
18340 if (isSplatVector(N1.getNode())) {
18341 assert(N0.getValueType().isVector() && "Invalid vector shift type");
18342 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18343 // We shift all of the values by one. In many cases we do not have
18344 // hardware support for this operation. This is better expressed as an ADD
18346 if (N1C && (1 == N1C->getZExtValue())) {
18347 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18354 /// \brief Returns a vector of 0s if the node in input is a vector logical
18355 /// shift by a constant amount which is known to be bigger than or equal
18356 /// to the vector element size in bits.
18357 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18358 const X86Subtarget *Subtarget) {
18359 EVT VT = N->getValueType(0);
18361 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18362 (!Subtarget->hasInt256() ||
18363 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18366 SDValue Amt = N->getOperand(1);
18368 if (isSplatVector(Amt.getNode())) {
18369 SDValue SclrAmt = Amt->getOperand(0);
18370 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18371 APInt ShiftAmt = C->getAPIntValue();
18372 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18374 // SSE2/AVX2 logical shifts always return a vector of 0s
18375 // if the shift amount is bigger than or equal to
18376 // the element size. The constant shift amount will be
18377 // encoded as a 8-bit immediate.
18378 if (ShiftAmt.trunc(8).uge(MaxAmount))
18379 return getZeroVector(VT, Subtarget, DAG, DL);
18386 /// PerformShiftCombine - Combine shifts.
18387 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18388 TargetLowering::DAGCombinerInfo &DCI,
18389 const X86Subtarget *Subtarget) {
18390 if (N->getOpcode() == ISD::SHL) {
18391 SDValue V = PerformSHLCombine(N, DAG);
18392 if (V.getNode()) return V;
18395 if (N->getOpcode() != ISD::SRA) {
18396 // Try to fold this logical shift into a zero vector.
18397 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18398 if (V.getNode()) return V;
18404 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
18405 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18406 // and friends. Likewise for OR -> CMPNEQSS.
18407 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18408 TargetLowering::DAGCombinerInfo &DCI,
18409 const X86Subtarget *Subtarget) {
18412 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18413 // we're requiring SSE2 for both.
18414 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18415 SDValue N0 = N->getOperand(0);
18416 SDValue N1 = N->getOperand(1);
18417 SDValue CMP0 = N0->getOperand(1);
18418 SDValue CMP1 = N1->getOperand(1);
18421 // The SETCCs should both refer to the same CMP.
18422 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18425 SDValue CMP00 = CMP0->getOperand(0);
18426 SDValue CMP01 = CMP0->getOperand(1);
18427 EVT VT = CMP00.getValueType();
18429 if (VT == MVT::f32 || VT == MVT::f64) {
18430 bool ExpectingFlags = false;
18431 // Check for any users that want flags:
18432 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18433 !ExpectingFlags && UI != UE; ++UI)
18434 switch (UI->getOpcode()) {
18439 ExpectingFlags = true;
18441 case ISD::CopyToReg:
18442 case ISD::SIGN_EXTEND:
18443 case ISD::ZERO_EXTEND:
18444 case ISD::ANY_EXTEND:
18448 if (!ExpectingFlags) {
18449 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18450 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18452 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18453 X86::CondCode tmp = cc0;
18458 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
18459 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18460 // FIXME: need symbolic constants for these magic numbers.
18461 // See X86ATTInstPrinter.cpp:printSSECC().
18462 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18463 if (Subtarget->hasAVX512()) {
18464 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18465 CMP01, DAG.getConstant(x86cc, MVT::i8));
18466 if (N->getValueType(0) != MVT::i1)
18467 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18471 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18472 CMP00.getValueType(), CMP00, CMP01,
18473 DAG.getConstant(x86cc, MVT::i8));
18475 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18476 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18478 if (is64BitFP && !Subtarget->is64Bit()) {
18479 // On a 32-bit target, we cannot bitcast the 64-bit float to a
18480 // 64-bit integer, since that's not a legal type. Since
18481 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18482 // bits, but can do this little dance to extract the lowest 32 bits
18483 // and work with those going forward.
18484 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18486 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18488 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18489 Vector32, DAG.getIntPtrConstant(0));
18493 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18494 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18495 DAG.getConstant(1, IntVT));
18496 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18497 return OneBitOfTruth;
18505 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18506 /// so it can be folded inside ANDNP.
18507 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18508 EVT VT = N->getValueType(0);
18510 // Match direct AllOnes for 128 and 256-bit vectors
18511 if (ISD::isBuildVectorAllOnes(N))
18514 // Look through a bit convert.
18515 if (N->getOpcode() == ISD::BITCAST)
18516 N = N->getOperand(0).getNode();
18518 // Sometimes the operand may come from a insert_subvector building a 256-bit
18520 if (VT.is256BitVector() &&
18521 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18522 SDValue V1 = N->getOperand(0);
18523 SDValue V2 = N->getOperand(1);
18525 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18526 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18527 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18528 ISD::isBuildVectorAllOnes(V2.getNode()))
18535 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18536 // register. In most cases we actually compare or select YMM-sized registers
18537 // and mixing the two types creates horrible code. This method optimizes
18538 // some of the transition sequences.
18539 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18540 TargetLowering::DAGCombinerInfo &DCI,
18541 const X86Subtarget *Subtarget) {
18542 EVT VT = N->getValueType(0);
18543 if (!VT.is256BitVector())
18546 assert((N->getOpcode() == ISD::ANY_EXTEND ||
18547 N->getOpcode() == ISD::ZERO_EXTEND ||
18548 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18550 SDValue Narrow = N->getOperand(0);
18551 EVT NarrowVT = Narrow->getValueType(0);
18552 if (!NarrowVT.is128BitVector())
18555 if (Narrow->getOpcode() != ISD::XOR &&
18556 Narrow->getOpcode() != ISD::AND &&
18557 Narrow->getOpcode() != ISD::OR)
18560 SDValue N0 = Narrow->getOperand(0);
18561 SDValue N1 = Narrow->getOperand(1);
18564 // The Left side has to be a trunc.
18565 if (N0.getOpcode() != ISD::TRUNCATE)
18568 // The type of the truncated inputs.
18569 EVT WideVT = N0->getOperand(0)->getValueType(0);
18573 // The right side has to be a 'trunc' or a constant vector.
18574 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18575 bool RHSConst = (isSplatVector(N1.getNode()) &&
18576 isa<ConstantSDNode>(N1->getOperand(0)));
18577 if (!RHSTrunc && !RHSConst)
18580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18582 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18585 // Set N0 and N1 to hold the inputs to the new wide operation.
18586 N0 = N0->getOperand(0);
18588 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18589 N1->getOperand(0));
18590 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18591 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18592 } else if (RHSTrunc) {
18593 N1 = N1->getOperand(0);
18596 // Generate the wide operation.
18597 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18598 unsigned Opcode = N->getOpcode();
18600 case ISD::ANY_EXTEND:
18602 case ISD::ZERO_EXTEND: {
18603 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18604 APInt Mask = APInt::getAllOnesValue(InBits);
18605 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18606 return DAG.getNode(ISD::AND, DL, VT,
18607 Op, DAG.getConstant(Mask, VT));
18609 case ISD::SIGN_EXTEND:
18610 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18611 Op, DAG.getValueType(NarrowVT));
18613 llvm_unreachable("Unexpected opcode");
18617 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18618 TargetLowering::DAGCombinerInfo &DCI,
18619 const X86Subtarget *Subtarget) {
18620 EVT VT = N->getValueType(0);
18621 if (DCI.isBeforeLegalizeOps())
18624 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18628 // Create BEXTR instructions
18629 // BEXTR is ((X >> imm) & (2**size-1))
18630 if (VT == MVT::i32 || VT == MVT::i64) {
18631 SDValue N0 = N->getOperand(0);
18632 SDValue N1 = N->getOperand(1);
18635 // Check for BEXTR.
18636 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18637 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18638 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18639 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18640 if (MaskNode && ShiftNode) {
18641 uint64_t Mask = MaskNode->getZExtValue();
18642 uint64_t Shift = ShiftNode->getZExtValue();
18643 if (isMask_64(Mask)) {
18644 uint64_t MaskSize = CountPopulation_64(Mask);
18645 if (Shift + MaskSize <= VT.getSizeInBits())
18646 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18647 DAG.getConstant(Shift | (MaskSize << 8), VT));
18655 // Want to form ANDNP nodes:
18656 // 1) In the hopes of then easily combining them with OR and AND nodes
18657 // to form PBLEND/PSIGN.
18658 // 2) To match ANDN packed intrinsics
18659 if (VT != MVT::v2i64 && VT != MVT::v4i64)
18662 SDValue N0 = N->getOperand(0);
18663 SDValue N1 = N->getOperand(1);
18666 // Check LHS for vnot
18667 if (N0.getOpcode() == ISD::XOR &&
18668 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18669 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18670 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18672 // Check RHS for vnot
18673 if (N1.getOpcode() == ISD::XOR &&
18674 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18675 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18676 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18681 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18682 TargetLowering::DAGCombinerInfo &DCI,
18683 const X86Subtarget *Subtarget) {
18684 if (DCI.isBeforeLegalizeOps())
18687 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18691 SDValue N0 = N->getOperand(0);
18692 SDValue N1 = N->getOperand(1);
18693 EVT VT = N->getValueType(0);
18695 // look for psign/blend
18696 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18697 if (!Subtarget->hasSSSE3() ||
18698 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18701 // Canonicalize pandn to RHS
18702 if (N0.getOpcode() == X86ISD::ANDNP)
18704 // or (and (m, y), (pandn m, x))
18705 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18706 SDValue Mask = N1.getOperand(0);
18707 SDValue X = N1.getOperand(1);
18709 if (N0.getOperand(0) == Mask)
18710 Y = N0.getOperand(1);
18711 if (N0.getOperand(1) == Mask)
18712 Y = N0.getOperand(0);
18714 // Check to see if the mask appeared in both the AND and ANDNP and
18718 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18719 // Look through mask bitcast.
18720 if (Mask.getOpcode() == ISD::BITCAST)
18721 Mask = Mask.getOperand(0);
18722 if (X.getOpcode() == ISD::BITCAST)
18723 X = X.getOperand(0);
18724 if (Y.getOpcode() == ISD::BITCAST)
18725 Y = Y.getOperand(0);
18727 EVT MaskVT = Mask.getValueType();
18729 // Validate that the Mask operand is a vector sra node.
18730 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18731 // there is no psrai.b
18732 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18733 unsigned SraAmt = ~0;
18734 if (Mask.getOpcode() == ISD::SRA) {
18735 SDValue Amt = Mask.getOperand(1);
18736 if (isSplatVector(Amt.getNode())) {
18737 SDValue SclrAmt = Amt->getOperand(0);
18738 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18739 SraAmt = C->getZExtValue();
18741 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18742 SDValue SraC = Mask.getOperand(1);
18743 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
18745 if ((SraAmt + 1) != EltBits)
18750 // Now we know we at least have a plendvb with the mask val. See if
18751 // we can form a psignb/w/d.
18752 // psign = x.type == y.type == mask.type && y = sub(0, x);
18753 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18754 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18755 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18756 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18757 "Unsupported VT for PSIGN");
18758 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18759 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18761 // PBLENDVB only available on SSE 4.1
18762 if (!Subtarget->hasSSE41())
18765 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18767 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18768 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18769 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18770 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18771 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18775 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18778 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18779 MachineFunction &MF = DAG.getMachineFunction();
18780 bool OptForSize = MF.getFunction()->getAttributes().
18781 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18783 // SHLD/SHRD instructions have lower register pressure, but on some
18784 // platforms they have higher latency than the equivalent
18785 // series of shifts/or that would otherwise be generated.
18786 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18787 // have higher latencies and we are not optimizing for size.
18788 if (!OptForSize && Subtarget->isSHLDSlow())
18791 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18793 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18795 if (!N0.hasOneUse() || !N1.hasOneUse())
18798 SDValue ShAmt0 = N0.getOperand(1);
18799 if (ShAmt0.getValueType() != MVT::i8)
18801 SDValue ShAmt1 = N1.getOperand(1);
18802 if (ShAmt1.getValueType() != MVT::i8)
18804 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18805 ShAmt0 = ShAmt0.getOperand(0);
18806 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18807 ShAmt1 = ShAmt1.getOperand(0);
18810 unsigned Opc = X86ISD::SHLD;
18811 SDValue Op0 = N0.getOperand(0);
18812 SDValue Op1 = N1.getOperand(0);
18813 if (ShAmt0.getOpcode() == ISD::SUB) {
18814 Opc = X86ISD::SHRD;
18815 std::swap(Op0, Op1);
18816 std::swap(ShAmt0, ShAmt1);
18819 unsigned Bits = VT.getSizeInBits();
18820 if (ShAmt1.getOpcode() == ISD::SUB) {
18821 SDValue Sum = ShAmt1.getOperand(0);
18822 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18823 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18824 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18825 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18826 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18827 return DAG.getNode(Opc, DL, VT,
18829 DAG.getNode(ISD::TRUNCATE, DL,
18832 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18833 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18835 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18836 return DAG.getNode(Opc, DL, VT,
18837 N0.getOperand(0), N1.getOperand(0),
18838 DAG.getNode(ISD::TRUNCATE, DL,
18845 // Generate NEG and CMOV for integer abs.
18846 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18847 EVT VT = N->getValueType(0);
18849 // Since X86 does not have CMOV for 8-bit integer, we don't convert
18850 // 8-bit integer abs to NEG and CMOV.
18851 if (VT.isInteger() && VT.getSizeInBits() == 8)
18854 SDValue N0 = N->getOperand(0);
18855 SDValue N1 = N->getOperand(1);
18858 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18859 // and change it to SUB and CMOV.
18860 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18861 N0.getOpcode() == ISD::ADD &&
18862 N0.getOperand(1) == N1 &&
18863 N1.getOpcode() == ISD::SRA &&
18864 N1.getOperand(0) == N0.getOperand(0))
18865 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18866 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18867 // Generate SUB & CMOV.
18868 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18869 DAG.getConstant(0, VT), N0.getOperand(0));
18871 SDValue Ops[] = { N0.getOperand(0), Neg,
18872 DAG.getConstant(X86::COND_GE, MVT::i8),
18873 SDValue(Neg.getNode(), 1) };
18874 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18879 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18880 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18881 TargetLowering::DAGCombinerInfo &DCI,
18882 const X86Subtarget *Subtarget) {
18883 if (DCI.isBeforeLegalizeOps())
18886 if (Subtarget->hasCMov()) {
18887 SDValue RV = performIntegerAbsCombine(N, DAG);
18895 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18896 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18897 TargetLowering::DAGCombinerInfo &DCI,
18898 const X86Subtarget *Subtarget) {
18899 LoadSDNode *Ld = cast<LoadSDNode>(N);
18900 EVT RegVT = Ld->getValueType(0);
18901 EVT MemVT = Ld->getMemoryVT();
18903 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18904 unsigned RegSz = RegVT.getSizeInBits();
18906 // On Sandybridge unaligned 256bit loads are inefficient.
18907 ISD::LoadExtType Ext = Ld->getExtensionType();
18908 unsigned Alignment = Ld->getAlignment();
18909 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18910 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18911 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18912 unsigned NumElems = RegVT.getVectorNumElements();
18916 SDValue Ptr = Ld->getBasePtr();
18917 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18919 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18921 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18922 Ld->getPointerInfo(), Ld->isVolatile(),
18923 Ld->isNonTemporal(), Ld->isInvariant(),
18925 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18926 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18927 Ld->getPointerInfo(), Ld->isVolatile(),
18928 Ld->isNonTemporal(), Ld->isInvariant(),
18929 std::min(16U, Alignment));
18930 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18932 Load2.getValue(1));
18934 SDValue NewVec = DAG.getUNDEF(RegVT);
18935 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18936 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18937 return DCI.CombineTo(N, NewVec, TF, true);
18940 // If this is a vector EXT Load then attempt to optimize it using a
18941 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18942 // expansion is still better than scalar code.
18943 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18944 // emit a shuffle and a arithmetic shift.
18945 // TODO: It is possible to support ZExt by zeroing the undef values
18946 // during the shuffle phase or after the shuffle.
18947 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18948 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18949 assert(MemVT != RegVT && "Cannot extend to the same type");
18950 assert(MemVT.isVector() && "Must load a vector from memory");
18952 unsigned NumElems = RegVT.getVectorNumElements();
18953 unsigned MemSz = MemVT.getSizeInBits();
18954 assert(RegSz > MemSz && "Register size must be greater than the mem size");
18956 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18959 // All sizes must be a power of two.
18960 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18963 // Attempt to load the original value using scalar loads.
18964 // Find the largest scalar type that divides the total loaded size.
18965 MVT SclrLoadTy = MVT::i8;
18966 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18967 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18968 MVT Tp = (MVT::SimpleValueType)tp;
18969 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18974 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18975 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18977 SclrLoadTy = MVT::f64;
18979 // Calculate the number of scalar loads that we need to perform
18980 // in order to load our vector from memory.
18981 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18982 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18985 unsigned loadRegZize = RegSz;
18986 if (Ext == ISD::SEXTLOAD && RegSz == 256)
18989 // Represent our vector as a sequence of elements which are the
18990 // largest scalar that we can load.
18991 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18992 loadRegZize/SclrLoadTy.getSizeInBits());
18994 // Represent the data using the same element type that is stored in
18995 // memory. In practice, we ''widen'' MemVT.
18997 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18998 loadRegZize/MemVT.getScalarType().getSizeInBits());
19000 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19001 "Invalid vector type");
19003 // We can't shuffle using an illegal type.
19004 if (!TLI.isTypeLegal(WideVecVT))
19007 SmallVector<SDValue, 8> Chains;
19008 SDValue Ptr = Ld->getBasePtr();
19009 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19010 TLI.getPointerTy());
19011 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19013 for (unsigned i = 0; i < NumLoads; ++i) {
19014 // Perform a single load.
19015 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19016 Ptr, Ld->getPointerInfo(),
19017 Ld->isVolatile(), Ld->isNonTemporal(),
19018 Ld->isInvariant(), Ld->getAlignment());
19019 Chains.push_back(ScalarLoad.getValue(1));
19020 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19021 // another round of DAGCombining.
19023 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19025 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19026 ScalarLoad, DAG.getIntPtrConstant(i));
19028 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19031 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19033 // Bitcast the loaded value to a vector of the original element type, in
19034 // the size of the target vector type.
19035 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19036 unsigned SizeRatio = RegSz/MemSz;
19038 if (Ext == ISD::SEXTLOAD) {
19039 // If we have SSE4.1 we can directly emit a VSEXT node.
19040 if (Subtarget->hasSSE41()) {
19041 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19042 return DCI.CombineTo(N, Sext, TF, true);
19045 // Otherwise we'll shuffle the small elements in the high bits of the
19046 // larger type and perform an arithmetic shift. If the shift is not legal
19047 // it's better to scalarize.
19048 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19051 // Redistribute the loaded elements into the different locations.
19052 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19053 for (unsigned i = 0; i != NumElems; ++i)
19054 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19056 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19057 DAG.getUNDEF(WideVecVT),
19060 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19062 // Build the arithmetic shift.
19063 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19064 MemVT.getVectorElementType().getSizeInBits();
19065 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19066 DAG.getConstant(Amt, RegVT));
19068 return DCI.CombineTo(N, Shuff, TF, true);
19071 // Redistribute the loaded elements into the different locations.
19072 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19073 for (unsigned i = 0; i != NumElems; ++i)
19074 ShuffleVec[i*SizeRatio] = i;
19076 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19077 DAG.getUNDEF(WideVecVT),
19080 // Bitcast to the requested type.
19081 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19082 // Replace the original load with the new sequence
19083 // and return the new chain.
19084 return DCI.CombineTo(N, Shuff, TF, true);
19090 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19091 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19092 const X86Subtarget *Subtarget) {
19093 StoreSDNode *St = cast<StoreSDNode>(N);
19094 EVT VT = St->getValue().getValueType();
19095 EVT StVT = St->getMemoryVT();
19097 SDValue StoredVal = St->getOperand(1);
19098 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19100 // If we are saving a concatenation of two XMM registers, perform two stores.
19101 // On Sandy Bridge, 256-bit memory operations are executed by two
19102 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19103 // memory operation.
19104 unsigned Alignment = St->getAlignment();
19105 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19106 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19107 StVT == VT && !IsAligned) {
19108 unsigned NumElems = VT.getVectorNumElements();
19112 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19113 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19115 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19116 SDValue Ptr0 = St->getBasePtr();
19117 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19119 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19120 St->getPointerInfo(), St->isVolatile(),
19121 St->isNonTemporal(), Alignment);
19122 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19123 St->getPointerInfo(), St->isVolatile(),
19124 St->isNonTemporal(),
19125 std::min(16U, Alignment));
19126 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19129 // Optimize trunc store (of multiple scalars) to shuffle and store.
19130 // First, pack all of the elements in one place. Next, store to memory
19131 // in fewer chunks.
19132 if (St->isTruncatingStore() && VT.isVector()) {
19133 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19134 unsigned NumElems = VT.getVectorNumElements();
19135 assert(StVT != VT && "Cannot truncate to the same type");
19136 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19137 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19139 // From, To sizes and ElemCount must be pow of two
19140 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19141 // We are going to use the original vector elt for storing.
19142 // Accumulated smaller vector elements must be a multiple of the store size.
19143 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19145 unsigned SizeRatio = FromSz / ToSz;
19147 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19149 // Create a type on which we perform the shuffle
19150 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19151 StVT.getScalarType(), NumElems*SizeRatio);
19153 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19155 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19156 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19157 for (unsigned i = 0; i != NumElems; ++i)
19158 ShuffleVec[i] = i * SizeRatio;
19160 // Can't shuffle using an illegal type.
19161 if (!TLI.isTypeLegal(WideVecVT))
19164 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19165 DAG.getUNDEF(WideVecVT),
19167 // At this point all of the data is stored at the bottom of the
19168 // register. We now need to save it to mem.
19170 // Find the largest store unit
19171 MVT StoreType = MVT::i8;
19172 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19173 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19174 MVT Tp = (MVT::SimpleValueType)tp;
19175 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19179 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19180 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19181 (64 <= NumElems * ToSz))
19182 StoreType = MVT::f64;
19184 // Bitcast the original vector into a vector of store-size units
19185 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19186 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19187 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19188 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19189 SmallVector<SDValue, 8> Chains;
19190 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19191 TLI.getPointerTy());
19192 SDValue Ptr = St->getBasePtr();
19194 // Perform one or more big stores into memory.
19195 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19196 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19197 StoreType, ShuffWide,
19198 DAG.getIntPtrConstant(i));
19199 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19200 St->getPointerInfo(), St->isVolatile(),
19201 St->isNonTemporal(), St->getAlignment());
19202 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19203 Chains.push_back(Ch);
19206 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19209 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
19210 // the FP state in cases where an emms may be missing.
19211 // A preferable solution to the general problem is to figure out the right
19212 // places to insert EMMS. This qualifies as a quick hack.
19214 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19215 if (VT.getSizeInBits() != 64)
19218 const Function *F = DAG.getMachineFunction().getFunction();
19219 bool NoImplicitFloatOps = F->getAttributes().
19220 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19221 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19222 && Subtarget->hasSSE2();
19223 if ((VT.isVector() ||
19224 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19225 isa<LoadSDNode>(St->getValue()) &&
19226 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19227 St->getChain().hasOneUse() && !St->isVolatile()) {
19228 SDNode* LdVal = St->getValue().getNode();
19229 LoadSDNode *Ld = nullptr;
19230 int TokenFactorIndex = -1;
19231 SmallVector<SDValue, 8> Ops;
19232 SDNode* ChainVal = St->getChain().getNode();
19233 // Must be a store of a load. We currently handle two cases: the load
19234 // is a direct child, and it's under an intervening TokenFactor. It is
19235 // possible to dig deeper under nested TokenFactors.
19236 if (ChainVal == LdVal)
19237 Ld = cast<LoadSDNode>(St->getChain());
19238 else if (St->getValue().hasOneUse() &&
19239 ChainVal->getOpcode() == ISD::TokenFactor) {
19240 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19241 if (ChainVal->getOperand(i).getNode() == LdVal) {
19242 TokenFactorIndex = i;
19243 Ld = cast<LoadSDNode>(St->getValue());
19245 Ops.push_back(ChainVal->getOperand(i));
19249 if (!Ld || !ISD::isNormalLoad(Ld))
19252 // If this is not the MMX case, i.e. we are just turning i64 load/store
19253 // into f64 load/store, avoid the transformation if there are multiple
19254 // uses of the loaded value.
19255 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19260 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19261 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19263 if (Subtarget->is64Bit() || F64IsLegal) {
19264 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19265 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19266 Ld->getPointerInfo(), Ld->isVolatile(),
19267 Ld->isNonTemporal(), Ld->isInvariant(),
19268 Ld->getAlignment());
19269 SDValue NewChain = NewLd.getValue(1);
19270 if (TokenFactorIndex != -1) {
19271 Ops.push_back(NewChain);
19272 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19274 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19275 St->getPointerInfo(),
19276 St->isVolatile(), St->isNonTemporal(),
19277 St->getAlignment());
19280 // Otherwise, lower to two pairs of 32-bit loads / stores.
19281 SDValue LoAddr = Ld->getBasePtr();
19282 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19283 DAG.getConstant(4, MVT::i32));
19285 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19286 Ld->getPointerInfo(),
19287 Ld->isVolatile(), Ld->isNonTemporal(),
19288 Ld->isInvariant(), Ld->getAlignment());
19289 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19290 Ld->getPointerInfo().getWithOffset(4),
19291 Ld->isVolatile(), Ld->isNonTemporal(),
19293 MinAlign(Ld->getAlignment(), 4));
19295 SDValue NewChain = LoLd.getValue(1);
19296 if (TokenFactorIndex != -1) {
19297 Ops.push_back(LoLd);
19298 Ops.push_back(HiLd);
19299 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19302 LoAddr = St->getBasePtr();
19303 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19304 DAG.getConstant(4, MVT::i32));
19306 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19307 St->getPointerInfo(),
19308 St->isVolatile(), St->isNonTemporal(),
19309 St->getAlignment());
19310 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19311 St->getPointerInfo().getWithOffset(4),
19313 St->isNonTemporal(),
19314 MinAlign(St->getAlignment(), 4));
19315 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19320 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19321 /// and return the operands for the horizontal operation in LHS and RHS. A
19322 /// horizontal operation performs the binary operation on successive elements
19323 /// of its first operand, then on successive elements of its second operand,
19324 /// returning the resulting values in a vector. For example, if
19325 /// A = < float a0, float a1, float a2, float a3 >
19327 /// B = < float b0, float b1, float b2, float b3 >
19328 /// then the result of doing a horizontal operation on A and B is
19329 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19330 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19331 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19332 /// set to A, RHS to B, and the routine returns 'true'.
19333 /// Note that the binary operation should have the property that if one of the
19334 /// operands is UNDEF then the result is UNDEF.
19335 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19336 // Look for the following pattern: if
19337 // A = < float a0, float a1, float a2, float a3 >
19338 // B = < float b0, float b1, float b2, float b3 >
19340 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19341 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19342 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19343 // which is A horizontal-op B.
19345 // At least one of the operands should be a vector shuffle.
19346 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19347 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19350 MVT VT = LHS.getSimpleValueType();
19352 assert((VT.is128BitVector() || VT.is256BitVector()) &&
19353 "Unsupported vector type for horizontal add/sub");
19355 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19356 // operate independently on 128-bit lanes.
19357 unsigned NumElts = VT.getVectorNumElements();
19358 unsigned NumLanes = VT.getSizeInBits()/128;
19359 unsigned NumLaneElts = NumElts / NumLanes;
19360 assert((NumLaneElts % 2 == 0) &&
19361 "Vector type should have an even number of elements in each lane");
19362 unsigned HalfLaneElts = NumLaneElts/2;
19364 // View LHS in the form
19365 // LHS = VECTOR_SHUFFLE A, B, LMask
19366 // If LHS is not a shuffle then pretend it is the shuffle
19367 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19368 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19371 SmallVector<int, 16> LMask(NumElts);
19372 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19373 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19374 A = LHS.getOperand(0);
19375 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19376 B = LHS.getOperand(1);
19377 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19378 std::copy(Mask.begin(), Mask.end(), LMask.begin());
19380 if (LHS.getOpcode() != ISD::UNDEF)
19382 for (unsigned i = 0; i != NumElts; ++i)
19386 // Likewise, view RHS in the form
19387 // RHS = VECTOR_SHUFFLE C, D, RMask
19389 SmallVector<int, 16> RMask(NumElts);
19390 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19391 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19392 C = RHS.getOperand(0);
19393 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19394 D = RHS.getOperand(1);
19395 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19396 std::copy(Mask.begin(), Mask.end(), RMask.begin());
19398 if (RHS.getOpcode() != ISD::UNDEF)
19400 for (unsigned i = 0; i != NumElts; ++i)
19404 // Check that the shuffles are both shuffling the same vectors.
19405 if (!(A == C && B == D) && !(A == D && B == C))
19408 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19409 if (!A.getNode() && !B.getNode())
19412 // If A and B occur in reverse order in RHS, then "swap" them (which means
19413 // rewriting the mask).
19415 CommuteVectorShuffleMask(RMask, NumElts);
19417 // At this point LHS and RHS are equivalent to
19418 // LHS = VECTOR_SHUFFLE A, B, LMask
19419 // RHS = VECTOR_SHUFFLE A, B, RMask
19420 // Check that the masks correspond to performing a horizontal operation.
19421 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19422 for (unsigned i = 0; i != NumLaneElts; ++i) {
19423 int LIdx = LMask[i+l], RIdx = RMask[i+l];
19425 // Ignore any UNDEF components.
19426 if (LIdx < 0 || RIdx < 0 ||
19427 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19428 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19431 // Check that successive elements are being operated on. If not, this is
19432 // not a horizontal operation.
19433 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19434 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19435 if (!(LIdx == Index && RIdx == Index + 1) &&
19436 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19441 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19442 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19446 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19447 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19448 const X86Subtarget *Subtarget) {
19449 EVT VT = N->getValueType(0);
19450 SDValue LHS = N->getOperand(0);
19451 SDValue RHS = N->getOperand(1);
19453 // Try to synthesize horizontal adds from adds of shuffles.
19454 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19455 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19456 isHorizontalBinOp(LHS, RHS, true))
19457 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19461 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19462 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19463 const X86Subtarget *Subtarget) {
19464 EVT VT = N->getValueType(0);
19465 SDValue LHS = N->getOperand(0);
19466 SDValue RHS = N->getOperand(1);
19468 // Try to synthesize horizontal subs from subs of shuffles.
19469 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19470 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19471 isHorizontalBinOp(LHS, RHS, false))
19472 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19476 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19477 /// X86ISD::FXOR nodes.
19478 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19479 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19480 // F[X]OR(0.0, x) -> x
19481 // F[X]OR(x, 0.0) -> x
19482 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19483 if (C->getValueAPF().isPosZero())
19484 return N->getOperand(1);
19485 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19486 if (C->getValueAPF().isPosZero())
19487 return N->getOperand(0);
19491 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19492 /// X86ISD::FMAX nodes.
19493 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19494 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19496 // Only perform optimizations if UnsafeMath is used.
19497 if (!DAG.getTarget().Options.UnsafeFPMath)
19500 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19501 // into FMINC and FMAXC, which are Commutative operations.
19502 unsigned NewOp = 0;
19503 switch (N->getOpcode()) {
19504 default: llvm_unreachable("unknown opcode");
19505 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
19506 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
19509 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19510 N->getOperand(0), N->getOperand(1));
19513 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19514 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19515 // FAND(0.0, x) -> 0.0
19516 // FAND(x, 0.0) -> 0.0
19517 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19518 if (C->getValueAPF().isPosZero())
19519 return N->getOperand(0);
19520 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19521 if (C->getValueAPF().isPosZero())
19522 return N->getOperand(1);
19526 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19527 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19528 // FANDN(x, 0.0) -> 0.0
19529 // FANDN(0.0, x) -> x
19530 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19531 if (C->getValueAPF().isPosZero())
19532 return N->getOperand(1);
19533 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19534 if (C->getValueAPF().isPosZero())
19535 return N->getOperand(1);
19539 static SDValue PerformBTCombine(SDNode *N,
19541 TargetLowering::DAGCombinerInfo &DCI) {
19542 // BT ignores high bits in the bit index operand.
19543 SDValue Op1 = N->getOperand(1);
19544 if (Op1.hasOneUse()) {
19545 unsigned BitWidth = Op1.getValueSizeInBits();
19546 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19547 APInt KnownZero, KnownOne;
19548 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19549 !DCI.isBeforeLegalizeOps());
19550 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19551 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19552 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19553 DCI.CommitTargetLoweringOpt(TLO);
19558 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19559 SDValue Op = N->getOperand(0);
19560 if (Op.getOpcode() == ISD::BITCAST)
19561 Op = Op.getOperand(0);
19562 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19563 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19564 VT.getVectorElementType().getSizeInBits() ==
19565 OpVT.getVectorElementType().getSizeInBits()) {
19566 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19571 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19572 const X86Subtarget *Subtarget) {
19573 EVT VT = N->getValueType(0);
19574 if (!VT.isVector())
19577 SDValue N0 = N->getOperand(0);
19578 SDValue N1 = N->getOperand(1);
19579 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19582 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19583 // both SSE and AVX2 since there is no sign-extended shift right
19584 // operation on a vector with 64-bit elements.
19585 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19586 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19587 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19588 N0.getOpcode() == ISD::SIGN_EXTEND)) {
19589 SDValue N00 = N0.getOperand(0);
19591 // EXTLOAD has a better solution on AVX2,
19592 // it may be replaced with X86ISD::VSEXT node.
19593 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19594 if (!ISD::isNormalLoad(N00.getNode()))
19597 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19598 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19600 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19606 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19607 TargetLowering::DAGCombinerInfo &DCI,
19608 const X86Subtarget *Subtarget) {
19609 if (!DCI.isBeforeLegalizeOps())
19612 if (!Subtarget->hasFp256())
19615 EVT VT = N->getValueType(0);
19616 if (VT.isVector() && VT.getSizeInBits() == 256) {
19617 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19625 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19626 const X86Subtarget* Subtarget) {
19628 EVT VT = N->getValueType(0);
19630 // Let legalize expand this if it isn't a legal type yet.
19631 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19634 EVT ScalarVT = VT.getScalarType();
19635 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19636 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19639 SDValue A = N->getOperand(0);
19640 SDValue B = N->getOperand(1);
19641 SDValue C = N->getOperand(2);
19643 bool NegA = (A.getOpcode() == ISD::FNEG);
19644 bool NegB = (B.getOpcode() == ISD::FNEG);
19645 bool NegC = (C.getOpcode() == ISD::FNEG);
19647 // Negative multiplication when NegA xor NegB
19648 bool NegMul = (NegA != NegB);
19650 A = A.getOperand(0);
19652 B = B.getOperand(0);
19654 C = C.getOperand(0);
19658 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19660 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19662 return DAG.getNode(Opcode, dl, VT, A, B, C);
19665 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19666 TargetLowering::DAGCombinerInfo &DCI,
19667 const X86Subtarget *Subtarget) {
19668 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
19669 // (and (i32 x86isd::setcc_carry), 1)
19670 // This eliminates the zext. This transformation is necessary because
19671 // ISD::SETCC is always legalized to i8.
19673 SDValue N0 = N->getOperand(0);
19674 EVT VT = N->getValueType(0);
19676 if (N0.getOpcode() == ISD::AND &&
19678 N0.getOperand(0).hasOneUse()) {
19679 SDValue N00 = N0.getOperand(0);
19680 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19681 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19682 if (!C || C->getZExtValue() != 1)
19684 return DAG.getNode(ISD::AND, dl, VT,
19685 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19686 N00.getOperand(0), N00.getOperand(1)),
19687 DAG.getConstant(1, VT));
19691 if (N0.getOpcode() == ISD::TRUNCATE &&
19693 N0.getOperand(0).hasOneUse()) {
19694 SDValue N00 = N0.getOperand(0);
19695 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19696 return DAG.getNode(ISD::AND, dl, VT,
19697 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19698 N00.getOperand(0), N00.getOperand(1)),
19699 DAG.getConstant(1, VT));
19702 if (VT.is256BitVector()) {
19703 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19711 // Optimize x == -y --> x+y == 0
19712 // x != -y --> x+y != 0
19713 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19714 const X86Subtarget* Subtarget) {
19715 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19716 SDValue LHS = N->getOperand(0);
19717 SDValue RHS = N->getOperand(1);
19718 EVT VT = N->getValueType(0);
19721 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19722 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19723 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19724 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19725 LHS.getValueType(), RHS, LHS.getOperand(1));
19726 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19727 addV, DAG.getConstant(0, addV.getValueType()), CC);
19729 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19730 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19731 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19732 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19733 RHS.getValueType(), LHS, RHS.getOperand(1));
19734 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19735 addV, DAG.getConstant(0, addV.getValueType()), CC);
19738 if (VT.getScalarType() == MVT::i1) {
19739 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19740 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19741 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19742 if (!IsSEXT0 && !IsVZero0)
19744 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19745 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
19746 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19748 if (!IsSEXT1 && !IsVZero1)
19751 if (IsSEXT0 && IsVZero1) {
19752 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19753 if (CC == ISD::SETEQ)
19754 return DAG.getNOT(DL, LHS.getOperand(0), VT);
19755 return LHS.getOperand(0);
19757 if (IsSEXT1 && IsVZero0) {
19758 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19759 if (CC == ISD::SETEQ)
19760 return DAG.getNOT(DL, RHS.getOperand(0), VT);
19761 return RHS.getOperand(0);
19768 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19769 // as "sbb reg,reg", since it can be extended without zext and produces
19770 // an all-ones bit which is more useful than 0/1 in some cases.
19771 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19774 return DAG.getNode(ISD::AND, DL, VT,
19775 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19776 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19777 DAG.getConstant(1, VT));
19778 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19779 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19780 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19781 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19784 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19785 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19786 TargetLowering::DAGCombinerInfo &DCI,
19787 const X86Subtarget *Subtarget) {
19789 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19790 SDValue EFLAGS = N->getOperand(1);
19792 if (CC == X86::COND_A) {
19793 // Try to convert COND_A into COND_B in an attempt to facilitate
19794 // materializing "setb reg".
19796 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19797 // cannot take an immediate as its first operand.
19799 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19800 EFLAGS.getValueType().isInteger() &&
19801 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19802 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19803 EFLAGS.getNode()->getVTList(),
19804 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19805 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19806 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19810 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19811 // a zext and produces an all-ones bit which is more useful than 0/1 in some
19813 if (CC == X86::COND_B)
19814 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19818 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19819 if (Flags.getNode()) {
19820 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19821 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19827 // Optimize branch condition evaluation.
19829 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19830 TargetLowering::DAGCombinerInfo &DCI,
19831 const X86Subtarget *Subtarget) {
19833 SDValue Chain = N->getOperand(0);
19834 SDValue Dest = N->getOperand(1);
19835 SDValue EFLAGS = N->getOperand(3);
19836 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19840 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19841 if (Flags.getNode()) {
19842 SDValue Cond = DAG.getConstant(CC, MVT::i8);
19843 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19850 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19851 const X86TargetLowering *XTLI) {
19852 SDValue Op0 = N->getOperand(0);
19853 EVT InVT = Op0->getValueType(0);
19855 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19856 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19858 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19859 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19860 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19863 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19864 // a 32-bit target where SSE doesn't support i64->FP operations.
19865 if (Op0.getOpcode() == ISD::LOAD) {
19866 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19867 EVT VT = Ld->getValueType(0);
19868 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19869 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19870 !XTLI->getSubtarget()->is64Bit() &&
19872 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19873 Ld->getChain(), Op0, DAG);
19874 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19881 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19882 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19883 X86TargetLowering::DAGCombinerInfo &DCI) {
19884 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19885 // the result is either zero or one (depending on the input carry bit).
19886 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19887 if (X86::isZeroNode(N->getOperand(0)) &&
19888 X86::isZeroNode(N->getOperand(1)) &&
19889 // We don't have a good way to replace an EFLAGS use, so only do this when
19891 SDValue(N, 1).use_empty()) {
19893 EVT VT = N->getValueType(0);
19894 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19895 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19896 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19897 DAG.getConstant(X86::COND_B,MVT::i8),
19899 DAG.getConstant(1, VT));
19900 return DCI.CombineTo(N, Res1, CarryOut);
19906 // fold (add Y, (sete X, 0)) -> adc 0, Y
19907 // (add Y, (setne X, 0)) -> sbb -1, Y
19908 // (sub (sete X, 0), Y) -> sbb 0, Y
19909 // (sub (setne X, 0), Y) -> adc -1, Y
19910 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19913 // Look through ZExts.
19914 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19915 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19918 SDValue SetCC = Ext.getOperand(0);
19919 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19922 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19923 if (CC != X86::COND_E && CC != X86::COND_NE)
19926 SDValue Cmp = SetCC.getOperand(1);
19927 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19928 !X86::isZeroNode(Cmp.getOperand(1)) ||
19929 !Cmp.getOperand(0).getValueType().isInteger())
19932 SDValue CmpOp0 = Cmp.getOperand(0);
19933 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19934 DAG.getConstant(1, CmpOp0.getValueType()));
19936 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19937 if (CC == X86::COND_NE)
19938 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19939 DL, OtherVal.getValueType(), OtherVal,
19940 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19941 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19942 DL, OtherVal.getValueType(), OtherVal,
19943 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19946 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19947 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19948 const X86Subtarget *Subtarget) {
19949 EVT VT = N->getValueType(0);
19950 SDValue Op0 = N->getOperand(0);
19951 SDValue Op1 = N->getOperand(1);
19953 // Try to synthesize horizontal adds from adds of shuffles.
19954 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19955 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19956 isHorizontalBinOp(Op0, Op1, true))
19957 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19959 return OptimizeConditionalInDecrement(N, DAG);
19962 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19963 const X86Subtarget *Subtarget) {
19964 SDValue Op0 = N->getOperand(0);
19965 SDValue Op1 = N->getOperand(1);
19967 // X86 can't encode an immediate LHS of a sub. See if we can push the
19968 // negation into a preceding instruction.
19969 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19970 // If the RHS of the sub is a XOR with one use and a constant, invert the
19971 // immediate. Then add one to the LHS of the sub so we can turn
19972 // X-Y -> X+~Y+1, saving one register.
19973 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19974 isa<ConstantSDNode>(Op1.getOperand(1))) {
19975 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19976 EVT VT = Op0.getValueType();
19977 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19979 DAG.getConstant(~XorC, VT));
19980 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19981 DAG.getConstant(C->getAPIntValue()+1, VT));
19985 // Try to synthesize horizontal adds from adds of shuffles.
19986 EVT VT = N->getValueType(0);
19987 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19988 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19989 isHorizontalBinOp(Op0, Op1, true))
19990 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19992 return OptimizeConditionalInDecrement(N, DAG);
19995 /// performVZEXTCombine - Performs build vector combines
19996 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19997 TargetLowering::DAGCombinerInfo &DCI,
19998 const X86Subtarget *Subtarget) {
19999 // (vzext (bitcast (vzext (x)) -> (vzext x)
20000 SDValue In = N->getOperand(0);
20001 while (In.getOpcode() == ISD::BITCAST)
20002 In = In.getOperand(0);
20004 if (In.getOpcode() != X86ISD::VZEXT)
20007 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20011 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20012 DAGCombinerInfo &DCI) const {
20013 SelectionDAG &DAG = DCI.DAG;
20014 switch (N->getOpcode()) {
20016 case ISD::EXTRACT_VECTOR_ELT:
20017 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20019 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20020 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20021 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
20022 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
20023 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
20024 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
20027 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
20028 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
20029 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
20030 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
20031 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
20032 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
20033 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
20034 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
20035 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
20037 case X86ISD::FOR: return PerformFORCombine(N, DAG);
20039 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
20040 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
20041 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
20042 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
20043 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
20044 case ISD::ANY_EXTEND:
20045 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
20046 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
20047 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20048 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20049 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
20050 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20051 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20052 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
20053 case X86ISD::SHUFP: // Handle all target specific shuffles
20054 case X86ISD::PALIGNR:
20055 case X86ISD::UNPCKH:
20056 case X86ISD::UNPCKL:
20057 case X86ISD::MOVHLPS:
20058 case X86ISD::MOVLHPS:
20059 case X86ISD::PSHUFD:
20060 case X86ISD::PSHUFHW:
20061 case X86ISD::PSHUFLW:
20062 case X86ISD::MOVSS:
20063 case X86ISD::MOVSD:
20064 case X86ISD::VPERMILP:
20065 case X86ISD::VPERM2X128:
20066 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20067 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
20073 /// isTypeDesirableForOp - Return true if the target has native support for
20074 /// the specified value type and it is 'desirable' to use the type for the
20075 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20076 /// instruction encodings are longer and some i16 instructions are slow.
20077 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20078 if (!isTypeLegal(VT))
20080 if (VT != MVT::i16)
20087 case ISD::SIGN_EXTEND:
20088 case ISD::ZERO_EXTEND:
20089 case ISD::ANY_EXTEND:
20102 /// IsDesirableToPromoteOp - This method query the target whether it is
20103 /// beneficial for dag combiner to promote the specified node. If true, it
20104 /// should return the desired promotion type by reference.
20105 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20106 EVT VT = Op.getValueType();
20107 if (VT != MVT::i16)
20110 bool Promote = false;
20111 bool Commute = false;
20112 switch (Op.getOpcode()) {
20115 LoadSDNode *LD = cast<LoadSDNode>(Op);
20116 // If the non-extending load has a single use and it's not live out, then it
20117 // might be folded.
20118 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20119 Op.hasOneUse()*/) {
20120 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20121 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20122 // The only case where we'd want to promote LOAD (rather then it being
20123 // promoted as an operand is when it's only use is liveout.
20124 if (UI->getOpcode() != ISD::CopyToReg)
20131 case ISD::SIGN_EXTEND:
20132 case ISD::ZERO_EXTEND:
20133 case ISD::ANY_EXTEND:
20138 SDValue N0 = Op.getOperand(0);
20139 // Look out for (store (shl (load), x)).
20140 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20153 SDValue N0 = Op.getOperand(0);
20154 SDValue N1 = Op.getOperand(1);
20155 if (!Commute && MayFoldLoad(N1))
20157 // Avoid disabling potential load folding opportunities.
20158 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20160 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20170 //===----------------------------------------------------------------------===//
20171 // X86 Inline Assembly Support
20172 //===----------------------------------------------------------------------===//
20175 // Helper to match a string separated by whitespace.
20176 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20177 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20179 for (unsigned i = 0, e = args.size(); i != e; ++i) {
20180 StringRef piece(*args[i]);
20181 if (!s.startswith(piece)) // Check if the piece matches.
20184 s = s.substr(piece.size());
20185 StringRef::size_type pos = s.find_first_not_of(" \t");
20186 if (pos == 0) // We matched a prefix.
20194 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20197 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20199 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20200 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20201 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20202 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20204 if (AsmPieces.size() == 3)
20206 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20213 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20214 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20216 std::string AsmStr = IA->getAsmString();
20218 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20219 if (!Ty || Ty->getBitWidth() % 16 != 0)
20222 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20223 SmallVector<StringRef, 4> AsmPieces;
20224 SplitString(AsmStr, AsmPieces, ";\n");
20226 switch (AsmPieces.size()) {
20227 default: return false;
20229 // FIXME: this should verify that we are targeting a 486 or better. If not,
20230 // we will turn this bswap into something that will be lowered to logical
20231 // ops instead of emitting the bswap asm. For now, we don't support 486 or
20232 // lower so don't worry about this.
20234 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20235 matchAsm(AsmPieces[0], "bswapl", "$0") ||
20236 matchAsm(AsmPieces[0], "bswapq", "$0") ||
20237 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20238 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20239 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20240 // No need to check constraints, nothing other than the equivalent of
20241 // "=r,0" would be valid here.
20242 return IntrinsicLowering::LowerToByteSwap(CI);
20245 // rorw $$8, ${0:w} --> llvm.bswap.i16
20246 if (CI->getType()->isIntegerTy(16) &&
20247 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20248 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20249 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20251 const std::string &ConstraintsStr = IA->getConstraintString();
20252 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20253 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20254 if (clobbersFlagRegisters(AsmPieces))
20255 return IntrinsicLowering::LowerToByteSwap(CI);
20259 if (CI->getType()->isIntegerTy(32) &&
20260 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20261 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20262 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20263 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20265 const std::string &ConstraintsStr = IA->getConstraintString();
20266 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20267 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20268 if (clobbersFlagRegisters(AsmPieces))
20269 return IntrinsicLowering::LowerToByteSwap(CI);
20272 if (CI->getType()->isIntegerTy(64)) {
20273 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20274 if (Constraints.size() >= 2 &&
20275 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20276 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20277 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
20278 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20279 matchAsm(AsmPieces[1], "bswap", "%edx") &&
20280 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20281 return IntrinsicLowering::LowerToByteSwap(CI);
20289 /// getConstraintType - Given a constraint letter, return the type of
20290 /// constraint it is for this target.
20291 X86TargetLowering::ConstraintType
20292 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20293 if (Constraint.size() == 1) {
20294 switch (Constraint[0]) {
20305 return C_RegisterClass;
20329 return TargetLowering::getConstraintType(Constraint);
20332 /// Examine constraint type and operand type and determine a weight value.
20333 /// This object must already have been set up with the operand type
20334 /// and the current alternative constraint selected.
20335 TargetLowering::ConstraintWeight
20336 X86TargetLowering::getSingleConstraintMatchWeight(
20337 AsmOperandInfo &info, const char *constraint) const {
20338 ConstraintWeight weight = CW_Invalid;
20339 Value *CallOperandVal = info.CallOperandVal;
20340 // If we don't have a value, we can't do a match,
20341 // but allow it at the lowest weight.
20342 if (!CallOperandVal)
20344 Type *type = CallOperandVal->getType();
20345 // Look at the constraint type.
20346 switch (*constraint) {
20348 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20359 if (CallOperandVal->getType()->isIntegerTy())
20360 weight = CW_SpecificReg;
20365 if (type->isFloatingPointTy())
20366 weight = CW_SpecificReg;
20369 if (type->isX86_MMXTy() && Subtarget->hasMMX())
20370 weight = CW_SpecificReg;
20374 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20375 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20376 weight = CW_Register;
20379 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20380 if (C->getZExtValue() <= 31)
20381 weight = CW_Constant;
20385 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20386 if (C->getZExtValue() <= 63)
20387 weight = CW_Constant;
20391 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20392 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20393 weight = CW_Constant;
20397 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20398 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20399 weight = CW_Constant;
20403 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20404 if (C->getZExtValue() <= 3)
20405 weight = CW_Constant;
20409 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20410 if (C->getZExtValue() <= 0xff)
20411 weight = CW_Constant;
20416 if (dyn_cast<ConstantFP>(CallOperandVal)) {
20417 weight = CW_Constant;
20421 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20422 if ((C->getSExtValue() >= -0x80000000LL) &&
20423 (C->getSExtValue() <= 0x7fffffffLL))
20424 weight = CW_Constant;
20428 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20429 if (C->getZExtValue() <= 0xffffffff)
20430 weight = CW_Constant;
20437 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20438 /// with another that has more specific requirements based on the type of the
20439 /// corresponding operand.
20440 const char *X86TargetLowering::
20441 LowerXConstraint(EVT ConstraintVT) const {
20442 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20443 // 'f' like normal targets.
20444 if (ConstraintVT.isFloatingPoint()) {
20445 if (Subtarget->hasSSE2())
20447 if (Subtarget->hasSSE1())
20451 return TargetLowering::LowerXConstraint(ConstraintVT);
20454 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20455 /// vector. If it is invalid, don't add anything to Ops.
20456 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20457 std::string &Constraint,
20458 std::vector<SDValue>&Ops,
20459 SelectionDAG &DAG) const {
20462 // Only support length 1 constraints for now.
20463 if (Constraint.length() > 1) return;
20465 char ConstraintLetter = Constraint[0];
20466 switch (ConstraintLetter) {
20469 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20470 if (C->getZExtValue() <= 31) {
20471 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20477 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20478 if (C->getZExtValue() <= 63) {
20479 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20485 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20486 if (isInt<8>(C->getSExtValue())) {
20487 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20493 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20494 if (C->getZExtValue() <= 255) {
20495 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20501 // 32-bit signed value
20502 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20503 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20504 C->getSExtValue())) {
20505 // Widen to 64 bits here to get it sign extended.
20506 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20509 // FIXME gcc accepts some relocatable values here too, but only in certain
20510 // memory models; it's complicated.
20515 // 32-bit unsigned value
20516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20517 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20518 C->getZExtValue())) {
20519 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20523 // FIXME gcc accepts some relocatable values here too, but only in certain
20524 // memory models; it's complicated.
20528 // Literal immediates are always ok.
20529 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20530 // Widen to 64 bits here to get it sign extended.
20531 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20535 // In any sort of PIC mode addresses need to be computed at runtime by
20536 // adding in a register or some sort of table lookup. These can't
20537 // be used as immediates.
20538 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20541 // If we are in non-pic codegen mode, we allow the address of a global (with
20542 // an optional displacement) to be used with 'i'.
20543 GlobalAddressSDNode *GA = nullptr;
20544 int64_t Offset = 0;
20546 // Match either (GA), (GA+C), (GA+C1+C2), etc.
20548 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20549 Offset += GA->getOffset();
20551 } else if (Op.getOpcode() == ISD::ADD) {
20552 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20553 Offset += C->getZExtValue();
20554 Op = Op.getOperand(0);
20557 } else if (Op.getOpcode() == ISD::SUB) {
20558 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20559 Offset += -C->getZExtValue();
20560 Op = Op.getOperand(0);
20565 // Otherwise, this isn't something we can handle, reject it.
20569 const GlobalValue *GV = GA->getGlobal();
20570 // If we require an extra load to get this address, as in PIC mode, we
20571 // can't accept it.
20572 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20573 getTargetMachine())))
20576 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20577 GA->getValueType(0), Offset);
20582 if (Result.getNode()) {
20583 Ops.push_back(Result);
20586 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20589 std::pair<unsigned, const TargetRegisterClass*>
20590 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20592 // First, see if this is a constraint that directly corresponds to an LLVM
20594 if (Constraint.size() == 1) {
20595 // GCC Constraint Letters
20596 switch (Constraint[0]) {
20598 // TODO: Slight differences here in allocation order and leaving
20599 // RIP in the class. Do they matter any more here than they do
20600 // in the normal allocation?
20601 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20602 if (Subtarget->is64Bit()) {
20603 if (VT == MVT::i32 || VT == MVT::f32)
20604 return std::make_pair(0U, &X86::GR32RegClass);
20605 if (VT == MVT::i16)
20606 return std::make_pair(0U, &X86::GR16RegClass);
20607 if (VT == MVT::i8 || VT == MVT::i1)
20608 return std::make_pair(0U, &X86::GR8RegClass);
20609 if (VT == MVT::i64 || VT == MVT::f64)
20610 return std::make_pair(0U, &X86::GR64RegClass);
20613 // 32-bit fallthrough
20614 case 'Q': // Q_REGS
20615 if (VT == MVT::i32 || VT == MVT::f32)
20616 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20617 if (VT == MVT::i16)
20618 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20619 if (VT == MVT::i8 || VT == MVT::i1)
20620 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20621 if (VT == MVT::i64)
20622 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20624 case 'r': // GENERAL_REGS
20625 case 'l': // INDEX_REGS
20626 if (VT == MVT::i8 || VT == MVT::i1)
20627 return std::make_pair(0U, &X86::GR8RegClass);
20628 if (VT == MVT::i16)
20629 return std::make_pair(0U, &X86::GR16RegClass);
20630 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20631 return std::make_pair(0U, &X86::GR32RegClass);
20632 return std::make_pair(0U, &X86::GR64RegClass);
20633 case 'R': // LEGACY_REGS
20634 if (VT == MVT::i8 || VT == MVT::i1)
20635 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20636 if (VT == MVT::i16)
20637 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20638 if (VT == MVT::i32 || !Subtarget->is64Bit())
20639 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20640 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20641 case 'f': // FP Stack registers.
20642 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20643 // value to the correct fpstack register class.
20644 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20645 return std::make_pair(0U, &X86::RFP32RegClass);
20646 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20647 return std::make_pair(0U, &X86::RFP64RegClass);
20648 return std::make_pair(0U, &X86::RFP80RegClass);
20649 case 'y': // MMX_REGS if MMX allowed.
20650 if (!Subtarget->hasMMX()) break;
20651 return std::make_pair(0U, &X86::VR64RegClass);
20652 case 'Y': // SSE_REGS if SSE2 allowed
20653 if (!Subtarget->hasSSE2()) break;
20655 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20656 if (!Subtarget->hasSSE1()) break;
20658 switch (VT.SimpleTy) {
20660 // Scalar SSE types.
20663 return std::make_pair(0U, &X86::FR32RegClass);
20666 return std::make_pair(0U, &X86::FR64RegClass);
20674 return std::make_pair(0U, &X86::VR128RegClass);
20682 return std::make_pair(0U, &X86::VR256RegClass);
20687 return std::make_pair(0U, &X86::VR512RegClass);
20693 // Use the default implementation in TargetLowering to convert the register
20694 // constraint into a member of a register class.
20695 std::pair<unsigned, const TargetRegisterClass*> Res;
20696 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20698 // Not found as a standard register?
20700 // Map st(0) -> st(7) -> ST0
20701 if (Constraint.size() == 7 && Constraint[0] == '{' &&
20702 tolower(Constraint[1]) == 's' &&
20703 tolower(Constraint[2]) == 't' &&
20704 Constraint[3] == '(' &&
20705 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20706 Constraint[5] == ')' &&
20707 Constraint[6] == '}') {
20709 Res.first = X86::ST0+Constraint[4]-'0';
20710 Res.second = &X86::RFP80RegClass;
20714 // GCC allows "st(0)" to be called just plain "st".
20715 if (StringRef("{st}").equals_lower(Constraint)) {
20716 Res.first = X86::ST0;
20717 Res.second = &X86::RFP80RegClass;
20722 if (StringRef("{flags}").equals_lower(Constraint)) {
20723 Res.first = X86::EFLAGS;
20724 Res.second = &X86::CCRRegClass;
20728 // 'A' means EAX + EDX.
20729 if (Constraint == "A") {
20730 Res.first = X86::EAX;
20731 Res.second = &X86::GR32_ADRegClass;
20737 // Otherwise, check to see if this is a register class of the wrong value
20738 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20739 // turn into {ax},{dx}.
20740 if (Res.second->hasType(VT))
20741 return Res; // Correct type already, nothing to do.
20743 // All of the single-register GCC register classes map their values onto
20744 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
20745 // really want an 8-bit or 32-bit register, map to the appropriate register
20746 // class and return the appropriate register.
20747 if (Res.second == &X86::GR16RegClass) {
20748 if (VT == MVT::i8 || VT == MVT::i1) {
20749 unsigned DestReg = 0;
20750 switch (Res.first) {
20752 case X86::AX: DestReg = X86::AL; break;
20753 case X86::DX: DestReg = X86::DL; break;
20754 case X86::CX: DestReg = X86::CL; break;
20755 case X86::BX: DestReg = X86::BL; break;
20758 Res.first = DestReg;
20759 Res.second = &X86::GR8RegClass;
20761 } else if (VT == MVT::i32 || VT == MVT::f32) {
20762 unsigned DestReg = 0;
20763 switch (Res.first) {
20765 case X86::AX: DestReg = X86::EAX; break;
20766 case X86::DX: DestReg = X86::EDX; break;
20767 case X86::CX: DestReg = X86::ECX; break;
20768 case X86::BX: DestReg = X86::EBX; break;
20769 case X86::SI: DestReg = X86::ESI; break;
20770 case X86::DI: DestReg = X86::EDI; break;
20771 case X86::BP: DestReg = X86::EBP; break;
20772 case X86::SP: DestReg = X86::ESP; break;
20775 Res.first = DestReg;
20776 Res.second = &X86::GR32RegClass;
20778 } else if (VT == MVT::i64 || VT == MVT::f64) {
20779 unsigned DestReg = 0;
20780 switch (Res.first) {
20782 case X86::AX: DestReg = X86::RAX; break;
20783 case X86::DX: DestReg = X86::RDX; break;
20784 case X86::CX: DestReg = X86::RCX; break;
20785 case X86::BX: DestReg = X86::RBX; break;
20786 case X86::SI: DestReg = X86::RSI; break;
20787 case X86::DI: DestReg = X86::RDI; break;
20788 case X86::BP: DestReg = X86::RBP; break;
20789 case X86::SP: DestReg = X86::RSP; break;
20792 Res.first = DestReg;
20793 Res.second = &X86::GR64RegClass;
20796 } else if (Res.second == &X86::FR32RegClass ||
20797 Res.second == &X86::FR64RegClass ||
20798 Res.second == &X86::VR128RegClass ||
20799 Res.second == &X86::VR256RegClass ||
20800 Res.second == &X86::FR32XRegClass ||
20801 Res.second == &X86::FR64XRegClass ||
20802 Res.second == &X86::VR128XRegClass ||
20803 Res.second == &X86::VR256XRegClass ||
20804 Res.second == &X86::VR512RegClass) {
20805 // Handle references to XMM physical registers that got mapped into the
20806 // wrong class. This can happen with constraints like {xmm0} where the
20807 // target independent register mapper will just pick the first match it can
20808 // find, ignoring the required type.
20810 if (VT == MVT::f32 || VT == MVT::i32)
20811 Res.second = &X86::FR32RegClass;
20812 else if (VT == MVT::f64 || VT == MVT::i64)
20813 Res.second = &X86::FR64RegClass;
20814 else if (X86::VR128RegClass.hasType(VT))
20815 Res.second = &X86::VR128RegClass;
20816 else if (X86::VR256RegClass.hasType(VT))
20817 Res.second = &X86::VR256RegClass;
20818 else if (X86::VR512RegClass.hasType(VT))
20819 Res.second = &X86::VR512RegClass;
20825 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20827 // Scaling factors are not free at all.
20828 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20829 // will take 2 allocations instead of 1 for plain addressing mode,
20830 // i.e. inst (reg1).
20831 if (isLegalAddressingMode(AM, Ty))
20832 // Scale represents reg2 * scale, thus account for 1
20833 // as soon as we use a second register.
20834 return AM.Scale != 0;